context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Windows; using System.Windows.Input; using NCmdLiner.SolutionCreator.Library.Common.UI; using NCmdLiner.SolutionCreator.Library.Views; namespace NCmdLiner.SolutionCreator.Library.ViewModels { public class MainViewModel : ViewModelBase, IMainViewModel { public MainViewModel() { CompanyNameLabelText = "Company Name:"; NamespaceCompanyNameLabelText = "Namespace Company Name:"; ProductNameLabelText = "Product Name:"; ShortProductNameLabelText = "Short Product Name:"; ProductDescriptionLabelText = "Product Description:"; ConsoleProjectNameLabelText = "Console Project Name:"; LibraryProjectNameLabelText = "Library Project Name:"; TestsProjectNameLabelText = "Tests Project Name:"; SetupProjectNameLabelText = "Setup Project Name:"; ScriptInstallProjectNameLabelText = "Script Install Project Name:"; AuthorsLableText = "Authors:"; MaxLabelWidth = 200 ; OkCommand = new CommandHandler(this.Exit, true); } public static readonly DependencyProperty CompanyNameProperty = DependencyProperty.Register( "CompanyName", typeof(string), typeof(MainViewModel), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.AffectsMeasure, CompanyNameChanged)); private static void CompanyNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var viewModel = (MainViewModel)d; viewModel.NamespaceCompanyName = viewModel.CompanyName.Replace(" ", ""); viewModel.ScriptInstallProjectName = viewModel.CompanyName + " " + viewModel.ProductName + " %Version%"; CommandManager.InvalidateRequerySuggested(); } public string CompanyName { get { return (string)GetValue(CompanyNameProperty); } set { SetValue(CompanyNameProperty, value); } } public static readonly DependencyProperty CompanyNameLabelTextProperty = DependencyProperty.Register( "CompanyNameLabelText", typeof(string), typeof(MainViewModel), new PropertyMetadata(default(string))); public string CompanyNameLabelText { get { return (string)GetValue(CompanyNameLabelTextProperty); } set { SetValue(CompanyNameLabelTextProperty, value); } } public static readonly DependencyProperty NamespaceCompanyNameProperty = DependencyProperty.Register( "NamespaceCompanyName", typeof(string), typeof(MainViewModel), new PropertyMetadata(default(string))); public string NamespaceCompanyName { get { return (string)GetValue(NamespaceCompanyNameProperty); } set { SetValue(NamespaceCompanyNameProperty, value); } } public static readonly DependencyProperty NamespaceCompanyNameLabelTextProperty = DependencyProperty.Register( "NamespaceCompanyNameLabelText", typeof(string), typeof(MainViewModel), new PropertyMetadata(default(string))); public string NamespaceCompanyNameLabelText { get { return (string)GetValue(NamespaceCompanyNameLabelTextProperty); } set { SetValue(NamespaceCompanyNameLabelTextProperty, value); } } public static readonly DependencyProperty ProductNameProperty = DependencyProperty.Register( "ProductName", typeof(string), typeof(MainViewModel), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.AffectsMeasure, ProductNameChanged)); private static void ProductNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var viewModel = (MainViewModel)d; viewModel.ShortProductName = viewModel.ProductName.Replace(" ", "."); viewModel.ScriptInstallProjectName = viewModel.CompanyName + " " + viewModel.ProductName + " %Version%"; CommandManager.InvalidateRequerySuggested(); } public string ProductName { get { return (string)GetValue(ProductNameProperty); } set { SetValue(ProductNameProperty, value); } } public static readonly DependencyProperty ProductNameLabelTextProperty = DependencyProperty.Register( "ProductNameLabelText", typeof(string), typeof(MainViewModel), new PropertyMetadata(default(string))); public string ProductNameLabelText { get { return (string)GetValue(ProductNameLabelTextProperty); } set { SetValue(ProductNameLabelTextProperty, value); } } public static readonly DependencyProperty ShortProductNameProperty = DependencyProperty.Register( "ShortProductName", typeof(string), typeof(MainViewModel), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.AffectsMeasure, ShortProductNameChanged)); private static void ShortProductNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var viewModel = (MainViewModel)d; viewModel.ConsoleProjectName = viewModel.NamespaceCompanyName + "." + viewModel.ShortProductName; CommandManager.InvalidateRequerySuggested(); } public string ShortProductName { get { return (string)GetValue(ShortProductNameProperty); } set { SetValue(ShortProductNameProperty, value); } } public static readonly DependencyProperty ShortProductNameLabelTextProperty = DependencyProperty.Register( "ShortProductNameLabelText", typeof(string), typeof(MainViewModel), new PropertyMetadata(default(string))); public string ShortProductNameLabelText { get { return (string)GetValue(ShortProductNameLabelTextProperty); } set { SetValue(ShortProductNameLabelTextProperty, value); } } public static readonly DependencyProperty ProductDescriptionProperty = DependencyProperty.Register( "ProductDescription", typeof(string), typeof(MainViewModel), new PropertyMetadata(default(string))); public string ProductDescription { get { return (string)GetValue(ProductDescriptionProperty); } set { SetValue(ProductDescriptionProperty, value); } } public static readonly DependencyProperty ProductDescriptionLabelTextProperty = DependencyProperty.Register( "ProductDescriptionLabelText", typeof(string), typeof(MainViewModel), new PropertyMetadata(default(string))); public string ProductDescriptionLabelText { get { return (string)GetValue(ProductDescriptionLabelTextProperty); } set { SetValue(ProductDescriptionLabelTextProperty, value); } } public static readonly DependencyProperty ConsoleProjectNameProperty = DependencyProperty.Register( "ConsoleProjectName", typeof(string), typeof(MainViewModel), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.AffectsMeasure, ConsoleProjectNameChanged)); private static void ConsoleProjectNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var viewModel = (MainViewModel)d; viewModel.LibraryProjectName = viewModel.ConsoleProjectName + ".Library"; viewModel.TestsProjectName = viewModel.ConsoleProjectName + ".Tests"; viewModel.SetupProjectName = viewModel.ConsoleProjectName + ".Setup"; CommandManager.InvalidateRequerySuggested(); } public string ConsoleProjectName { get { return (string)GetValue(ConsoleProjectNameProperty); } set { SetValue(ConsoleProjectNameProperty, value); } } public static readonly DependencyProperty ConsoleProjectNameLabelTextProperty = DependencyProperty.Register( "ConsoleProjectNameLabelText", typeof(string), typeof(MainViewModel), new PropertyMetadata(default(string))); public string ConsoleProjectNameLabelText { get { return (string)GetValue(ConsoleProjectNameLabelTextProperty); } set { SetValue(ConsoleProjectNameLabelTextProperty, value); } } public static readonly DependencyProperty LibraryProjectNameProperty = DependencyProperty.Register( "LibraryProjectName", typeof(string), typeof(MainViewModel), new PropertyMetadata(default(string))); public string LibraryProjectName { get { return (string)GetValue(LibraryProjectNameProperty); } set { SetValue(LibraryProjectNameProperty, value); } } public static readonly DependencyProperty LibraryProjectNameLabelTextProperty = DependencyProperty.Register( "LibraryProjectNameLabelText", typeof(string), typeof(MainViewModel), new PropertyMetadata(default(string))); public string LibraryProjectNameLabelText { get { return (string)GetValue(LibraryProjectNameLabelTextProperty); } set { SetValue(LibraryProjectNameLabelTextProperty, value); } } public static readonly DependencyProperty TestsProjectNameProperty = DependencyProperty.Register( "TestsProjectName", typeof(string), typeof(MainViewModel), new PropertyMetadata(default(string))); public string TestsProjectName { get { return (string)GetValue(TestsProjectNameProperty); } set { SetValue(TestsProjectNameProperty, value); } } public static readonly DependencyProperty TestsProjectNameLabelTextProperty = DependencyProperty.Register( "TestsProjectNameLabelText", typeof(string), typeof(MainViewModel), new PropertyMetadata(default(string))); public string TestsProjectNameLabelText { get { return (string)GetValue(TestsProjectNameLabelTextProperty); } set { SetValue(TestsProjectNameLabelTextProperty, value); } } public static readonly DependencyProperty SetupProjectNameProperty = DependencyProperty.Register( "SetupProjectName", typeof(string), typeof(MainViewModel), new PropertyMetadata(default(string))); public string SetupProjectName { get { return (string)GetValue(SetupProjectNameProperty); } set { SetValue(SetupProjectNameProperty, value); } } public static readonly DependencyProperty SetupProjectNameLabelTextProperty = DependencyProperty.Register( "SetupProjectNameLabelText", typeof(string), typeof(MainViewModel), new PropertyMetadata(default(string))); public string SetupProjectNameLabelText { get { return (string)GetValue(SetupProjectNameLabelTextProperty); } set { SetValue(SetupProjectNameLabelTextProperty, value); } } public static readonly DependencyProperty ScriptInstallProjectNameProperty = DependencyProperty.Register( "ScriptInstallProjectName", typeof (string), typeof (MainViewModel), new PropertyMetadata(default(string))); public string ScriptInstallProjectName { get { return (string) GetValue(ScriptInstallProjectNameProperty); } set { SetValue(ScriptInstallProjectNameProperty, value); } } public static readonly DependencyProperty ScriptInstallProjectNameLabelTextProperty = DependencyProperty.Register( "ScriptInstallProjectNameLabelText", typeof (string), typeof (MainViewModel), new PropertyMetadata(default(string))); public string ScriptInstallProjectNameLabelText { get { return (string) GetValue(ScriptInstallProjectNameLabelTextProperty); } set { SetValue(ScriptInstallProjectNameLabelTextProperty, value); } } public static readonly DependencyProperty AuthorsProperty = DependencyProperty.Register( "Authors", typeof(string), typeof(MainViewModel), new PropertyMetadata(default(string))); public string Authors { get { return (string) GetValue(AuthorsProperty); } set { SetValue(AuthorsProperty, value); } } public static readonly DependencyProperty AuthorsLableTextProperty = DependencyProperty.Register( "AuthorsLableText", typeof (string), typeof (MainViewModel), new PropertyMetadata(default(string))); public string AuthorsLableText { get { return (string) GetValue(AuthorsLableTextProperty); } set { SetValue(AuthorsLableTextProperty, value); } } public static readonly DependencyProperty MaxLabelWidthProperty = DependencyProperty.Register( "MaxLabelWidth", typeof(int), typeof(MainViewModel), new PropertyMetadata(default(int))); public int MaxLabelWidth { get { return (int)GetValue(MaxLabelWidthProperty); } set { SetValue(MaxLabelWidthProperty, value); } } public ICommand OkCommand { get; set; } private void Exit() { if (MainWindow != null) { MainWindow.Close(); } else { throw new Exception("Unable to close main window as no reference to the main window has been set."); } } public bool IsFilledOut { get { return !string.IsNullOrEmpty(this.Authors) && !string.IsNullOrEmpty(this.CompanyName) && !string.IsNullOrEmpty(this.ConsoleProjectName) && !string.IsNullOrEmpty(this.LibraryProjectName) && !string.IsNullOrEmpty(this.NamespaceCompanyName) && !string.IsNullOrEmpty(this.ProductDescription) && !string.IsNullOrEmpty(this.ProductName) && !string.IsNullOrEmpty(this.ScriptInstallProjectName) && !string.IsNullOrEmpty(this.SetupProjectName) && !string.IsNullOrEmpty(this.ShortProductName) && !string.IsNullOrEmpty(this.TestsProjectName) ; } } } }
// *********************************************************************** // Copyright (c) 2012-2014 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** #if PARALLEL using System; using System.Collections.Generic; using System.Threading; namespace NUnit.Framework.Internal.Execution { /// <summary> /// ParallelWorkItemDispatcher handles execution of work items by /// queuing them for worker threads to process. /// </summary> public class ParallelWorkItemDispatcher : IWorkItemDispatcher { private static readonly Logger log = InternalTrace.GetLogger("WorkItemDispatcher"); private readonly int _levelOfParallelism; private int _itemsDispatched; // Non-STA private readonly WorkShift _parallelShift = new WorkShift("Parallel"); private readonly WorkShift _nonParallelShift = new WorkShift("NonParallel"); private readonly Lazy<WorkItemQueue> _parallelQueue; private readonly Lazy<WorkItemQueue> _nonParallelQueue; // STA #if !NETCF private readonly WorkShift _nonParallelSTAShift = new WorkShift("NonParallelSTA"); private readonly Lazy<WorkItemQueue> _parallelSTAQueue; private readonly Lazy<WorkItemQueue> _nonParallelSTAQueue; #endif // The first WorkItem to be dispatched, assumed to be top-level item private WorkItem _topLevelWorkItem; /// <summary> /// Construct a ParallelWorkItemDispatcher /// </summary> /// <param name="levelOfParallelism">Number of workers to use</param> public ParallelWorkItemDispatcher(int levelOfParallelism) { _levelOfParallelism = levelOfParallelism; Shifts = new WorkShift[] { _parallelShift, _nonParallelShift, #if !NETCF _nonParallelSTAShift #endif }; foreach (var shift in Shifts) shift.EndOfShift += OnEndOfShift; _parallelQueue = new Lazy<WorkItemQueue>(() => { var parallelQueue = new WorkItemQueue("ParallelQueue"); _parallelShift.AddQueue(parallelQueue); for (int i = 1; i <= _levelOfParallelism; i++) { string name = string.Format("Worker#" + i.ToString()); #if NETCF _parallelShift.Assign(new TestWorker(parallelQueue, name)); #else _parallelShift.Assign(new TestWorker(parallelQueue, name, ApartmentState.MTA)); #endif } return parallelQueue; }); #if !NETCF _parallelSTAQueue = new Lazy<WorkItemQueue>(() => { var parallelSTAQueue = new WorkItemQueue("ParallelSTAQueue"); _parallelShift.AddQueue(parallelSTAQueue); _parallelShift.Assign(new TestWorker(parallelSTAQueue, "Worker#STA", ApartmentState.STA)); return parallelSTAQueue; }); #endif _nonParallelQueue = new Lazy<WorkItemQueue>(() => { var nonParallelQueue = new WorkItemQueue("NonParallelQueue"); _nonParallelShift.AddQueue(nonParallelQueue); #if NETCF _nonParallelShift.Assign(new TestWorker(nonParallelQueue, "Worker#NP")); #else _nonParallelShift.Assign(new TestWorker(nonParallelQueue, "Worker#STA_NP", ApartmentState.MTA)); #endif return nonParallelQueue; }); #if !NETCF _nonParallelSTAQueue = new Lazy<WorkItemQueue>(() => { var nonParallelSTAQueue = new WorkItemQueue("NonParallelSTAQueue"); _nonParallelSTAShift.AddQueue(nonParallelSTAQueue); _nonParallelSTAShift.Assign(new TestWorker(nonParallelSTAQueue, "Worker#NP_STA", ApartmentState.STA)); return nonParallelSTAQueue; }); #endif } /// <summary> /// Enumerates all the shifts supported by the dispatcher /// </summary> public IEnumerable<WorkShift> Shifts { get; private set; } #region IWorkItemDispatcher Members /// <summary> /// Dispatch a single work item for execution. The first /// work item dispatched is saved as the top-level /// work item and used when stopping the run. /// </summary> /// <param name="work">The item to dispatch</param> public void Dispatch(WorkItem work) { // Special handling of the top-level item if (Interlocked.CompareExchange (ref _topLevelWorkItem, work, null) == null) { Enqueue(work); StartNextShift(); } // We run child items directly, rather than enqueuing them... // 1. If the context is single threaded. // 2. If there is no fixture, and so nothing to do but dispatch grandchildren. // 3. For now, if this represents a test case. This avoids issues of // tests that access the fixture state and allows handling ApartmentState // preferences set on the fixture. else if (work.Context.IsSingleThreaded || work.Test.TypeInfo == null || work is SimpleWorkItem) Execute(work); else Enqueue(work); Interlocked.Increment(ref _itemsDispatched); } private void Execute(WorkItem work) { log.Debug("Directly executing {0}", work.Test.Name); work.Execute(); } private void Enqueue(WorkItem work) { log.Debug("Enqueuing {0}", work.Test.Name); if (work.IsParallelizable) { #if !NETCF if (work.TargetApartment == ApartmentState.STA) ParallelSTAQueue.Enqueue(work); else #endif ParallelQueue.Enqueue(work); } #if !NETCF else if (work.TargetApartment == ApartmentState.STA) NonParallelSTAQueue.Enqueue(work); #endif else NonParallelQueue.Enqueue(work); } /// <summary> /// Cancel the ongoing run completely. /// If no run is in process, the call has no effect. /// </summary> public void CancelRun(bool force) { foreach (var shift in Shifts) shift.Cancel(force); } #endregion #region Private Queue Properties // Queues are not actually created until the first time the property // is referenced by the Dispatch method adding a WorkItem to it. private WorkItemQueue ParallelQueue { get { return _parallelQueue.Value; } } #if !NETCF private WorkItemQueue ParallelSTAQueue { get { return _parallelSTAQueue.Value; } } #endif private WorkItemQueue NonParallelQueue { get { return _nonParallelQueue.Value; } } #if !NETCF private WorkItemQueue NonParallelSTAQueue { get { return _nonParallelSTAQueue.Value; } } #endif #endregion #region Helper Methods private void OnEndOfShift(object sender, EventArgs ea) { if (!StartNextShift()) { foreach (var shift in Shifts) shift.ShutDown(); } } private bool StartNextShift() { foreach (var shift in Shifts) { if (shift.HasWork) { shift.Start(); return true; } } return false; } #endregion } } #endif
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Collections; using System.Management.Automation; using Microsoft.Azure.Commands.ResourceManager.Common.Tags; using Microsoft.Azure.Management.Storage; using Microsoft.Azure.Management.Storage.Models; using StorageModels = Microsoft.Azure.Management.Storage.Models; using Microsoft.Azure.Commands.Management.Storage.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using System; namespace Microsoft.Azure.Commands.Management.Storage { [Cmdlet(VerbsCommon.New, StorageAccountNounStr), OutputType(typeof(PSStorageAccount))] public class NewAzureStorageAccountCommand : StorageAccountBaseCmdlet { [Parameter( Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Resource Group Name.")] [ResourceGroupCompleter] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } [Parameter( Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Storage Account Name.")] [Alias(StorageAccountNameAlias, AccountNameAlias)] [ValidateNotNullOrEmpty] public string Name { get; set; } [Parameter( Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Storage Account Sku Name.")] [Alias(StorageAccountTypeAlias, AccountTypeAlias, Account_TypeAlias)] [ValidateSet(AccountTypeString.StandardLRS, AccountTypeString.StandardZRS, AccountTypeString.StandardGRS, AccountTypeString.StandardRAGRS, AccountTypeString.PremiumLRS, IgnoreCase = true)] public string SkuName { get; set; } [Parameter( Position = 3, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Storage Account Location.")] [LocationCompleter("Microsoft.Storage/storageAccounts")] [ValidateNotNullOrEmpty] public string Location { get; set; } [Parameter( Mandatory = false, HelpMessage = "Storage Account Kind.")] [ValidateSet(AccountKind.Storage, AccountKind.StorageV2, AccountKind.BlobStorage, IgnoreCase = true)] public string Kind { get; set; } [Parameter( Mandatory = false, HelpMessage = "Storage Account Access Tier.")] [ValidateSet(AccountAccessTier.Hot, AccountAccessTier.Cool, IgnoreCase = true)] public string AccessTier { get; set; } [Parameter( Mandatory = false, HelpMessage = "Storage Account Custom Domain.")] [ValidateNotNullOrEmpty] public string CustomDomainName { get; set; } [Parameter( Mandatory = false, HelpMessage = "To Use Sub Domain.")] [ValidateNotNullOrEmpty] public bool? UseSubDomain { get; set; } [Parameter( Mandatory = false, HelpMessage = "Storage Service that will enable encryption.")] [Obsolete("Encryption at Rest is already enabled by default for this storage account.", false)] public EncryptionSupportServiceEnum? EnableEncryptionService { get; set; } [Parameter( Mandatory = false, HelpMessage = "Storage Account Tags.")] [ValidateNotNull] [Alias(TagsAlias)] public Hashtable Tag { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Storage Account EnableHttpsTrafficOnly.")] public bool EnableHttpsTrafficOnly { get { return enableHttpsTrafficOnly.Value; } set { enableHttpsTrafficOnly = value; } } private bool? enableHttpsTrafficOnly = null; [Parameter( Mandatory = false, HelpMessage = "Generate and assign a new Storage Account Identity for this storage account for use with key management services like Azure KeyVault.")] public SwitchParameter AssignIdentity { get; set; } [Parameter(HelpMessage = "Storage Account NetworkRule", Mandatory = false)] [ValidateNotNullOrEmpty] public PSNetworkRuleSet NetworkRuleSet { get; set; } [Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")] public SwitchParameter AsJob { get; set; } public override void ExecuteCmdlet() { base.ExecuteCmdlet(); CheckNameAvailabilityResult checkNameAvailabilityResult = this.StorageClient.StorageAccounts.CheckNameAvailability(this.Name); if (!checkNameAvailabilityResult.NameAvailable.Value) { throw new System.ArgumentException(checkNameAvailabilityResult.Message, "Name"); } StorageAccountCreateParameters createParameters = new StorageAccountCreateParameters() { Location = this.Location, Sku = new Sku(ParseSkuName(this.SkuName)), Tags = TagsConversionHelper.CreateTagDictionary(Tag, validate: true), }; if (this.CustomDomainName != null) { createParameters.CustomDomain = new CustomDomain() { Name = CustomDomainName, UseSubDomain = UseSubDomain }; } else if (UseSubDomain != null) { throw new System.ArgumentException(string.Format("UseSubDomain must be set together with CustomDomainName.")); } if (Kind != null) { createParameters.Kind = ParseAccountKind(Kind); } if (this.AccessTier != null) { createParameters.AccessTier = ParseAccessTier(AccessTier); } if (enableHttpsTrafficOnly != null) { createParameters.EnableHttpsTrafficOnly = enableHttpsTrafficOnly; } if (AssignIdentity.IsPresent) { createParameters.Identity = new Identity(); } if (NetworkRuleSet != null) { createParameters.NetworkRuleSet = PSNetworkRuleSet.ParseStorageNetworkRule(NetworkRuleSet); } var createAccountResponse = this.StorageClient.StorageAccounts.Create( this.ResourceGroupName, this.Name, createParameters); var storageAccount = this.StorageClient.StorageAccounts.GetProperties(this.ResourceGroupName, this.Name); this.WriteStorageAccount(storageAccount); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareScalarGreaterThanSingle() { var test = new SimpleBinaryOpTest__CompareScalarGreaterThanSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareScalarGreaterThanSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareScalarGreaterThanSingle testClass) { var result = Sse.CompareScalarGreaterThan(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareScalarGreaterThanSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.CompareScalarGreaterThan( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareScalarGreaterThanSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleBinaryOpTest__CompareScalarGreaterThanSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse.CompareScalarGreaterThan( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse.CompareScalarGreaterThan( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse.CompareScalarGreaterThan( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarGreaterThan), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarGreaterThan), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarGreaterThan), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse.CompareScalarGreaterThan( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) fixed (Vector128<Single>* pClsVar2 = &_clsVar2) { var result = Sse.CompareScalarGreaterThan( Sse.LoadVector128((Single*)(pClsVar1)), Sse.LoadVector128((Single*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.CompareScalarGreaterThan(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareScalarGreaterThan(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareScalarGreaterThan(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareScalarGreaterThanSingle(); var result = Sse.CompareScalarGreaterThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__CompareScalarGreaterThanSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) { var result = Sse.CompareScalarGreaterThan( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse.CompareScalarGreaterThan(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.CompareScalarGreaterThan( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse.CompareScalarGreaterThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse.CompareScalarGreaterThan( Sse.LoadVector128((Single*)(&test._fld1)), Sse.LoadVector128((Single*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(result[0]) != ((left[0] > right[0]) ? -1 : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(left[i]) != BitConverter.SingleToInt32Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse)}.{nameof(Sse.CompareScalarGreaterThan)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// MIT License // // Copyright (c) 2009-2017 Luca Piccioni // // 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. // // This file is automatically generated #pragma warning disable 649, 1572, 1573 // ReSharper disable RedundantUsingDirective using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using Khronos; // ReSharper disable CheckNamespace // ReSharper disable InconsistentNaming // ReSharper disable JoinDeclarationAndInitializer namespace OpenGL { public partial class Gl { /// <summary> /// [GL] glIsRenderbufferOES: Binding for glIsRenderbufferOES. /// </summary> /// <param name="renderbuffer"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] public static bool IsRenderbufferOES(uint renderbuffer) { bool retValue; Debug.Assert(Delegates.pglIsRenderbufferOES != null, "pglIsRenderbufferOES not implemented"); retValue = Delegates.pglIsRenderbufferOES(renderbuffer); LogCommand("glIsRenderbufferOES", retValue, renderbuffer ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GL] glBindRenderbufferOES: Binding for glBindRenderbufferOES. /// </summary> /// <param name="target"> /// A <see cref="T:RenderbufferTarget"/>. /// </param> /// <param name="renderbuffer"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] public static void BindRenderbufferOES(RenderbufferTarget target, uint renderbuffer) { Debug.Assert(Delegates.pglBindRenderbufferOES != null, "pglBindRenderbufferOES not implemented"); Delegates.pglBindRenderbufferOES((int)target, renderbuffer); LogCommand("glBindRenderbufferOES", null, target, renderbuffer ); DebugCheckErrors(null); } /// <summary> /// [GL] glDeleteRenderbuffersOES: Binding for glDeleteRenderbuffersOES. /// </summary> /// <param name="renderbuffers"> /// A <see cref="T:uint[]"/>. /// </param> [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] public static void DeleteRenderbuffersOES(uint[] renderbuffers) { unsafe { fixed (uint* p_renderbuffers = renderbuffers) { Debug.Assert(Delegates.pglDeleteRenderbuffersOES != null, "pglDeleteRenderbuffersOES not implemented"); Delegates.pglDeleteRenderbuffersOES(renderbuffers.Length, p_renderbuffers); LogCommand("glDeleteRenderbuffersOES", null, renderbuffers.Length, renderbuffers ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGenRenderbuffersOES: Binding for glGenRenderbuffersOES. /// </summary> /// <param name="renderbuffers"> /// A <see cref="T:uint[]"/>. /// </param> [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] public static void GenRenderbuffersOES(uint[] renderbuffers) { unsafe { fixed (uint* p_renderbuffers = renderbuffers) { Debug.Assert(Delegates.pglGenRenderbuffersOES != null, "pglGenRenderbuffersOES not implemented"); Delegates.pglGenRenderbuffersOES(renderbuffers.Length, p_renderbuffers); LogCommand("glGenRenderbuffersOES", null, renderbuffers.Length, renderbuffers ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGenRenderbuffersOES: Binding for glGenRenderbuffersOES. /// </summary> [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] public static uint GenRenderbufferOES() { uint retValue; unsafe { Delegates.pglGenRenderbuffersOES(1, &retValue); LogCommand("glGenRenderbuffersOES", null, 1, "{ " + retValue + " }" ); } DebugCheckErrors(null); return (retValue); } /// <summary> /// [GL] glRenderbufferStorageOES: Binding for glRenderbufferStorageOES. /// </summary> /// <param name="target"> /// A <see cref="T:RenderbufferTarget"/>. /// </param> /// <param name="internalformat"> /// A <see cref="T:InternalFormat"/>. /// </param> /// <param name="width"> /// A <see cref="T:int"/>. /// </param> /// <param name="height"> /// A <see cref="T:int"/>. /// </param> [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] public static void RenderbufferStorageOES(RenderbufferTarget target, InternalFormat internalformat, int width, int height) { Debug.Assert(Delegates.pglRenderbufferStorageOES != null, "pglRenderbufferStorageOES not implemented"); Delegates.pglRenderbufferStorageOES((int)target, (int)internalformat, width, height); LogCommand("glRenderbufferStorageOES", null, target, internalformat, width, height ); DebugCheckErrors(null); } /// <summary> /// [GL] glGetRenderbufferParameterivOES: Binding for glGetRenderbufferParameterivOES. /// </summary> /// <param name="target"> /// A <see cref="T:RenderbufferTarget"/>. /// </param> /// <param name="pname"> /// A <see cref="T:RenderbufferParameterName"/>. /// </param> /// <param name="params"> /// A <see cref="T:int[]"/>. /// </param> [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] public static void GetRenderbufferParameterOES(RenderbufferTarget target, RenderbufferParameterName pname, [Out] int[] @params) { unsafe { fixed (int* p_params = @params) { Debug.Assert(Delegates.pglGetRenderbufferParameterivOES != null, "pglGetRenderbufferParameterivOES not implemented"); Delegates.pglGetRenderbufferParameterivOES((int)target, (int)pname, p_params); LogCommand("glGetRenderbufferParameterivOES", null, target, pname, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glIsFramebufferOES: Binding for glIsFramebufferOES. /// </summary> /// <param name="framebuffer"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] public static bool IsFramebufferOES(uint framebuffer) { bool retValue; Debug.Assert(Delegates.pglIsFramebufferOES != null, "pglIsFramebufferOES not implemented"); retValue = Delegates.pglIsFramebufferOES(framebuffer); LogCommand("glIsFramebufferOES", retValue, framebuffer ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GL] glBindFramebufferOES: Binding for glBindFramebufferOES. /// </summary> /// <param name="target"> /// A <see cref="T:FramebufferTarget"/>. /// </param> /// <param name="framebuffer"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] public static void BindFramebufferOES(FramebufferTarget target, uint framebuffer) { Debug.Assert(Delegates.pglBindFramebufferOES != null, "pglBindFramebufferOES not implemented"); Delegates.pglBindFramebufferOES((int)target, framebuffer); LogCommand("glBindFramebufferOES", null, target, framebuffer ); DebugCheckErrors(null); } /// <summary> /// [GL] glDeleteFramebuffersOES: Binding for glDeleteFramebuffersOES. /// </summary> /// <param name="framebuffers"> /// A <see cref="T:uint[]"/>. /// </param> [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] public static void DeleteFramebuffersOES(uint[] framebuffers) { unsafe { fixed (uint* p_framebuffers = framebuffers) { Debug.Assert(Delegates.pglDeleteFramebuffersOES != null, "pglDeleteFramebuffersOES not implemented"); Delegates.pglDeleteFramebuffersOES(framebuffers.Length, p_framebuffers); LogCommand("glDeleteFramebuffersOES", null, framebuffers.Length, framebuffers ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGenFramebuffersOES: Binding for glGenFramebuffersOES. /// </summary> /// <param name="framebuffers"> /// A <see cref="T:uint[]"/>. /// </param> [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] public static void GenFramebuffersOES(uint[] framebuffers) { unsafe { fixed (uint* p_framebuffers = framebuffers) { Debug.Assert(Delegates.pglGenFramebuffersOES != null, "pglGenFramebuffersOES not implemented"); Delegates.pglGenFramebuffersOES(framebuffers.Length, p_framebuffers); LogCommand("glGenFramebuffersOES", null, framebuffers.Length, framebuffers ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGenFramebuffersOES: Binding for glGenFramebuffersOES. /// </summary> [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] public static uint GenFramebufferOES() { uint retValue; unsafe { Delegates.pglGenFramebuffersOES(1, &retValue); LogCommand("glGenFramebuffersOES", null, 1, "{ " + retValue + " }" ); } DebugCheckErrors(null); return (retValue); } /// <summary> /// [GL] glCheckFramebufferStatusOES: Binding for glCheckFramebufferStatusOES. /// </summary> /// <param name="target"> /// A <see cref="T:FramebufferTarget"/>. /// </param> [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] public static FramebufferStatus CheckFramebufferStatusOES(FramebufferTarget target) { int retValue; Debug.Assert(Delegates.pglCheckFramebufferStatusOES != null, "pglCheckFramebufferStatusOES not implemented"); retValue = Delegates.pglCheckFramebufferStatusOES((int)target); LogCommand("glCheckFramebufferStatusOES", (FramebufferStatus)retValue, target ); DebugCheckErrors(retValue); return ((FramebufferStatus)retValue); } /// <summary> /// [GL] glFramebufferRenderbufferOES: Binding for glFramebufferRenderbufferOES. /// </summary> /// <param name="target"> /// A <see cref="T:FramebufferTarget"/>. /// </param> /// <param name="attachment"> /// A <see cref="T:FramebufferAttachment"/>. /// </param> /// <param name="renderbuffertarget"> /// A <see cref="T:RenderbufferTarget"/>. /// </param> /// <param name="renderbuffer"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] public static void FramebufferRenderbufferOES(FramebufferTarget target, FramebufferAttachment attachment, RenderbufferTarget renderbuffertarget, uint renderbuffer) { Debug.Assert(Delegates.pglFramebufferRenderbufferOES != null, "pglFramebufferRenderbufferOES not implemented"); Delegates.pglFramebufferRenderbufferOES((int)target, (int)attachment, (int)renderbuffertarget, renderbuffer); LogCommand("glFramebufferRenderbufferOES", null, target, attachment, renderbuffertarget, renderbuffer ); DebugCheckErrors(null); } /// <summary> /// [GL] glFramebufferTexture2DOES: Binding for glFramebufferTexture2DOES. /// </summary> /// <param name="target"> /// A <see cref="T:FramebufferTarget"/>. /// </param> /// <param name="attachment"> /// A <see cref="T:FramebufferAttachment"/>. /// </param> /// <param name="textarget"> /// A <see cref="T:TextureTarget"/>. /// </param> /// <param name="texture"> /// A <see cref="T:uint"/>. /// </param> /// <param name="level"> /// A <see cref="T:int"/>. /// </param> [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] public static void FramebufferTexture2DOES(FramebufferTarget target, FramebufferAttachment attachment, TextureTarget textarget, uint texture, int level) { Debug.Assert(Delegates.pglFramebufferTexture2DOES != null, "pglFramebufferTexture2DOES not implemented"); Delegates.pglFramebufferTexture2DOES((int)target, (int)attachment, (int)textarget, texture, level); LogCommand("glFramebufferTexture2DOES", null, target, attachment, textarget, texture, level ); DebugCheckErrors(null); } /// <summary> /// [GL] glGetFramebufferAttachmentParameterivOES: Binding for glGetFramebufferAttachmentParameterivOES. /// </summary> /// <param name="target"> /// A <see cref="T:FramebufferTarget"/>. /// </param> /// <param name="attachment"> /// A <see cref="T:FramebufferAttachment"/>. /// </param> /// <param name="pname"> /// A <see cref="T:FramebufferAttachmentParameterName"/>. /// </param> /// <param name="params"> /// A <see cref="T:int[]"/>. /// </param> [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] public static void GetFramebufferAttachmentParameterOES(FramebufferTarget target, FramebufferAttachment attachment, FramebufferAttachmentParameterName pname, [Out] int[] @params) { unsafe { fixed (int* p_params = @params) { Debug.Assert(Delegates.pglGetFramebufferAttachmentParameterivOES != null, "pglGetFramebufferAttachmentParameterivOES not implemented"); Delegates.pglGetFramebufferAttachmentParameterivOES((int)target, (int)attachment, (int)pname, p_params); LogCommand("glGetFramebufferAttachmentParameterivOES", null, target, attachment, pname, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGenerateMipmapOES: Binding for glGenerateMipmapOES. /// </summary> /// <param name="target"> /// A <see cref="T:TextureTarget"/>. /// </param> [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] public static void GenerateMipmapOES(TextureTarget target) { Debug.Assert(Delegates.pglGenerateMipmapOES != null, "pglGenerateMipmapOES not implemented"); Delegates.pglGenerateMipmapOES((int)target); LogCommand("glGenerateMipmapOES", null, target ); DebugCheckErrors(null); } internal static unsafe partial class Delegates { [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] internal delegate bool glIsRenderbufferOES(uint renderbuffer); [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [ThreadStatic] internal static glIsRenderbufferOES pglIsRenderbufferOES; [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glBindRenderbufferOES(int target, uint renderbuffer); [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [ThreadStatic] internal static glBindRenderbufferOES pglBindRenderbufferOES; [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glDeleteRenderbuffersOES(int n, uint* renderbuffers); [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [ThreadStatic] internal static glDeleteRenderbuffersOES pglDeleteRenderbuffersOES; [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glGenRenderbuffersOES(int n, uint* renderbuffers); [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [ThreadStatic] internal static glGenRenderbuffersOES pglGenRenderbuffersOES; [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glRenderbufferStorageOES(int target, int internalformat, int width, int height); [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [ThreadStatic] internal static glRenderbufferStorageOES pglRenderbufferStorageOES; [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetRenderbufferParameterivOES(int target, int pname, int* @params); [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [ThreadStatic] internal static glGetRenderbufferParameterivOES pglGetRenderbufferParameterivOES; [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] internal delegate bool glIsFramebufferOES(uint framebuffer); [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [ThreadStatic] internal static glIsFramebufferOES pglIsFramebufferOES; [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glBindFramebufferOES(int target, uint framebuffer); [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [ThreadStatic] internal static glBindFramebufferOES pglBindFramebufferOES; [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glDeleteFramebuffersOES(int n, uint* framebuffers); [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [ThreadStatic] internal static glDeleteFramebuffersOES pglDeleteFramebuffersOES; [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glGenFramebuffersOES(int n, uint* framebuffers); [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [ThreadStatic] internal static glGenFramebuffersOES pglGenFramebuffersOES; [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate int glCheckFramebufferStatusOES(int target); [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [ThreadStatic] internal static glCheckFramebufferStatusOES pglCheckFramebufferStatusOES; [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glFramebufferRenderbufferOES(int target, int attachment, int renderbuffertarget, uint renderbuffer); [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [ThreadStatic] internal static glFramebufferRenderbufferOES pglFramebufferRenderbufferOES; [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glFramebufferTexture2DOES(int target, int attachment, int textarget, uint texture, int level); [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [ThreadStatic] internal static glFramebufferTexture2DOES pglFramebufferTexture2DOES; [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetFramebufferAttachmentParameterivOES(int target, int attachment, int pname, int* @params); [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [ThreadStatic] internal static glGetFramebufferAttachmentParameterivOES pglGetFramebufferAttachmentParameterivOES; [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glGenerateMipmapOES(int target); [RequiredByFeature("GL_OES_framebuffer_object", Api = "gles1")] [ThreadStatic] internal static glGenerateMipmapOES pglGenerateMipmapOES; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// ExpressRouteCircuitAuthorizationsOperations operations. /// </summary> public partial interface IExpressRouteCircuitAuthorizationsOperations { /// <summary> /// Deletes the specified authorization from the specified express /// route circuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='authorizationName'> /// The name of the authorization. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the specified authorization from the specified express route /// circuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='authorizationName'> /// The name of the authorization. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> GetWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates an authorization in the specified express route /// circuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='authorizationName'> /// The name of the authorization. /// </param> /// <param name='authorizationParameters'> /// Parameters supplied to the create or update express route circuit /// authorization operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all authorizations in an express route circuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the circuit. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>> ListWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified authorization from the specified express /// route circuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='authorizationName'> /// The name of the authorization. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates an authorization in the specified express route /// circuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='authorizationName'> /// The name of the authorization. /// </param> /// <param name='authorizationParameters'> /// Parameters supplied to the create or update express route circuit /// authorization operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ExpressRouteCircuitAuthorization>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string authorizationName, ExpressRouteCircuitAuthorization authorizationParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all authorizations in an express route circuit. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<ExpressRouteCircuitAuthorization>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// 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.Xml; using System.Diagnostics; using System.Collections.Generic; namespace System.Xml.Schema { internal enum AttributeMatchState { AttributeFound, AnyIdAttributeFound, UndeclaredElementAndAttribute, UndeclaredAttribute, AnyAttributeLax, AnyAttributeSkip, ProhibitedAnyAttribute, ProhibitedAttribute, AttributeNameMismatch, ValidateAttributeInvalidCall, } internal class SchemaInfo : IDtdInfo { private Dictionary<XmlQualifiedName, SchemaElementDecl> _elementDecls = new Dictionary<XmlQualifiedName, SchemaElementDecl>(); private Dictionary<XmlQualifiedName, SchemaElementDecl> _undeclaredElementDecls = new Dictionary<XmlQualifiedName, SchemaElementDecl>(); private Dictionary<XmlQualifiedName, SchemaEntity> _generalEntities; private Dictionary<XmlQualifiedName, SchemaEntity> _parameterEntities; private XmlQualifiedName _docTypeName = XmlQualifiedName.Empty; private string _internalDtdSubset = string.Empty; private bool _hasNonCDataAttributes = false; private bool _hasDefaultAttributes = false; private Dictionary<string, bool> _targetNamespaces = new Dictionary<string, bool>(); private Dictionary<XmlQualifiedName, SchemaAttDef> _attributeDecls = new Dictionary<XmlQualifiedName, SchemaAttDef>(); private int _errorCount; private SchemaType _schemaType; private Dictionary<XmlQualifiedName, SchemaElementDecl> _elementDeclsByType = new Dictionary<XmlQualifiedName, SchemaElementDecl>(); private Dictionary<string, SchemaNotation> _notations; internal SchemaInfo() { _schemaType = SchemaType.None; } public XmlQualifiedName DocTypeName { get { return _docTypeName; } set { _docTypeName = value; } } internal string InternalDtdSubset { get { return _internalDtdSubset; } set { _internalDtdSubset = value; } } internal Dictionary<XmlQualifiedName, SchemaElementDecl> ElementDecls { get { return _elementDecls; } } internal Dictionary<XmlQualifiedName, SchemaElementDecl> UndeclaredElementDecls { get { return _undeclaredElementDecls; } } internal Dictionary<XmlQualifiedName, SchemaEntity> GeneralEntities { get { if (_generalEntities == null) { _generalEntities = new Dictionary<XmlQualifiedName, SchemaEntity>(); } return _generalEntities; } } internal Dictionary<XmlQualifiedName, SchemaEntity> ParameterEntities { get { if (_parameterEntities == null) { _parameterEntities = new Dictionary<XmlQualifiedName, SchemaEntity>(); } return _parameterEntities; } } internal SchemaType SchemaType { get { return _schemaType; } set { _schemaType = value; } } internal Dictionary<string, bool> TargetNamespaces { get { return _targetNamespaces; } } internal Dictionary<XmlQualifiedName, SchemaElementDecl> ElementDeclsByType { get { return _elementDeclsByType; } } internal Dictionary<XmlQualifiedName, SchemaAttDef> AttributeDecls { get { return _attributeDecls; } } internal Dictionary<string, SchemaNotation> Notations { get { if (_notations == null) { _notations = new Dictionary<string, SchemaNotation>(); } return _notations; } } internal int ErrorCount { get { return _errorCount; } set { _errorCount = value; } } internal SchemaElementDecl GetElementDecl(XmlQualifiedName qname) { SchemaElementDecl elemDecl; if (_elementDecls.TryGetValue(qname, out elemDecl)) { return elemDecl; } return null; } internal SchemaElementDecl GetTypeDecl(XmlQualifiedName qname) { SchemaElementDecl elemDecl; if (_elementDeclsByType.TryGetValue(qname, out elemDecl)) { return elemDecl; } return null; } internal XmlSchemaElement GetElement(XmlQualifiedName qname) { SchemaElementDecl ed = GetElementDecl(qname); if (ed != null) { return ed.SchemaElement; } return null; } internal bool HasSchema(string ns) { return _targetNamespaces.ContainsKey(ns); } internal bool Contains(string ns) { return _targetNamespaces.ContainsKey(ns); } internal SchemaAttDef GetAttributeXdr(SchemaElementDecl ed, XmlQualifiedName qname) { SchemaAttDef attdef = null; if (ed != null) { attdef = ed.GetAttDef(qname); ; if (attdef == null) { if (!ed.ContentValidator.IsOpen || qname.Namespace.Length == 0) { throw new XmlSchemaException(SR.Sch_UndeclaredAttribute, qname.ToString()); } if (!_attributeDecls.TryGetValue(qname, out attdef) && _targetNamespaces.ContainsKey(qname.Namespace)) { throw new XmlSchemaException(SR.Sch_UndeclaredAttribute, qname.ToString()); } } } return attdef; } internal SchemaAttDef GetAttributeXsd(SchemaElementDecl ed, XmlQualifiedName qname, XmlSchemaObject partialValidationType, out AttributeMatchState attributeMatchState) { SchemaAttDef attdef = null; attributeMatchState = AttributeMatchState.UndeclaredAttribute; if (ed != null) { attdef = ed.GetAttDef(qname); if (attdef != null) { attributeMatchState = AttributeMatchState.AttributeFound; return attdef; } XmlSchemaAnyAttribute any = ed.AnyAttribute; if (any != null) { if (!any.NamespaceList.Allows(qname)) { attributeMatchState = AttributeMatchState.ProhibitedAnyAttribute; } else if (any.ProcessContentsCorrect != XmlSchemaContentProcessing.Skip) { if (_attributeDecls.TryGetValue(qname, out attdef)) { if (attdef.Datatype.TypeCode == XmlTypeCode.Id) { //anyAttribute match whose type is ID attributeMatchState = AttributeMatchState.AnyIdAttributeFound; } else { attributeMatchState = AttributeMatchState.AttributeFound; } } else if (any.ProcessContentsCorrect == XmlSchemaContentProcessing.Lax) { attributeMatchState = AttributeMatchState.AnyAttributeLax; } } else { attributeMatchState = AttributeMatchState.AnyAttributeSkip; } } else if (ed.ProhibitedAttributes.ContainsKey(qname)) { attributeMatchState = AttributeMatchState.ProhibitedAttribute; } } else if (partialValidationType != null) { XmlSchemaAttribute attr = partialValidationType as XmlSchemaAttribute; if (attr != null) { if (qname.Equals(attr.QualifiedName)) { attdef = attr.AttDef; attributeMatchState = AttributeMatchState.AttributeFound; } else { attributeMatchState = AttributeMatchState.AttributeNameMismatch; } } else { attributeMatchState = AttributeMatchState.ValidateAttributeInvalidCall; } } else { if (_attributeDecls.TryGetValue(qname, out attdef)) { attributeMatchState = AttributeMatchState.AttributeFound; } else { attributeMatchState = AttributeMatchState.UndeclaredElementAndAttribute; } } return attdef; } internal SchemaAttDef GetAttributeXsd(SchemaElementDecl ed, XmlQualifiedName qname, ref bool skip) { AttributeMatchState attributeMatchState; SchemaAttDef attDef = GetAttributeXsd(ed, qname, null, out attributeMatchState); switch (attributeMatchState) { case AttributeMatchState.UndeclaredAttribute: throw new XmlSchemaException(SR.Sch_UndeclaredAttribute, qname.ToString()); case AttributeMatchState.ProhibitedAnyAttribute: case AttributeMatchState.ProhibitedAttribute: throw new XmlSchemaException(SR.Sch_ProhibitedAttribute, qname.ToString()); case AttributeMatchState.AttributeFound: case AttributeMatchState.AnyIdAttributeFound: case AttributeMatchState.AnyAttributeLax: case AttributeMatchState.UndeclaredElementAndAttribute: break; case AttributeMatchState.AnyAttributeSkip: skip = true; break; default: Debug.Assert(false); break; } return attDef; } internal void Add(SchemaInfo sinfo, ValidationEventHandler eventhandler) { if (_schemaType == SchemaType.None) { _schemaType = sinfo.SchemaType; } else if (_schemaType != sinfo.SchemaType) { if (eventhandler != null) { eventhandler(this, new ValidationEventArgs(new XmlSchemaException(SR.Sch_MixSchemaTypes, string.Empty))); } return; } foreach (string tns in sinfo.TargetNamespaces.Keys) { if (!_targetNamespaces.ContainsKey(tns)) { _targetNamespaces.Add(tns, true); } } foreach (KeyValuePair<XmlQualifiedName, SchemaElementDecl> entry in sinfo._elementDecls) { if (!_elementDecls.ContainsKey(entry.Key)) { _elementDecls.Add(entry.Key, entry.Value); } } foreach (KeyValuePair<XmlQualifiedName, SchemaElementDecl> entry in sinfo._elementDeclsByType) { if (!_elementDeclsByType.ContainsKey(entry.Key)) { _elementDeclsByType.Add(entry.Key, entry.Value); } } foreach (SchemaAttDef attdef in sinfo.AttributeDecls.Values) { if (!_attributeDecls.ContainsKey(attdef.Name)) { _attributeDecls.Add(attdef.Name, attdef); } } foreach (SchemaNotation notation in sinfo.Notations.Values) { if (!Notations.ContainsKey(notation.Name.Name)) { Notations.Add(notation.Name.Name, notation); } } } internal void Finish() { Dictionary<XmlQualifiedName, SchemaElementDecl> elements = _elementDecls; for (int i = 0; i < 2; i++) { foreach (SchemaElementDecl e in elements.Values) { if (e.HasNonCDataAttribute) { _hasNonCDataAttributes = true; } if (e.DefaultAttDefs != null) { _hasDefaultAttributes = true; } } elements = _undeclaredElementDecls; } } // // IDtdInfo interface // #region IDtdInfo Members bool IDtdInfo.HasDefaultAttributes { get { return _hasDefaultAttributes; } } bool IDtdInfo.HasNonCDataAttributes { get { return _hasNonCDataAttributes; } } IDtdAttributeListInfo IDtdInfo.LookupAttributeList(string prefix, string localName) { XmlQualifiedName qname = new XmlQualifiedName(prefix, localName); SchemaElementDecl elementDecl; if (!_elementDecls.TryGetValue(qname, out elementDecl)) { _undeclaredElementDecls.TryGetValue(qname, out elementDecl); } return elementDecl; } IEnumerable<IDtdAttributeListInfo> IDtdInfo.GetAttributeLists() { foreach (SchemaElementDecl elemDecl in _elementDecls.Values) { IDtdAttributeListInfo eleDeclAsAttList = (IDtdAttributeListInfo)elemDecl; yield return eleDeclAsAttList; } } IDtdEntityInfo IDtdInfo.LookupEntity(string name) { if (_generalEntities == null) { return null; } XmlQualifiedName qname = new XmlQualifiedName(name); SchemaEntity entity; if (_generalEntities.TryGetValue(qname, out entity)) { return entity; } return null; } XmlQualifiedName IDtdInfo.Name { get { return _docTypeName; } } string IDtdInfo.InternalDtdSubset { get { return _internalDtdSubset; } } #endregion } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; #if !(NET20 || NET35 || PORTABLE) using System.Numerics; #endif using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Tests.TestObjects; using Newtonsoft.Json.Tests.TestObjects.Organization; #if DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif using Newtonsoft.Json.Linq; using System.IO; using System.Collections; #if !(DNXCORE50) using System.Web.UI; #endif #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Tests.Linq { [TestFixture] public class JObjectTests : TestFixtureBase { #if !(NET35 || NET20 || PORTABLE40) || NETSTANDARD2_0 [Test] public void EmbedJValueStringInNewJObject() { string s = null; var v = new JValue(s); dynamic o = JObject.FromObject(new { title = v }); string output = o.ToString(); StringAssert.AreEqual(@"{ ""title"": null }", output); Assert.AreEqual(null, v.Value); Assert.IsNull((string)o.title); } #endif [Test] public void ReadWithSupportMultipleContent() { string json = @"{ 'name': 'Admin' }{ 'name': 'Publisher' }"; IList<JObject> roles = new List<JObject>(); JsonTextReader reader = new JsonTextReader(new StringReader(json)); reader.SupportMultipleContent = true; while (true) { JObject role = (JObject)JToken.ReadFrom(reader); roles.Add(role); if (!reader.Read()) { break; } } Assert.AreEqual(2, roles.Count); Assert.AreEqual("Admin", (string)roles[0]["name"]); Assert.AreEqual("Publisher", (string)roles[1]["name"]); } [Test] public void JObjectWithComments() { string json = @"{ /*comment2*/ ""Name"": /*comment3*/ ""Apple"" /*comment4*/, /*comment5*/ ""ExpiryDate"": ""\/Date(1230422400000)\/"", ""Price"": 3.99, ""Sizes"": /*comment6*/ [ /*comment7*/ ""Small"", /*comment8*/ ""Medium"" /*comment9*/, /*comment10*/ ""Large"" /*comment11*/ ] /*comment12*/ } /*comment13*/"; JToken o = JToken.Parse(json); Assert.AreEqual("Apple", (string)o["Name"]); } [Test] public void WritePropertyWithNoValue() { var o = new JObject(); o.Add(new JProperty("novalue")); StringAssert.AreEqual(@"{ ""novalue"": null }", o.ToString()); } [Test] public void Keys() { var o = new JObject(); var d = (IDictionary<string, JToken>)o; Assert.AreEqual(0, d.Keys.Count); o["value"] = true; Assert.AreEqual(1, d.Keys.Count); } [Test] public void TryGetValue() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); JToken t; Assert.AreEqual(false, o.TryGetValue("sdf", out t)); Assert.AreEqual(null, t); Assert.AreEqual(false, o.TryGetValue(null, out t)); Assert.AreEqual(null, t); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t)); } [Test] public void DictionaryItemShouldSet() { JObject o = new JObject(); o["PropertyNameValue"] = new JValue(1); Assert.AreEqual(1, o.Children().Count()); JToken t; Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t)); o["PropertyNameValue"] = new JValue(2); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(2), t)); o["PropertyNameValue"] = null; Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(JValue.CreateNull(), t)); } [Test] public void Remove() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(false, o.Remove("sdf")); Assert.AreEqual(false, o.Remove(null)); Assert.AreEqual(true, o.Remove("PropertyNameValue")); Assert.AreEqual(0, o.Children().Count()); } [Test] public void GenericCollectionRemove() { JValue v = new JValue(1); JObject o = new JObject(); o.Add("PropertyNameValue", v); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1)))); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2)))); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1)))); Assert.AreEqual(true, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", v))); Assert.AreEqual(0, o.Children().Count()); } [Test] public void DuplicatePropertyNameShouldThrow() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); o.Add("PropertyNameValue", null); o.Add("PropertyNameValue", null); }, "Can not add property PropertyNameValue to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } [Test] public void GenericDictionaryAdd() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, (int)o["PropertyNameValue"]); o.Add("PropertyNameValue1", null); Assert.AreEqual(null, ((JValue)o["PropertyNameValue1"]).Value); Assert.AreEqual(2, o.Children().Count()); } [Test] public void GenericCollectionAdd() { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).Add(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))); Assert.AreEqual(1, (int)o["PropertyNameValue"]); Assert.AreEqual(1, o.Children().Count()); } [Test] public void GenericCollectionClear() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); JProperty p = (JProperty)o.Children().ElementAt(0); ((ICollection<KeyValuePair<string, JToken>>)o).Clear(); Assert.AreEqual(0, o.Children().Count()); Assert.AreEqual(null, p.Parent); } [Test] public void GenericCollectionContains() { JValue v = new JValue(1); JObject o = new JObject(); o.Add("PropertyNameValue", v); Assert.AreEqual(1, o.Children().Count()); bool contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))); Assert.AreEqual(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", v)); Assert.AreEqual(true, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2))); Assert.AreEqual(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1))); Assert.AreEqual(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(default(KeyValuePair<string, JToken>)); Assert.AreEqual(false, contains); } [Test] public void Contains() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); bool contains = o.ContainsKey("PropertyNameValue"); Assert.AreEqual(true, contains); contains = o.ContainsKey("does not exist"); Assert.AreEqual(false, contains); ExceptionAssert.Throws<ArgumentNullException>(() => { contains = o.ContainsKey(null); Assert.AreEqual(false, contains); }, @"Value cannot be null. Parameter name: propertyName"); } [Test] public void GenericDictionaryContains() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); bool contains = ((IDictionary<string, JToken>)o).ContainsKey("PropertyNameValue"); Assert.AreEqual(true, contains); } [Test] public void GenericCollectionCopyTo() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); o.Add("PropertyNameValue3", new JValue(3)); Assert.AreEqual(3, o.Children().Count()); KeyValuePair<string, JToken>[] a = new KeyValuePair<string, JToken>[5]; ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(a, 1); Assert.AreEqual(default(KeyValuePair<string, JToken>), a[0]); Assert.AreEqual("PropertyNameValue", a[1].Key); Assert.AreEqual(1, (int)a[1].Value); Assert.AreEqual("PropertyNameValue2", a[2].Key); Assert.AreEqual(2, (int)a[2].Value); Assert.AreEqual("PropertyNameValue3", a[3].Key); Assert.AreEqual(3, (int)a[3].Value); Assert.AreEqual(default(KeyValuePair<string, JToken>), a[4]); } [Test] public void GenericCollectionCopyToNullArrayShouldThrow() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(null, 0); }, @"Value cannot be null. Parameter name: array"); } [Test] public void GenericCollectionCopyToNegativeArrayIndexShouldThrow() { ExceptionAssert.Throws<ArgumentOutOfRangeException>(() => { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], -1); }, @"arrayIndex is less than 0. Parameter name: arrayIndex"); } [Test] public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], 1); }, @"arrayIndex is equal to or greater than the length of array."); } [Test] public void GenericCollectionCopyToInsufficientArrayCapacity() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); o.Add("PropertyNameValue3", new JValue(3)); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[3], 1); }, @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array."); } [Test] public void FromObjectRaw() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); Assert.AreEqual("FirstNameValue", (string)o["first_name"]); Assert.AreEqual(JTokenType.Raw, ((JValue)o["RawContent"]).Type); Assert.AreEqual("[1,2,3,4,5]", (string)o["RawContent"]); Assert.AreEqual("LastNameValue", (string)o["last_name"]); } [Test] public void JTokenReader() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); JsonReader reader = new JTokenReader(o); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.String, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Raw, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.String, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.EndObject, reader.TokenType); Assert.IsFalse(reader.Read()); } [Test] public void DeserializeFromRaw() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); JsonReader reader = new JTokenReader(o); JsonSerializer serializer = new JsonSerializer(); raw = (PersonRaw)serializer.Deserialize(reader, typeof(PersonRaw)); Assert.AreEqual("FirstNameValue", raw.FirstName); Assert.AreEqual("LastNameValue", raw.LastName); Assert.AreEqual("[1,2,3,4,5]", raw.RawContent.Value); } [Test] public void Parse_ShouldThrowOnUnexpectedToken() { ExceptionAssert.Throws<JsonReaderException>(() => { string json = @"[""prop""]"; JObject.Parse(json); }, "Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1."); } [Test] public void ParseJavaScriptDate() { string json = @"[new Date(1207285200000)]"; JArray a = (JArray)JsonConvert.DeserializeObject(json); JValue v = (JValue)a[0]; Assert.AreEqual(DateTimeUtils.ConvertJavaScriptTicksToDateTime(1207285200000), (DateTime)v); } [Test] public void GenericValueCast() { string json = @"{""foo"":true}"; JObject o = (JObject)JsonConvert.DeserializeObject(json); bool? value = o.Value<bool?>("foo"); Assert.AreEqual(true, value); json = @"{""foo"":null}"; o = (JObject)JsonConvert.DeserializeObject(json); value = o.Value<bool?>("foo"); Assert.AreEqual(null, value); } [Test] public void Blog() { ExceptionAssert.Throws<JsonReaderException>(() => { JObject.Parse(@"{ ""name"": ""James"", ]!#$THIS IS: BAD JSON![{}}}}] }"); }, "Invalid property identifier character: ]. Path 'name', line 3, position 4."); } [Test] public void RawChildValues() { JObject o = new JObject(); o["val1"] = new JRaw("1"); o["val2"] = new JRaw("1"); string json = o.ToString(); StringAssert.AreEqual(@"{ ""val1"": 1, ""val2"": 1 }", json); } [Test] public void Iterate() { JObject o = new JObject(); o.Add("PropertyNameValue1", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); JToken t = o; int i = 1; foreach (JProperty property in t) { Assert.AreEqual("PropertyNameValue" + i, property.Name); Assert.AreEqual(i, (int)property.Value); i++; } } [Test] public void KeyValuePairIterate() { JObject o = new JObject(); o.Add("PropertyNameValue1", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); int i = 1; foreach (KeyValuePair<string, JToken> pair in o) { Assert.AreEqual("PropertyNameValue" + i, pair.Key); Assert.AreEqual(i, (int)pair.Value); i++; } } [Test] public void WriteObjectNullStringValue() { string s = null; JValue v = new JValue(s); Assert.AreEqual(null, v.Value); Assert.AreEqual(JTokenType.String, v.Type); JObject o = new JObject(); o["title"] = v; string output = o.ToString(); StringAssert.AreEqual(@"{ ""title"": null }", output); } [Test] public void Example() { string json = @"{ ""Name"": ""Apple"", ""Expiry"": new Date(1230422400000), ""Price"": 3.99, ""Sizes"": [ ""Small"", ""Medium"", ""Large"" ] }"; JObject o = JObject.Parse(json); string name = (string)o["Name"]; // Apple JArray sizes = (JArray)o["Sizes"]; string smallest = (string)sizes[0]; // Small Assert.AreEqual("Apple", name); Assert.AreEqual("Small", smallest); } [Test] public void DeserializeClassManually() { string jsonText = @"{ ""short"": { ""original"":""http://www.foo.com/"", ""short"":""krehqk"", ""error"": { ""code"":0, ""msg"":""No action taken"" } } }"; JObject json = JObject.Parse(jsonText); Shortie shortie = new Shortie { Original = (string)json["short"]["original"], Short = (string)json["short"]["short"], Error = new ShortieException { Code = (int)json["short"]["error"]["code"], ErrorMessage = (string)json["short"]["error"]["msg"] } }; Assert.AreEqual("http://www.foo.com/", shortie.Original); Assert.AreEqual("krehqk", shortie.Short); Assert.AreEqual(null, shortie.Shortened); Assert.AreEqual(0, shortie.Error.Code); Assert.AreEqual("No action taken", shortie.Error.ErrorMessage); } [Test] public void JObjectContainingHtml() { JObject o = new JObject(); o["rc"] = new JValue(200); o["m"] = new JValue(""); o["o"] = new JValue(@"<div class='s1'>" + StringUtils.CarriageReturnLineFeed + @"</div>"); StringAssert.AreEqual(@"{ ""rc"": 200, ""m"": """", ""o"": ""<div class='s1'>\r\n</div>"" }", o.ToString()); } [Test] public void ImplicitValueConversions() { JObject moss = new JObject(); moss["FirstName"] = new JValue("Maurice"); moss["LastName"] = new JValue("Moss"); moss["BirthDate"] = new JValue(new DateTime(1977, 12, 30)); moss["Department"] = new JValue("IT"); moss["JobTitle"] = new JValue("Support"); StringAssert.AreEqual(@"{ ""FirstName"": ""Maurice"", ""LastName"": ""Moss"", ""BirthDate"": ""1977-12-30T00:00:00"", ""Department"": ""IT"", ""JobTitle"": ""Support"" }", moss.ToString()); JObject jen = new JObject(); jen["FirstName"] = "Jen"; jen["LastName"] = "Barber"; jen["BirthDate"] = new DateTime(1978, 3, 15); jen["Department"] = "IT"; jen["JobTitle"] = "Manager"; StringAssert.AreEqual(@"{ ""FirstName"": ""Jen"", ""LastName"": ""Barber"", ""BirthDate"": ""1978-03-15T00:00:00"", ""Department"": ""IT"", ""JobTitle"": ""Manager"" }", jen.ToString()); } [Test] public void ReplaceJPropertyWithJPropertyWithSameName() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); JObject o = new JObject(p1, p2); IList l = o; Assert.AreEqual(p1, l[0]); Assert.AreEqual(p2, l[1]); JProperty p3 = new JProperty("Test1", "III"); p1.Replace(p3); Assert.AreEqual(null, p1.Parent); Assert.AreEqual(l, p3.Parent); Assert.AreEqual(p3, l[0]); Assert.AreEqual(p2, l[1]); Assert.AreEqual(2, l.Count); Assert.AreEqual(2, o.Properties().Count()); JProperty p4 = new JProperty("Test4", "IV"); p2.Replace(p4); Assert.AreEqual(null, p2.Parent); Assert.AreEqual(l, p4.Parent); Assert.AreEqual(p3, l[0]); Assert.AreEqual(p4, l[1]); } #if !(NET20 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 [Test] public void PropertyChanging() { object changing = null; object changed = null; int changingCount = 0; int changedCount = 0; JObject o = new JObject(); o.PropertyChanging += (sender, args) => { JObject s = (JObject)sender; changing = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changingCount++; }; o.PropertyChanged += (sender, args) => { JObject s = (JObject)sender; changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changedCount++; }; o["StringValue"] = "value1"; Assert.AreEqual(null, changing); Assert.AreEqual("value1", changed); Assert.AreEqual("value1", (string)o["StringValue"]); Assert.AreEqual(1, changingCount); Assert.AreEqual(1, changedCount); o["StringValue"] = "value1"; Assert.AreEqual(1, changingCount); Assert.AreEqual(1, changedCount); o["StringValue"] = "value2"; Assert.AreEqual("value1", changing); Assert.AreEqual("value2", changed); Assert.AreEqual("value2", (string)o["StringValue"]); Assert.AreEqual(2, changingCount); Assert.AreEqual(2, changedCount); o["StringValue"] = null; Assert.AreEqual("value2", changing); Assert.AreEqual(null, changed); Assert.AreEqual(null, (string)o["StringValue"]); Assert.AreEqual(3, changingCount); Assert.AreEqual(3, changedCount); o["NullValue"] = null; Assert.AreEqual(null, changing); Assert.AreEqual(null, changed); Assert.AreEqual(JValue.CreateNull(), o["NullValue"]); Assert.AreEqual(4, changingCount); Assert.AreEqual(4, changedCount); o["NullValue"] = null; Assert.AreEqual(4, changingCount); Assert.AreEqual(4, changedCount); } #endif [Test] public void PropertyChanged() { object changed = null; int changedCount = 0; JObject o = new JObject(); o.PropertyChanged += (sender, args) => { JObject s = (JObject)sender; changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changedCount++; }; o["StringValue"] = "value1"; Assert.AreEqual("value1", changed); Assert.AreEqual("value1", (string)o["StringValue"]); Assert.AreEqual(1, changedCount); o["StringValue"] = "value1"; Assert.AreEqual(1, changedCount); o["StringValue"] = "value2"; Assert.AreEqual("value2", changed); Assert.AreEqual("value2", (string)o["StringValue"]); Assert.AreEqual(2, changedCount); o["StringValue"] = null; Assert.AreEqual(null, changed); Assert.AreEqual(null, (string)o["StringValue"]); Assert.AreEqual(3, changedCount); o["NullValue"] = null; Assert.AreEqual(null, changed); Assert.AreEqual(JValue.CreateNull(), o["NullValue"]); Assert.AreEqual(4, changedCount); o["NullValue"] = null; Assert.AreEqual(4, changedCount); } [Test] public void IListContains() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.IsTrue(l.Contains(p)); Assert.IsFalse(l.Contains(new JProperty("Test", 1))); } [Test] public void IListIndexOf() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.AreEqual(0, l.IndexOf(p)); Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1))); } [Test] public void IListClear() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.AreEqual(1, l.Count); l.Clear(); Assert.AreEqual(0, l.Count); } [Test] public void IListCopyTo() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); object[] a = new object[l.Count]; l.CopyTo(a, 0); Assert.AreEqual(p1, a[0]); Assert.AreEqual(p2, a[1]); } [Test] public void IListAdd() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Add(p3); Assert.AreEqual(3, l.Count); Assert.AreEqual(p3, l[2]); } [Test] public void IListAddBadToken() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l.Add(new JValue("Bad!")); }, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."); } [Test] public void IListAddBadValue() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l.Add("Bad!"); }, "Argument is not a JToken."); } [Test] public void IListAddPropertyWithExistingName() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test2", "II"); l.Add(p3); }, "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } [Test] public void IListRemove() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); // won't do anything l.Remove(p3); Assert.AreEqual(2, l.Count); l.Remove(p1); Assert.AreEqual(1, l.Count); Assert.IsFalse(l.Contains(p1)); Assert.IsTrue(l.Contains(p2)); l.Remove(p2); Assert.AreEqual(0, l.Count); Assert.IsFalse(l.Contains(p2)); Assert.AreEqual(null, p2.Parent); } [Test] public void IListRemoveAt() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); // won't do anything l.RemoveAt(0); l.Remove(p1); Assert.AreEqual(1, l.Count); l.Remove(p2); Assert.AreEqual(0, l.Count); } [Test] public void IListInsert() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Insert(1, p3); Assert.AreEqual(l, p3.Parent); Assert.AreEqual(p1, l[0]); Assert.AreEqual(p3, l[1]); Assert.AreEqual(p2, l[2]); } [Test] public void IListIsReadOnly() { IList l = new JObject(); Assert.IsFalse(l.IsReadOnly); } [Test] public void IListIsFixedSize() { IList l = new JObject(); Assert.IsFalse(l.IsFixedSize); } [Test] public void IListSetItem() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; Assert.AreEqual(p3, l[0]); Assert.AreEqual(p2, l[1]); } [Test] public void IListSetItemAlreadyExists() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; l[1] = p3; }, "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } [Test] public void IListSetItemInvalid() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l[0] = new JValue(true); }, @"Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."); } [Test] public void IListSyncRoot() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); Assert.IsNotNull(l.SyncRoot); } [Test] public void IListIsSynchronized() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); Assert.IsFalse(l.IsSynchronized); } [Test] public void GenericListJTokenContains() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.IsTrue(l.Contains(p)); Assert.IsFalse(l.Contains(new JProperty("Test", 1))); } [Test] public void GenericListJTokenIndexOf() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.AreEqual(0, l.IndexOf(p)); Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1))); } [Test] public void GenericListJTokenClear() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.AreEqual(1, l.Count); l.Clear(); Assert.AreEqual(0, l.Count); } [Test] public void GenericListJTokenCopyTo() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JToken[] a = new JToken[l.Count]; l.CopyTo(a, 0); Assert.AreEqual(p1, a[0]); Assert.AreEqual(p2, a[1]); } [Test] public void GenericListJTokenAdd() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Add(p3); Assert.AreEqual(3, l.Count); Assert.AreEqual(p3, l[2]); } [Test] public void GenericListJTokenAddBadToken() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); l.Add(new JValue("Bad!")); }, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."); } [Test] public void GenericListJTokenAddBadValue() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); // string is implicitly converted to JValue l.Add("Bad!"); }, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."); } [Test] public void GenericListJTokenAddPropertyWithExistingName() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test2", "II"); l.Add(p3); }, "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } [Test] public void GenericListJTokenRemove() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); // won't do anything Assert.IsFalse(l.Remove(p3)); Assert.AreEqual(2, l.Count); Assert.IsTrue(l.Remove(p1)); Assert.AreEqual(1, l.Count); Assert.IsFalse(l.Contains(p1)); Assert.IsTrue(l.Contains(p2)); Assert.IsTrue(l.Remove(p2)); Assert.AreEqual(0, l.Count); Assert.IsFalse(l.Contains(p2)); Assert.AreEqual(null, p2.Parent); } [Test] public void GenericListJTokenRemoveAt() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); // won't do anything l.RemoveAt(0); l.Remove(p1); Assert.AreEqual(1, l.Count); l.Remove(p2); Assert.AreEqual(0, l.Count); } [Test] public void GenericListJTokenInsert() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Insert(1, p3); Assert.AreEqual(l, p3.Parent); Assert.AreEqual(p1, l[0]); Assert.AreEqual(p3, l[1]); Assert.AreEqual(p2, l[2]); } [Test] public void GenericListJTokenIsReadOnly() { IList<JToken> l = new JObject(); Assert.IsFalse(l.IsReadOnly); } [Test] public void GenericListJTokenSetItem() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; Assert.AreEqual(p3, l[0]); Assert.AreEqual(p2, l[1]); } [Test] public void GenericListJTokenSetItemAlreadyExists() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; l[1] = p3; }, "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } #if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 [Test] public void IBindingListSortDirection() { IBindingList l = new JObject(); Assert.AreEqual(ListSortDirection.Ascending, l.SortDirection); } [Test] public void IBindingListSortProperty() { IBindingList l = new JObject(); Assert.AreEqual(null, l.SortProperty); } [Test] public void IBindingListSupportsChangeNotification() { IBindingList l = new JObject(); Assert.AreEqual(true, l.SupportsChangeNotification); } [Test] public void IBindingListSupportsSearching() { IBindingList l = new JObject(); Assert.AreEqual(false, l.SupportsSearching); } [Test] public void IBindingListSupportsSorting() { IBindingList l = new JObject(); Assert.AreEqual(false, l.SupportsSorting); } [Test] public void IBindingListAllowEdit() { IBindingList l = new JObject(); Assert.AreEqual(true, l.AllowEdit); } [Test] public void IBindingListAllowNew() { IBindingList l = new JObject(); Assert.AreEqual(true, l.AllowNew); } [Test] public void IBindingListAllowRemove() { IBindingList l = new JObject(); Assert.AreEqual(true, l.AllowRemove); } [Test] public void IBindingListAddIndex() { IBindingList l = new JObject(); // do nothing l.AddIndex(null); } [Test] public void IBindingListApplySort() { ExceptionAssert.Throws<NotSupportedException>(() => { IBindingList l = new JObject(); l.ApplySort(null, ListSortDirection.Ascending); }, "Specified method is not supported."); } [Test] public void IBindingListRemoveSort() { ExceptionAssert.Throws<NotSupportedException>(() => { IBindingList l = new JObject(); l.RemoveSort(); }, "Specified method is not supported."); } [Test] public void IBindingListRemoveIndex() { IBindingList l = new JObject(); // do nothing l.RemoveIndex(null); } [Test] public void IBindingListFind() { ExceptionAssert.Throws<NotSupportedException>(() => { IBindingList l = new JObject(); l.Find(null, null); }, "Specified method is not supported."); } [Test] public void IBindingListIsSorted() { IBindingList l = new JObject(); Assert.AreEqual(false, l.IsSorted); } [Test] public void IBindingListAddNew() { ExceptionAssert.Throws<JsonException>(() => { IBindingList l = new JObject(); l.AddNew(); }, "Could not determine new value to add to 'Newtonsoft.Json.Linq.JObject'."); } [Test] public void IBindingListAddNewWithEvent() { JObject o = new JObject(); o._addingNew += (s, e) => e.NewObject = new JProperty("Property!"); IBindingList l = o; object newObject = l.AddNew(); Assert.IsNotNull(newObject); JProperty p = (JProperty)newObject; Assert.AreEqual("Property!", p.Name); Assert.AreEqual(o, p.Parent); } [Test] public void ITypedListGetListName() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); ITypedList l = new JObject(p1, p2); Assert.AreEqual(string.Empty, l.GetListName(null)); } [Test] public void ITypedListGetItemProperties() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); ITypedList l = new JObject(p1, p2); PropertyDescriptorCollection propertyDescriptors = l.GetItemProperties(null); Assert.IsNull(propertyDescriptors); } [Test] public void ListChanged() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); JObject o = new JObject(p1, p2); ListChangedType? changedType = null; int? index = null; o.ListChanged += (s, a) => { changedType = a.ListChangedType; index = a.NewIndex; }; JProperty p3 = new JProperty("Test3", "III"); o.Add(p3); Assert.AreEqual(changedType, ListChangedType.ItemAdded); Assert.AreEqual(index, 2); Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]); JProperty p4 = new JProperty("Test4", "IV"); ((IList<JToken>)o)[index.Value] = p4; Assert.AreEqual(changedType, ListChangedType.ItemChanged); Assert.AreEqual(index, 2); Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]); Assert.IsFalse(((IList<JToken>)o).Contains(p3)); Assert.IsTrue(((IList<JToken>)o).Contains(p4)); o["Test1"] = 2; Assert.AreEqual(changedType, ListChangedType.ItemChanged); Assert.AreEqual(index, 0); Assert.AreEqual(2, (int)o["Test1"]); } #endif #if !(NET20 || NET35 || PORTABLE40) || NETSTANDARD2_0 [Test] public void CollectionChanged() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); JObject o = new JObject(p1, p2); NotifyCollectionChangedAction? changedType = null; int? index = null; o._collectionChanged += (s, a) => { changedType = a.Action; index = a.NewStartingIndex; }; JProperty p3 = new JProperty("Test3", "III"); o.Add(p3); Assert.AreEqual(changedType, NotifyCollectionChangedAction.Add); Assert.AreEqual(index, 2); Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]); JProperty p4 = new JProperty("Test4", "IV"); ((IList<JToken>)o)[index.Value] = p4; Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace); Assert.AreEqual(index, 2); Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]); Assert.IsFalse(((IList<JToken>)o).Contains(p3)); Assert.IsTrue(((IList<JToken>)o).Contains(p4)); o["Test1"] = 2; Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace); Assert.AreEqual(index, 0); Assert.AreEqual(2, (int)o["Test1"]); } #endif [Test] public void GetGeocodeAddress() { string json = @"{ ""name"": ""Address: 435 North Mulford Road Rockford, IL 61107"", ""Status"": { ""code"": 200, ""request"": ""geocode"" }, ""Placemark"": [ { ""id"": ""p1"", ""address"": ""435 N Mulford Rd, Rockford, IL 61107, USA"", ""AddressDetails"": { ""Accuracy"" : 8, ""Country"" : { ""AdministrativeArea"" : { ""AdministrativeAreaName"" : ""IL"", ""SubAdministrativeArea"" : { ""Locality"" : { ""LocalityName"" : ""Rockford"", ""PostalCode"" : { ""PostalCodeNumber"" : ""61107"" }, ""Thoroughfare"" : { ""ThoroughfareName"" : ""435 N Mulford Rd"" } }, ""SubAdministrativeAreaName"" : ""Winnebago"" } }, ""CountryName"" : ""USA"", ""CountryNameCode"" : ""US"" } }, ""ExtendedData"": { ""LatLonBox"": { ""north"": 42.2753076, ""south"": 42.2690124, ""east"": -88.9964645, ""west"": -89.0027597 } }, ""Point"": { ""coordinates"": [ -88.9995886, 42.2721596, 0 ] } } ] }"; JObject o = JObject.Parse(json); string searchAddress = (string)o["Placemark"][0]["AddressDetails"]["Country"]["AdministrativeArea"]["SubAdministrativeArea"]["Locality"]["Thoroughfare"]["ThoroughfareName"]; Assert.AreEqual("435 N Mulford Rd", searchAddress); } [Test] public void SetValueWithInvalidPropertyName() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); o[0] = new JValue(3); }, "Set JObject values with invalid key value: 0. Object property name expected."); } [Test] public void SetValue() { object key = "TestKey"; JObject o = new JObject(); o[key] = new JValue(3); Assert.AreEqual(3, (int)o[key]); } [Test] public void ParseMultipleProperties() { string json = @"{ ""Name"": ""Name1"", ""Name"": ""Name2"" }"; JObject o = JObject.Parse(json); string value = (string)o["Name"]; Assert.AreEqual("Name2", value); } #if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 [Test] public void WriteObjectNullDBNullValue() { DBNull dbNull = DBNull.Value; JValue v = new JValue(dbNull); Assert.AreEqual(DBNull.Value, v.Value); Assert.AreEqual(JTokenType.Null, v.Type); JObject o = new JObject(); o["title"] = v; string output = o.ToString(); StringAssert.AreEqual(@"{ ""title"": null }", output); } #endif [Test] public void InvalidValueCastExceptionMessage() { ExceptionAssert.Throws<ArgumentException>(() => { string json = @"{ ""responseData"": {}, ""responseDetails"": null, ""responseStatus"": 200 }"; JObject o = JObject.Parse(json); string name = (string)o["responseData"]; }, "Can not convert Object to String."); } [Test] public void InvalidPropertyValueCastExceptionMessage() { ExceptionAssert.Throws<ArgumentException>(() => { string json = @"{ ""responseData"": {}, ""responseDetails"": null, ""responseStatus"": 200 }"; JObject o = JObject.Parse(json); string name = (string)o.Property("responseData"); }, "Can not convert Object to String."); } [Test] public void ParseIncomplete() { ExceptionAssert.Throws<Exception>(() => { JObject.Parse("{ foo:"); }, "Unexpected end of content while loading JObject. Path 'foo', line 1, position 6."); } [Test] public void LoadFromNestedObject() { string jsonText = @"{ ""short"": { ""error"": { ""code"":0, ""msg"":""No action taken"" } } }"; JsonReader reader = new JsonTextReader(new StringReader(jsonText)); reader.Read(); reader.Read(); reader.Read(); reader.Read(); reader.Read(); JObject o = (JObject)JToken.ReadFrom(reader); Assert.IsNotNull(o); StringAssert.AreEqual(@"{ ""code"": 0, ""msg"": ""No action taken"" }", o.ToString(Formatting.Indented)); } [Test] public void LoadFromNestedObjectIncomplete() { ExceptionAssert.Throws<JsonReaderException>(() => { string jsonText = @"{ ""short"": { ""error"": { ""code"":0"; JsonReader reader = new JsonTextReader(new StringReader(jsonText)); reader.Read(); reader.Read(); reader.Read(); reader.Read(); reader.Read(); JToken.ReadFrom(reader); }, "Unexpected end of content while loading JObject. Path 'short.error.code', line 6, position 14."); } #if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 [Test] public void GetProperties() { JObject o = JObject.Parse("{'prop1':12,'prop2':'hi!','prop3':null,'prop4':[1,2,3]}"); ICustomTypeDescriptor descriptor = o; PropertyDescriptorCollection properties = descriptor.GetProperties(); Assert.AreEqual(4, properties.Count); PropertyDescriptor prop1 = properties[0]; Assert.AreEqual("prop1", prop1.Name); Assert.AreEqual(typeof(object), prop1.PropertyType); Assert.AreEqual(typeof(JObject), prop1.ComponentType); Assert.AreEqual(false, prop1.CanResetValue(o)); Assert.AreEqual(false, prop1.ShouldSerializeValue(o)); PropertyDescriptor prop2 = properties[1]; Assert.AreEqual("prop2", prop2.Name); Assert.AreEqual(typeof(object), prop2.PropertyType); Assert.AreEqual(typeof(JObject), prop2.ComponentType); Assert.AreEqual(false, prop2.CanResetValue(o)); Assert.AreEqual(false, prop2.ShouldSerializeValue(o)); PropertyDescriptor prop3 = properties[2]; Assert.AreEqual("prop3", prop3.Name); Assert.AreEqual(typeof(object), prop3.PropertyType); Assert.AreEqual(typeof(JObject), prop3.ComponentType); Assert.AreEqual(false, prop3.CanResetValue(o)); Assert.AreEqual(false, prop3.ShouldSerializeValue(o)); PropertyDescriptor prop4 = properties[3]; Assert.AreEqual("prop4", prop4.Name); Assert.AreEqual(typeof(object), prop4.PropertyType); Assert.AreEqual(typeof(JObject), prop4.ComponentType); Assert.AreEqual(false, prop4.CanResetValue(o)); Assert.AreEqual(false, prop4.ShouldSerializeValue(o)); } #endif [Test] public void ParseEmptyObjectWithComment() { JObject o = JObject.Parse("{ /* A Comment */ }"); Assert.AreEqual(0, o.Count); } [Test] public void FromObjectTimeSpan() { JValue v = (JValue)JToken.FromObject(TimeSpan.FromDays(1)); Assert.AreEqual(v.Value, TimeSpan.FromDays(1)); Assert.AreEqual("1.00:00:00", v.ToString()); } [Test] public void FromObjectUri() { JValue v = (JValue)JToken.FromObject(new Uri("http://www.stuff.co.nz")); Assert.AreEqual(v.Value, new Uri("http://www.stuff.co.nz")); Assert.AreEqual("http://www.stuff.co.nz/", v.ToString()); } [Test] public void FromObjectGuid() { JValue v = (JValue)JToken.FromObject(new Guid("9065ACF3-C820-467D-BE50-8D4664BEAF35")); Assert.AreEqual(v.Value, new Guid("9065ACF3-C820-467D-BE50-8D4664BEAF35")); Assert.AreEqual("9065acf3-c820-467d-be50-8d4664beaf35", v.ToString()); } [Test] public void ParseAdditionalContent() { ExceptionAssert.Throws<JsonReaderException>(() => { string json = @"{ ""Name"": ""Apple"", ""Expiry"": new Date(1230422400000), ""Price"": 3.99, ""Sizes"": [ ""Small"", ""Medium"", ""Large"" ] }, 987987"; JObject o = JObject.Parse(json); }, "Additional text encountered after finished reading JSON content: ,. Path '', line 10, position 1."); } [Test] public void DeepEqualsIgnoreOrder() { JObject o1 = new JObject( new JProperty("null", null), new JProperty("integer", 1), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("array", new JArray(1, 2))); Assert.IsTrue(o1.DeepEquals(o1)); JObject o2 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 1), new JProperty("array", new JArray(1, 2))); Assert.IsTrue(o1.DeepEquals(o2)); JObject o3 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 2), new JProperty("array", new JArray(1, 2))); Assert.IsFalse(o1.DeepEquals(o3)); JObject o4 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 1), new JProperty("array", new JArray(2, 1))); Assert.IsFalse(o1.DeepEquals(o4)); JObject o5 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 1)); Assert.IsFalse(o1.DeepEquals(o5)); Assert.IsFalse(o1.DeepEquals(null)); } [Test] public void ToListOnEmptyObject() { JObject o = JObject.Parse(@"{}"); IList<JToken> l1 = o.ToList<JToken>(); Assert.AreEqual(0, l1.Count); IList<KeyValuePair<string, JToken>> l2 = o.ToList<KeyValuePair<string, JToken>>(); Assert.AreEqual(0, l2.Count); o = JObject.Parse(@"{'hi':null}"); l1 = o.ToList<JToken>(); Assert.AreEqual(1, l1.Count); l2 = o.ToList<KeyValuePair<string, JToken>>(); Assert.AreEqual(1, l2.Count); } [Test] public void EmptyObjectDeepEquals() { Assert.IsTrue(JToken.DeepEquals(new JObject(), new JObject())); JObject a = new JObject(); JObject b = new JObject(); b.Add("hi", "bye"); b.Remove("hi"); Assert.IsTrue(JToken.DeepEquals(a, b)); Assert.IsTrue(JToken.DeepEquals(b, a)); } [Test] public void GetValueBlogExample() { JObject o = JObject.Parse(@"{ 'name': 'Lower', 'NAME': 'Upper' }"); string exactMatch = (string)o.GetValue("NAME", StringComparison.OrdinalIgnoreCase); // Upper string ignoreCase = (string)o.GetValue("Name", StringComparison.OrdinalIgnoreCase); // Lower Assert.AreEqual("Upper", exactMatch); Assert.AreEqual("Lower", ignoreCase); } [Test] public void GetValue() { JObject a = new JObject(); a["Name"] = "Name!"; a["name"] = "name!"; a["title"] = "Title!"; Assert.AreEqual(null, a.GetValue("NAME", StringComparison.Ordinal)); Assert.AreEqual(null, a.GetValue("NAME")); Assert.AreEqual(null, a.GetValue("TITLE")); Assert.AreEqual("Name!", (string)a.GetValue("NAME", StringComparison.OrdinalIgnoreCase)); Assert.AreEqual("name!", (string)a.GetValue("name", StringComparison.Ordinal)); Assert.AreEqual(null, a.GetValue(null, StringComparison.Ordinal)); Assert.AreEqual(null, a.GetValue(null)); JToken v; Assert.IsFalse(a.TryGetValue("NAME", StringComparison.Ordinal, out v)); Assert.AreEqual(null, v); Assert.IsFalse(a.TryGetValue("NAME", out v)); Assert.IsFalse(a.TryGetValue("TITLE", out v)); Assert.IsTrue(a.TryGetValue("NAME", StringComparison.OrdinalIgnoreCase, out v)); Assert.AreEqual("Name!", (string)v); Assert.IsTrue(a.TryGetValue("name", StringComparison.Ordinal, out v)); Assert.AreEqual("name!", (string)v); Assert.IsFalse(a.TryGetValue(null, StringComparison.Ordinal, out v)); } public class FooJsonConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var token = JToken.FromObject(value, new JsonSerializer { ContractResolver = new CamelCasePropertyNamesContractResolver() }); if (token.Type == JTokenType.Object) { var o = (JObject)token; o.AddFirst(new JProperty("foo", "bar")); o.WriteTo(writer); } else { token.WriteTo(writer); } } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotSupportedException("This custom converter only supportes serialization and not deserialization."); } public override bool CanRead { get { return false; } } public override bool CanConvert(Type objectType) { return true; } } [Test] public void FromObjectInsideConverterWithCustomSerializer() { var p = new Person { Name = "Daniel Wertheim", }; var settings = new JsonSerializerSettings { Converters = new List<JsonConverter> { new FooJsonConverter() }, ContractResolver = new CamelCasePropertyNamesContractResolver() }; var json = JsonConvert.SerializeObject(p, settings); Assert.AreEqual(@"{""foo"":""bar"",""name"":""Daniel Wertheim"",""birthDate"":""0001-01-01T00:00:00"",""lastModified"":""0001-01-01T00:00:00""}", json); } [Test] public void Parse_NoComments() { string json = "{'prop':[1,2/*comment*/,3]}"; JObject o = JObject.Parse(json, new JsonLoadSettings { CommentHandling = CommentHandling.Ignore }); Assert.AreEqual(3, o["prop"].Count()); Assert.AreEqual(1, (int)o["prop"][0]); Assert.AreEqual(2, (int)o["prop"][1]); Assert.AreEqual(3, (int)o["prop"][2]); } [Test] public void Parse_ExcessiveContentJustComments() { string json = @"{'prop':[1,2,3]}/*comment*/ //Another comment."; JObject o = JObject.Parse(json); Assert.AreEqual(3, o["prop"].Count()); Assert.AreEqual(1, (int)o["prop"][0]); Assert.AreEqual(2, (int)o["prop"][1]); Assert.AreEqual(3, (int)o["prop"][2]); } [Test] public void Parse_ExcessiveContent() { string json = @"{'prop':[1,2,3]}/*comment*/ //Another comment. []"; ExceptionAssert.Throws<JsonReaderException>(() => JObject.Parse(json), "Additional text encountered after finished reading JSON content: [. Path '', line 3, position 0."); } #if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 [Test] public void GetPropertyOwner_ReturnsJObject() { ICustomTypeDescriptor o = new JObject { ["prop1"] = 1 }; PropertyDescriptorCollection properties = o.GetProperties(); Assert.AreEqual(1, properties.Count); PropertyDescriptor pd = properties[0]; Assert.AreEqual("prop1", pd.Name); object owner = o.GetPropertyOwner(pd); Assert.AreEqual(o, owner); object value = pd.GetValue(owner); Assert.AreEqual(1, (int)(JToken)value); } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime; using System.Runtime.CompilerServices; using EditorBrowsableState = System.ComponentModel.EditorBrowsableState; using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute; #pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)' #if BIT64 using nuint = System.UInt64; #else using nuint = System.UInt32; #endif namespace System { /// <summary> /// Span represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed /// or native memory, or to memory allocated on the stack. It is type- and memory-safe. /// </summary> public struct Span<T> { /// <summary>A byref or a native ptr.</summary> private readonly ByReference<T> _pointer; /// <summary>The number of elements this Span contains.</summary> #if PROJECTN [Bound] #endif private readonly int _length; /// <summary> /// Creates a new span over the entirety of the target array. /// </summary> /// <param name="array">The target array.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[] array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); _pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData())); _length = array.Length; } /// <summary> /// Creates a new span over the portion of the target array beginning /// at 'start' index and covering the remainder of the array. /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the span.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> is not in the range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[] array, int start) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); if ((uint)start > (uint)array.Length) ThrowHelper.ThrowArgumentOutOfRangeException(); _pointer = new ByReference<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start)); _length = array.Length - start; } /// <summary> /// Creates a new span over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the span.</param> /// <param name="length">The number of items in the span.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[] array, int start, int length) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); _pointer = new ByReference<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start)); _length = length; } /// <summary> /// Creates a new span over the target unmanaged buffer. Clearly this /// is quite dangerous, because we are creating arbitrarily typed T's /// out of a void*-typed block of memory. And the length is not checked. /// But if this creation is correct, then all subsequent uses are correct. /// </summary> /// <param name="pointer">An unmanaged pointer to memory.</param> /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="length"/> is negative. /// </exception> [CLSCompliant(false)] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe Span(void* pointer, int length) { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); if (length < 0) ThrowHelper.ThrowArgumentOutOfRangeException(); _pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref *(byte*)pointer)); _length = length; } /// <summary> /// Create a new span over a portion of a regular managed object. This can be useful /// if part of a managed object represents a "fixed array." This is dangerous because neither the /// <paramref name="length"/> is checked, nor <paramref name="obj"/> being null, nor the fact that /// "rawPointer" actually lies within <paramref name="obj"/>. /// </summary> /// <param name="obj">The managed object that contains the data to span over.</param> /// <param name="objectData">A reference to data within that object.</param> /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> DangerousCreate(object obj, ref T objectData, int length) => new Span<T>(ref objectData, length); // Constructor for internal use only. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Span(ref T ptr, int length) { Debug.Assert(length >= 0); _pointer = new ByReference<T>(ref ptr); _length = length; } /// <summary> /// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element /// would have been stored. Such a reference can be used for pinning but must never be dereferenced. /// </summary> public ref T DangerousGetPinnableReference() { return ref _pointer.Value; } /// <summary> /// The number of items in the span. /// </summary> public int Length => _length; /// <summary> /// Returns true if Length is 0. /// </summary> public bool IsEmpty => _length == 0; /// <summary> /// Returns a reference to specified element of the Span. /// </summary> /// <param name="index"></param> /// <returns></returns> /// <exception cref="System.IndexOutOfRangeException"> /// Thrown when index less than 0 or index greater than or equal to Length /// </exception> public ref T this[int index] { #if PROJECTN [BoundsChecking] get { return ref Unsafe.Add(ref _pointer.Value, index); } #else [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if ((uint)index >= (uint)_length) ThrowHelper.ThrowIndexOutOfRangeException(); return ref Unsafe.Add(ref _pointer.Value, index); } #endif } /// <summary> /// Clears the contents of this span. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Clear() { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { Span.ClearWithReferences(ref Unsafe.As<T, IntPtr>(ref _pointer.Value), (nuint)_length * (nuint)(Unsafe.SizeOf<T>() / sizeof(nuint))); } else { Span.ClearWithoutReferences(ref Unsafe.As<T, byte>(ref _pointer.Value), (nuint)_length * (nuint)Unsafe.SizeOf<T>()); } } /// <summary> /// Fills the contents of this span with the given value. /// </summary> public void Fill(T value) { if (Unsafe.SizeOf<T>() == 1) { uint length = (uint)_length; if (length == 0) return; T tmp = value; // Avoid taking address of the "value" argument. It would regress performance of the loop below. Unsafe.InitBlockUnaligned(ref Unsafe.As<T, byte>(ref _pointer.Value), Unsafe.As<T, byte>(ref tmp), length); } else { // Do all math as nuint to avoid unnecessary 64->32->64 bit integer truncations nuint length = (uint)_length; if (length == 0) return; ref T r = ref DangerousGetPinnableReference(); // TODO: Create block fill for value types of power of two sizes e.g. 2,4,8,16 nuint elementSize = (uint)Unsafe.SizeOf<T>(); nuint i = 0; for (; i < (length & ~(nuint)7); i += 8) { Unsafe.AddByteOffset<T>(ref r, (i + 0) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 1) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 2) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 3) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 4) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 5) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 6) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 7) * elementSize) = value; } if (i < (length & ~(nuint)3)) { Unsafe.AddByteOffset<T>(ref r, (i + 0) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 1) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 2) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 3) * elementSize) = value; i += 4; } for (; i < length; i++) { Unsafe.AddByteOffset<T>(ref r, i * elementSize) = value; } } } /// <summary> /// Copies the contents of this span into destination span. If the source /// and destinations overlap, this method behaves as if the original values in /// a temporary location before the destination is overwritten. /// </summary> /// <param name="destination">The span to copy items into.</param> /// <exception cref="System.ArgumentException"> /// Thrown when the destination Span is shorter than the source Span. /// </exception> public void CopyTo(Span<T> destination) { if (!TryCopyTo(destination)) ThrowHelper.ThrowArgumentException_DestinationTooShort(); } /// <summary> /// Copies the contents of this span into destination span. If the source /// and destinations overlap, this method behaves as if the original values in /// a temporary location before the destination is overwritten. /// </summary> /// <param name="destination">The span to copy items into.</param> /// <returns>If the destination span is shorter than the source span, this method /// return false and no data is written to the destination.</returns> public bool TryCopyTo(Span<T> destination) { if ((uint)_length > (uint)destination.Length) return false; Span.CopyTo<T>(ref destination._pointer.Value, ref _pointer.Value, _length); return true; } /// <summary> /// Returns true if left and right point at the same memory and have the same length. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public static bool operator ==(Span<T> left, Span<T> right) { return left._length == right._length && Unsafe.AreSame<T>(ref left._pointer.Value, ref right._pointer.Value); } /// <summary> /// Returns false if left and right point at the same memory and have the same length. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public static bool operator !=(Span<T> left, Span<T> right) => !(left == right); /// <summary> /// This method is not supported as spans cannot be boxed. To compare two spans, use operator==. /// <exception cref="System.NotSupportedException"> /// Always thrown by this method. /// </exception> /// </summary> [Obsolete("Equals() on Span will always throw an exception. Use == instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { throw new NotSupportedException(SR.NotSupported_CannotCallEqualsOnSpan); } /// <summary> /// This method is not supported as spans cannot be boxed. /// <exception cref="System.NotSupportedException"> /// Always thrown by this method. /// </exception> /// </summary> [Obsolete("GetHashCode() on Span will always throw an exception.")] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { throw new NotSupportedException(SR.NotSupported_CannotCallGetHashCodeOnSpan); } /// <summary> /// Defines an implicit conversion of an array to a <see cref="Span{T}"/> /// </summary> public static implicit operator Span<T>(T[] array) => new Span<T>(array); /// <summary> /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Span{T}"/> /// </summary> public static implicit operator Span<T>(ArraySegment<T> arraySegment) => new Span<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count); /// <summary> /// Defines an implicit conversion of a <see cref="Span{T}"/> to a <see cref="ReadOnlySpan{T}"/> /// </summary> public static implicit operator ReadOnlySpan<T>(Span<T> span) => new ReadOnlySpan<T>(ref span._pointer.Value, span._length); /// <summary> /// Forms a slice out of the given span, beginning at 'start'. /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start) { if ((uint)start > (uint)_length) ThrowHelper.ThrowArgumentOutOfRangeException(); return new Span<T>(ref Unsafe.Add(ref _pointer.Value, start), _length - start); } /// <summary> /// Forms a slice out of the given span, beginning at 'start', of given length /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The desired length for the slice (exclusive).</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); return new Span<T>(ref Unsafe.Add(ref _pointer.Value, start), length); } /// <summary> /// Copies the contents of this span into a new array. This heap /// allocates, so should generally be avoided, however it is sometimes /// necessary to bridge the gap with APIs written in terms of arrays. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public T[] ToArray() { if (_length == 0) return Array.Empty<T>(); var destination = new T[_length]; Span.CopyTo<T>(ref Unsafe.As<byte, T>(ref destination.GetRawSzArrayData()), ref _pointer.Value, _length); return destination; } // <summary> /// Returns an empty <see cref="Span{T}"/> /// </summary> public static Span<T> Empty => default(Span<T>); } }
// 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.ComponentModel.Composition.AttributedModel; using System.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Primitives; using System.ComponentModel.Composition.ReflectionModel; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; using Microsoft.Internal; namespace System.ComponentModel.Composition { public static class AttributedModelServices { [SuppressMessage("Microsoft.Design", "CA1004")] public static TMetadataView GetMetadataView<TMetadataView>(IDictionary<string, object> metadata) { Requires.NotNull(metadata, nameof(metadata)); Contract.Ensures(Contract.Result<TMetadataView>() != null); return MetadataViewProvider.GetMetadataView<TMetadataView>(metadata); } public static ComposablePart CreatePart(object attributedPart) { Requires.NotNull(attributedPart, nameof(attributedPart)); Contract.Ensures(Contract.Result<ComposablePart>() != null); return AttributedModelDiscovery.CreatePart(attributedPart); } public static ComposablePart CreatePart(object attributedPart, ReflectionContext reflectionContext) { Requires.NotNull(attributedPart, "attributedPart"); Requires.NotNull(reflectionContext, "reflectionContext"); Contract.Ensures(Contract.Result<ComposablePart>() != null); return AttributedModelDiscovery.CreatePart(attributedPart, reflectionContext); } public static ComposablePart CreatePart(ComposablePartDefinition partDefinition, object attributedPart) { Requires.NotNull(partDefinition, nameof(partDefinition)); Requires.NotNull(attributedPart, nameof(attributedPart)); Contract.Ensures(Contract.Result<ComposablePart>() != null); var reflectionComposablePartDefinition = partDefinition as ReflectionComposablePartDefinition; if(reflectionComposablePartDefinition == null) { throw ExceptionBuilder.CreateReflectionModelInvalidPartDefinition("partDefinition", partDefinition.GetType()); } return AttributedModelDiscovery.CreatePart(reflectionComposablePartDefinition, attributedPart); } public static ComposablePartDefinition CreatePartDefinition(Type type, ICompositionElement origin) { Requires.NotNull(type, nameof(type)); Contract.Ensures(Contract.Result<ComposablePartDefinition>() != null); return AttributedModelServices.CreatePartDefinition(type, origin, false); } public static ComposablePartDefinition CreatePartDefinition(Type type, ICompositionElement origin, bool ensureIsDiscoverable) { Requires.NotNull(type, nameof(type)); if (ensureIsDiscoverable) { return AttributedModelDiscovery.CreatePartDefinitionIfDiscoverable(type, origin); } else { return AttributedModelDiscovery.CreatePartDefinition(type, null, false, origin); } } public static string GetTypeIdentity(Type type) { Requires.NotNull(type, nameof(type)); Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>())); return ContractNameServices.GetTypeIdentity(type); } public static string GetTypeIdentity(MethodInfo method) { Requires.NotNull(method, nameof(method)); Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>())); return ContractNameServices.GetTypeIdentityFromMethod(method); } public static string GetContractName(Type type) { Requires.NotNull(type, nameof(type)); Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>())); return AttributedModelServices.GetTypeIdentity(type); } public static ComposablePart AddExportedValue<T>(this CompositionBatch batch, T exportedValue) { Requires.NotNull(batch, nameof(batch)); Contract.Ensures(Contract.Result<ComposablePart>() != null); string contractName = AttributedModelServices.GetContractName(typeof(T)); return batch.AddExportedValue<T>(contractName, exportedValue); } public static void ComposeExportedValue<T>(this CompositionContainer container, T exportedValue) { Requires.NotNull(container, nameof(container)); CompositionBatch batch = new CompositionBatch(); batch.AddExportedValue<T>(exportedValue); container.Compose(batch); } public static ComposablePart AddExportedValue<T>(this CompositionBatch batch, string contractName, T exportedValue) { Requires.NotNull(batch, nameof(batch)); Contract.Ensures(Contract.Result<ComposablePart>() != null); string typeIdentity = AttributedModelServices.GetTypeIdentity(typeof(T)); IDictionary<string, object> metadata = new Dictionary<string, object>(); metadata.Add(CompositionConstants.ExportTypeIdentityMetadataName, typeIdentity); return batch.AddExport(new Export(contractName, metadata, () => exportedValue)); } public static void ComposeExportedValue<T>(this CompositionContainer container, string contractName, T exportedValue) { Requires.NotNull(container, nameof(container)); CompositionBatch batch = new CompositionBatch(); batch.AddExportedValue<T>(contractName, exportedValue); container.Compose(batch); } public static ComposablePart AddPart(this CompositionBatch batch, object attributedPart) { Requires.NotNull(batch, nameof(batch)); Requires.NotNull(attributedPart, nameof(attributedPart)); Contract.Ensures(Contract.Result<ComposablePart>() != null); ComposablePart part = AttributedModelServices.CreatePart(attributedPart); batch.AddPart(part); return part; } public static void ComposeParts(this CompositionContainer container, params object[] attributedParts) { Requires.NotNull(container, nameof(container)); Requires.NotNullOrNullElements(attributedParts, "attributedParts"); CompositionBatch batch = new CompositionBatch( attributedParts.Select(attributedPart => AttributedModelServices.CreatePart(attributedPart)).ToArray(), Enumerable.Empty<ComposablePart>()); container.Compose(batch); } /// <summary> /// Satisfies the imports of the specified attributed object exactly once and they will not /// ever be recomposed. /// </summary> /// <param name="part"> /// The attributed object to set the imports. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="compositionService"/> or <paramref name="attributedPart"/> is <see langword="null"/>. /// </exception> /// <exception cref="CompositionException"> /// An error occurred during composition. <see cref="CompositionException.Errors"/> will /// contain a collection of errors that occurred. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="ICompositionService"/> has been disposed of. /// </exception> public static ComposablePart SatisfyImportsOnce(this ICompositionService compositionService, object attributedPart) { Requires.NotNull(compositionService, nameof(compositionService)); Requires.NotNull(attributedPart, nameof(attributedPart)); Contract.Ensures(Contract.Result<ComposablePart>() != null); ComposablePart part = AttributedModelServices.CreatePart(attributedPart); compositionService.SatisfyImportsOnce(part); return part; } /// <summary> /// Satisfies the imports of the specified attributed object exactly once and they will not /// ever be recomposed. /// </summary> /// <param name="part"> /// The attributed object to set the imports. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="compositionService"/> or <paramref name="attributedPart"/> or <paramref name="reflectionContext"/> is <see langword="null"/>. /// </exception> /// <exception cref="CompositionException"> /// An error occurred during composition. <see cref="CompositionException.Errors"/> will /// contain a collection of errors that occurred. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="ICompositionService"/> has been disposed of. /// </exception> public static ComposablePart SatisfyImportsOnce(this ICompositionService compositionService, object attributedPart, ReflectionContext reflectionContext) { Requires.NotNull(compositionService, "compositionService"); Requires.NotNull(attributedPart, "attributedPart"); Requires.NotNull(reflectionContext, "reflectionContext"); Contract.Ensures(Contract.Result<ComposablePart>() != null); ComposablePart part = AttributedModelServices.CreatePart(attributedPart, reflectionContext); compositionService.SatisfyImportsOnce(part); return part; } /// <summary> /// Determines whether the specified part exports the specified contract. /// </summary> /// <param name="part">The part.</param> /// <param name="contractType">Type of the contract.</param> /// <returns> /// <c>true</c> if the specified part exports the specified contract; otherwise, <c>false</c>. /// </returns> public static bool Exports(this ComposablePartDefinition part, Type contractType) { Requires.NotNull(part, nameof(part)); Requires.NotNull(contractType, nameof(contractType)); return part.Exports(AttributedModelServices.GetContractName(contractType)); } /// <summary> /// Determines whether the specified part exports the specified contract. /// </summary> /// <typeparam name="T">Type of the contract.</typeparam> /// <param name="part">The part.</param> /// <returns> /// <c>true</c> if the specified part exports the specified contract; otherwise, <c>false</c>. /// </returns> public static bool Exports<T>(this ComposablePartDefinition part) { Requires.NotNull(part, nameof(part)); return part.Exports(typeof(T)); } /// <summary> /// Determines whether the specified part imports the specified contract. /// </summary> /// <param name="part">The part.</param> /// <param name="contractType">Type of the contract.</param> /// <returns> /// <c>true</c> if the specified part imports the specified contract; otherwise, <c>false</c>. /// </returns> public static bool Imports(this ComposablePartDefinition part, Type contractType) { Requires.NotNull(part, nameof(part)); Requires.NotNull(contractType, nameof(contractType)); return part.Imports(AttributedModelServices.GetContractName(contractType)); } /// <summary> /// Determines whether the specified part imports the specified contract. /// </summary> /// <param name="part">The part.</param> /// <typeparam name="T">Type of the contract.</typeparam> /// <returns> /// <c>true</c> if the specified part imports the specified contract; otherwise, <c>false</c>. /// </returns> public static bool Imports<T>(this ComposablePartDefinition part) { Requires.NotNull(part, nameof(part)); return part.Imports(typeof(T)); } /// <summary> /// Determines whether the specified part imports the specified contract with the given cardinality. /// </summary> /// <param name="part">The part.</param> /// <param name="contractType">Type of the contract.</param> /// <param name="importCardinality">The import cardinality.</param> /// <returns> /// <c>true</c> if the specified part imports the specified contract with the given cardinality; otherwise, <c>false</c>. /// </returns> public static bool Imports(this ComposablePartDefinition part, Type contractType, ImportCardinality importCardinality) { Requires.NotNull(part, nameof(part)); Requires.NotNull(contractType, nameof(contractType)); return part.Imports(AttributedModelServices.GetContractName(contractType), importCardinality); } /// <summary> /// Determines whether the specified part imports the specified contract with the given cardinality. /// </summary> /// <param name="part">The part.</param> /// <typeparam name="T">Type of the contract.</typeparam> /// <param name="importCardinality">The import cardinality.</param> /// <returns> /// <c>true</c> if the specified part imports the specified contract with the given cardinality; otherwise, <c>false</c>. /// </returns> public static bool Imports<T>(this ComposablePartDefinition part, ImportCardinality importCardinality) { Requires.NotNull(part, nameof(part)); return part.Imports(typeof(T), importCardinality); } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Build.Construction; using Microsoft.DotNet.Tools.Test.Utilities; using System.IO; using System.Linq; using Xunit; using FluentAssertions; using Microsoft.DotNet.ProjectJsonMigration.Rules; using System; namespace Microsoft.DotNet.ProjectJsonMigration.Tests { public class GivenThatIWantToMigratePackOptions : TestBase { [Fact] public void ItDoesNotMigrateSummary() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""summary"": ""Some not important summary"" } }"); EmitsOnlyAlwaysEmittedPackOptionsProperties(mockProj); } [Fact] public void ItDoesNotMigrateOwner() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""owner"": ""Some not important owner"" } }"); EmitsOnlyAlwaysEmittedPackOptionsProperties(mockProj); } [Fact] public void MigratingEmptyTagsDoesNotPopulatePackageTags() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""tags"": [] } }"); mockProj.Properties.Count(p => p.Name == "PackageTags").Should().Be(0); } [Fact] public void MigratingTagsPopulatesPackageTagsSemicolonDelimited() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""tags"": [""hyperscale"", ""cats""] } }"); mockProj.Properties.Count(p => p.Name == "PackageTags").Should().Be(1); mockProj.Properties.First(p => p.Name == "PackageTags").Value.Should().Be("hyperscale;cats"); } [Fact] public void MigratingReleaseNotesPopulatesPackageReleaseNotes() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""releaseNotes"": ""Some release notes value."" } }"); mockProj.Properties.Count(p => p.Name == "PackageReleaseNotes").Should().Be(1); mockProj.Properties.First(p => p.Name == "PackageReleaseNotes").Value.Should() .Be("Some release notes value."); } [Fact] public void MigratingIconUrlPopulatesPackageIconUrl() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""iconUrl"": ""http://www.mylibrary.gov/favicon.ico"" } }"); mockProj.Properties.Count(p => p.Name == "PackageIconUrl").Should().Be(1); mockProj.Properties.First(p => p.Name == "PackageIconUrl").Value.Should() .Be("http://www.mylibrary.gov/favicon.ico"); } [Fact] public void MigratingProjectUrlPopulatesPackageProjectUrl() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""projectUrl"": ""http://www.url.to.library.com"" } }"); mockProj.Properties.Count(p => p.Name == "PackageProjectUrl").Should().Be(1); mockProj.Properties.First(p => p.Name == "PackageProjectUrl").Value.Should() .Be("http://www.url.to.library.com"); } [Fact] public void MigratingLicenseUrlPopulatesPackageLicenseUrl() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""licenseUrl"": ""http://www.url.to.library.com/licence"" } }"); mockProj.Properties.Count(p => p.Name == "PackageLicenseUrl").Should().Be(1); mockProj.Properties.First(p => p.Name == "PackageLicenseUrl").Value.Should() .Be("http://www.url.to.library.com/licence"); } [Fact] public void MigratingRequireLicenseAcceptancePopulatesPackageRequireLicenseAcceptance() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""requireLicenseAcceptance"": ""true"" } }"); mockProj.Properties.Count(p => p.Name == "PackageRequireLicenseAcceptance").Should().Be(1); mockProj.Properties.First(p => p.Name == "PackageRequireLicenseAcceptance").Value.Should().Be("true"); } [Fact] public void MigratingRequireLicenseAcceptancePopulatesPackageRequireLicenseAcceptanceEvenIfItsValueIsFalse() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""requireLicenseAcceptance"": ""false"" } }"); mockProj.Properties.Count(p => p.Name == "PackageRequireLicenseAcceptance").Should().Be(1); mockProj.Properties.First(p => p.Name == "PackageRequireLicenseAcceptance").Value.Should().Be("false"); } [Fact] public void MigratingRepositoryTypePopulatesRepositoryType() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""repository"": { ""type"": ""git"" } } }"); mockProj.Properties.Count(p => p.Name == "RepositoryType").Should().Be(1); mockProj.Properties.First(p => p.Name == "RepositoryType").Value.Should().Be("git"); } [Fact] public void MigratingRepositoryUrlPopulatesRepositoryUrl() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""repository"": { ""url"": ""http://github.com/dotnet/cli"" } } }"); mockProj.Properties.Count(p => p.Name == "RepositoryUrl").Should().Be(1); mockProj.Properties.First(p => p.Name == "RepositoryUrl").Value.Should().Be("http://github.com/dotnet/cli"); } [Fact] public void MigratingFilesWithoutMappingsPopulatesContentWithSamePathAsIncludeAndPackTrue() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""files"": { ""include"": [""path/to/some/file.cs"", ""path/to/some/other/file.cs""] } } }"); var contentItems = mockProj.Items .Where(item => item.ItemType.Equals("None", StringComparison.Ordinal)) .Where(item => item.GetMetadataWithName("Pack").Value == "true"); contentItems.Count().Should().Be(1); contentItems.First().Update.Should().Be(@"path\to\some\file.cs;path\to\some\other\file.cs"); } [Fact] public void MigratingFilesWithExcludePopulatesNoneWithPackFalseForTheExcludedFiles() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""files"": { ""include"": [""path/to/some/file.cs"", ""path/to/some/other/file.cs""], ""exclude"": [""path/to/file/to/exclude.cs""] } } }"); foreach (var item in mockProj.Items.Where(i => i.ItemType.Equals("None", StringComparison.Ordinal))) { Console.WriteLine($"Update: {item.Update}, Include: {item.Include}, Remove: {item.Remove}"); foreach(var meta in item.Metadata) { Console.WriteLine($"\tMetadata: Name: {meta.Name}, Value: {meta.Value}"); } foreach(var condition in item.ConditionChain()) { Console.WriteLine($"\tCondition: {condition}"); } } var contentItemsToInclude = mockProj.Items .Where(item => item.ItemType.Equals("None", StringComparison.Ordinal)) .Where(item => item.GetMetadataWithName("Pack").Value == "true"); contentItemsToInclude.Count().Should().Be(1); contentItemsToInclude.First().Update.Should().Be(@"path\to\some\file.cs;path\to\some\other\file.cs"); var contentItemsToExclude = mockProj.Items .Where(item => item.ItemType.Equals("None", StringComparison.Ordinal)) .Where(item => item.GetMetadataWithName("Pack").Value == "false"); contentItemsToExclude.Count().Should().Be(1); contentItemsToExclude.First().Update.Should().Be(@"path\to\file\to\exclude.cs"); } [Fact] public void MigratingFilesWithMappingsPopulatesContentPackagePathMetadata() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""files"": { ""include"": [""path/to/some/file.cs""], ""mappings"": { ""some/other/path/file.cs"": ""path/to/some/file.cs"" } } } }"); var contentItems = mockProj.Items .Where(item => item.ItemType.Equals("None", StringComparison.Ordinal)) .Where(item => item.GetMetadataWithName("Pack").Value == "true" && item.GetMetadataWithName("PackagePath") != null); contentItems.Count().Should().Be(1); contentItems.First().Update.Should().Be(@"path\to\some\file.cs"); contentItems.First().GetMetadataWithName("PackagePath").Value.Should().Be( Path.Combine("some", "other", "path")); } [Fact] public void MigratingFilesWithMappingsToRootPopulatesContentPackagePathMetadataButLeavesItEmpty() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""files"": { ""include"": [""path/to/some/file.cs""], ""mappings"": { "".file.cs"": ""path/to/some/file.cs"" } } } }"); var contentItems = mockProj.Items .Where(item => item.ItemType.Equals("None", StringComparison.Ordinal)) .Where(item => item.GetMetadataWithName("Pack").Value == "true" && item.GetMetadataWithName("PackagePath") != null); contentItems.Count().Should().Be(1); contentItems.First().Update.Should().Be(@"path\to\some\file.cs"); contentItems.First().GetMetadataWithName("PackagePath").Value.Should().BeEmpty(); } [Fact] public void MigratingSameFileWithMultipleMappingsStringJoinsTheMappingsInPackagePath() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""files"": { ""include"": [""path/to/some/file.cs""], ""mappings"": { ""other/path/file.cs"": ""path/to/some/file.cs"", ""different/path/file1.cs"": ""path/to/some/file.cs"" } } } }"); var expectedPackagePath = string.Join( ";", new [] { Path.Combine("different", "path"), Path.Combine("other", "path") }); var contentItems = mockProj.Items .Where(item => item.ItemType.Equals("None", StringComparison.Ordinal)) .Where(item => item.GetMetadataWithName("Pack").Value == "true" && item.GetMetadataWithName("PackagePath") != null); contentItems.Count().Should().Be(1); contentItems.First().Update.Should().Be(@"path\to\some\file.cs"); contentItems.First().GetMetadataWithName("PackagePath").Value.Should().Be(expectedPackagePath); } private ProjectRootElement RunPackOptionsRuleOnPj(string packOptions, string testDirectory = null) { testDirectory = testDirectory ?? Temp.CreateDirectory().Path; return TemporaryProjectFileRuleRunner.RunRules(new IMigrationRule[] { new MigratePackOptionsRule() }, packOptions, testDirectory); } private void EmitsOnlyAlwaysEmittedPackOptionsProperties(ProjectRootElement project) { project.Properties.Count().Should().Be(1); project.Properties.All(p => p.Name == "PackageRequireLicenseAcceptance").Should().BeTrue(); } } }
/* * Copyright 2002-2015 Drew Noakes * * Modified by Yakov Danilov <yakodani@gmail.com> for Imazen LLC (Ported from Java to C#) * 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. * * More information about this project is available at: * * https://drewnoakes.com/code/exif/ * https://github.com/drewnoakes/metadata-extractor */ using System.Collections.Generic; using System.IO; using Com.Drew.Lang; using JetBrains.Annotations; using Sharpen; namespace Com.Drew.Metadata.Exif.Makernotes { /// <summary> /// The Olympus makernote is used by many manufacturers (Epson, Konica, Minolta and Agfa...), and as such contains some tags /// that appear specific to those manufacturers. /// </summary> /// <author>Drew Noakes https://drewnoakes.com</author> public class OlympusMakernoteDirectory : Com.Drew.Metadata.Directory { /// <summary>Used by Konica / Minolta cameras.</summary> public const int TagMakernoteVersion = unchecked((int)(0x0000)); /// <summary>Used by Konica / Minolta cameras.</summary> public const int TagCameraSettings1 = unchecked((int)(0x0001)); /// <summary>Alternate Camera Settings Tag.</summary> /// <remarks>Alternate Camera Settings Tag. Used by Konica / Minolta cameras.</remarks> public const int TagCameraSettings2 = unchecked((int)(0x0003)); /// <summary>Used by Konica / Minolta cameras.</summary> public const int TagCompressedImageSize = unchecked((int)(0x0040)); /// <summary>Used by Konica / Minolta cameras.</summary> public const int TagMinoltaThumbnailOffset1 = unchecked((int)(0x0081)); /// <summary>Alternate Thumbnail Offset.</summary> /// <remarks>Alternate Thumbnail Offset. Used by Konica / Minolta cameras.</remarks> public const int TagMinoltaThumbnailOffset2 = unchecked((int)(0x0088)); /// <summary>Length of thumbnail in bytes.</summary> /// <remarks>Length of thumbnail in bytes. Used by Konica / Minolta cameras.</remarks> public const int TagMinoltaThumbnailLength = unchecked((int)(0x0089)); public const int TagThumbnailImage = unchecked((int)(0x0100)); /// <summary> /// Used by Konica / Minolta cameras /// 0 = Natural Colour /// 1 = Black &amp; White /// 2 = Vivid colour /// 3 = Solarization /// 4 = AdobeRGB /// </summary> public const int TagColourMode = unchecked((int)(0x0101)); /// <summary>Used by Konica / Minolta cameras.</summary> /// <remarks> /// Used by Konica / Minolta cameras. /// 0 = Raw /// 1 = Super Fine /// 2 = Fine /// 3 = Standard /// 4 = Extra Fine /// </remarks> public const int TagImageQuality1 = unchecked((int)(0x0102)); /// <summary>Not 100% sure about this tag.</summary> /// <remarks> /// Not 100% sure about this tag. /// <p> /// Used by Konica / Minolta cameras. /// 0 = Raw /// 1 = Super Fine /// 2 = Fine /// 3 = Standard /// 4 = Extra Fine /// </remarks> public const int TagImageQuality2 = unchecked((int)(0x0103)); public const int TagBodyFirmwareVersion = unchecked((int)(0x0104)); /// <summary> /// Three values: /// Value 1: 0=Normal, 2=Fast, 3=Panorama /// Value 2: Sequence Number Value 3: /// 1 = Panorama Direction: Left to Right /// 2 = Panorama Direction: Right to Left /// 3 = Panorama Direction: Bottom to Top /// 4 = Panorama Direction: Top to Bottom /// </summary> public const int TagSpecialMode = unchecked((int)(0x0200)); /// <summary> /// 1 = Standard Quality /// 2 = High Quality /// 3 = Super High Quality /// </summary> public const int TagJpegQuality = unchecked((int)(0x0201)); /// <summary> /// 0 = Normal (Not Macro) /// 1 = Macro /// </summary> public const int TagMacroMode = unchecked((int)(0x0202)); /// <summary>0 = Off, 1 = On</summary> public const int TagBwMode = unchecked((int)(0x0203)); /// <summary>Zoom Factor (0 or 1 = normal)</summary> public const int TagDigiZoomRatio = unchecked((int)(0x0204)); public const int TagFocalPlaneDiagonal = unchecked((int)(0x0205)); public const int TagLensDistortionParameters = unchecked((int)(0x0206)); public const int TagFirmwareVersion = unchecked((int)(0x0207)); public const int TagPictInfo = unchecked((int)(0x0208)); public const int TagCameraId = unchecked((int)(0x0209)); /// <summary> /// Used by Epson cameras /// Units = pixels /// </summary> public const int TagImageWidth = unchecked((int)(0x020B)); /// <summary> /// Used by Epson cameras /// Units = pixels /// </summary> public const int TagImageHeight = unchecked((int)(0x020C)); /// <summary>A string.</summary> /// <remarks>A string. Used by Epson cameras.</remarks> public const int TagOriginalManufacturerModel = unchecked((int)(0x020D)); public const int TagPreviewImage = unchecked((int)(0x0280)); public const int TagPreCaptureFrames = unchecked((int)(0x0300)); public const int TagWhiteBoard = unchecked((int)(0x0301)); public const int TagOneTouchWb = unchecked((int)(0x0302)); public const int TagWhiteBalanceBracket = unchecked((int)(0x0303)); public const int TagWhiteBalanceBias = unchecked((int)(0x0304)); public const int TagSceneMode = unchecked((int)(0x0403)); public const int TagFirmware = unchecked((int)(0x0404)); /// <summary> /// See the PIM specification here: /// http://www.ozhiker.com/electronics/pjmt/jpeg_info/pim.html /// </summary> public const int TagPrintImageMatchingInfo = unchecked((int)(0x0E00)); public const int TagDataDump1 = unchecked((int)(0x0F00)); public const int TagDataDump2 = unchecked((int)(0x0F01)); public const int TagShutterSpeedValue = unchecked((int)(0x1000)); public const int TagIsoValue = unchecked((int)(0x1001)); public const int TagApertureValue = unchecked((int)(0x1002)); public const int TagBrightnessValue = unchecked((int)(0x1003)); public const int TagFlashMode = unchecked((int)(0x1004)); public const int TagFlashDevice = unchecked((int)(0x1005)); public const int TagBracket = unchecked((int)(0x1006)); public const int TagSensorTemperature = unchecked((int)(0x1007)); public const int TagLensTemperature = unchecked((int)(0x1008)); public const int TagLightCondition = unchecked((int)(0x1009)); public const int TagFocusRange = unchecked((int)(0x100A)); public const int TagFocusMode = unchecked((int)(0x100B)); public const int TagFocusDistance = unchecked((int)(0x100C)); public const int TagZoom = unchecked((int)(0x100D)); public const int TagMacroFocus = unchecked((int)(0x100E)); public const int TagSharpness = unchecked((int)(0x100F)); public const int TagFlashChargeLevel = unchecked((int)(0x1010)); public const int TagColourMatrix = unchecked((int)(0x1011)); public const int TagBlackLevel = unchecked((int)(0x1012)); public const int TagWhiteBalance = unchecked((int)(0x1015)); public const int TagRedBias = unchecked((int)(0x1017)); public const int TagBlueBias = unchecked((int)(0x1018)); public const int TagColorMatrixNumber = unchecked((int)(0x1019)); public const int TagSerialNumber = unchecked((int)(0x101A)); public const int TagFlashBias = unchecked((int)(0x1023)); public const int TagExternalFlashBounce = unchecked((int)(0x1026)); public const int TagExternalFlashZoom = unchecked((int)(0x1027)); public const int TagExternalFlashMode = unchecked((int)(0x1028)); public const int TagContrast = unchecked((int)(0x1029)); public const int TagSharpnessFactor = unchecked((int)(0x102A)); public const int TagColourControl = unchecked((int)(0x102B)); public const int TagValidBits = unchecked((int)(0x102C)); public const int TagCoringFilter = unchecked((int)(0x102D)); public const int TagFinalWidth = unchecked((int)(0x102E)); public const int TagFinalHeight = unchecked((int)(0x102F)); public const int TagCompressionRatio = unchecked((int)(0x1034)); public const int TagThumbnail = unchecked((int)(0x1035)); public const int TagThumbnailOffset = unchecked((int)(0x1036)); public const int TagThumbnailLength = unchecked((int)(0x1037)); public const int TagCcdScanMode = unchecked((int)(0x1039)); public const int TagNoiseReduction = unchecked((int)(0x103A)); public const int TagInfinityLensStep = unchecked((int)(0x103B)); public const int TagNearLensStep = unchecked((int)(0x103C)); public const int TagEquipment = unchecked((int)(0x2010)); public const int TagCameraSettings = unchecked((int)(0x2020)); public const int TagRawDevelopment = unchecked((int)(0x2030)); public const int TagRawDevelopment2 = unchecked((int)(0x2031)); public const int TagImageProcessing = unchecked((int)(0x2040)); public const int TagFocusInfo = unchecked((int)(0x2050)); public const int TagRawInfo = unchecked((int)(0x3000)); public sealed class CameraSettings { internal const int Offset = unchecked((int)(0xF000)); public const int TagExposureMode = Offset + 2; public const int TagFlashMode = Offset + 3; public const int TagWhiteBalance = Offset + 4; public const int TagImageSize = Offset + 5; public const int TagImageQuality = Offset + 6; public const int TagShootingMode = Offset + 7; public const int TagMeteringMode = Offset + 8; public const int TagApexFilmSpeedValue = Offset + 9; public const int TagApexShutterSpeedTimeValue = Offset + 10; public const int TagApexApertureValue = Offset + 11; public const int TagMacroMode = Offset + 12; public const int TagDigitalZoom = Offset + 13; public const int TagExposureCompensation = Offset + 14; public const int TagBracketStep = Offset + 15; public const int TagIntervalLength = Offset + 17; public const int TagIntervalNumber = Offset + 18; public const int TagFocalLength = Offset + 19; public const int TagFocusDistance = Offset + 20; public const int TagFlashFired = Offset + 21; public const int TagDate = Offset + 22; public const int TagTime = Offset + 23; public const int TagMaxApertureAtFocalLength = Offset + 24; public const int TagFileNumberMemory = Offset + 27; public const int TagLastFileNumber = Offset + 28; public const int TagWhiteBalanceRed = Offset + 29; public const int TagWhiteBalanceGreen = Offset + 30; public const int TagWhiteBalanceBlue = Offset + 31; public const int TagSaturation = Offset + 32; public const int TagContrast = Offset + 33; public const int TagSharpness = Offset + 34; public const int TagSubjectProgram = Offset + 35; public const int TagFlashCompensation = Offset + 36; public const int TagIsoSetting = Offset + 37; public const int TagCameraModel = Offset + 38; public const int TagIntervalMode = Offset + 39; public const int TagFolderName = Offset + 40; public const int TagColorMode = Offset + 41; public const int TagColorFilter = Offset + 42; public const int TagBlackAndWhiteFilter = Offset + 43; public const int TagInternalFlash = Offset + 44; public const int TagApexBrightnessValue = Offset + 45; public const int TagSpotFocusPointXCoordinate = Offset + 46; public const int TagSpotFocusPointYCoordinate = Offset + 47; public const int TagWideFocusZone = Offset + 48; public const int TagFocusMode = Offset + 49; public const int TagFocusArea = Offset + 50; public const int TagDecSwitchPosition = Offset + 51; // public static final int TAG_ = 0x1013; // public static final int TAG_ = 0x1014; // public static final int TAG_ = 0x1016; // public static final int TAG_ = 0x101B; // public static final int TAG_ = 0x101C; // public static final int TAG_ = 0x101D; // public static final int TAG_ = 0x101E; // public static final int TAG_ = 0x101F; // public static final int TAG_ = 0x1020; // public static final int TAG_ = 0x1021; // public static final int TAG_ = 0x1022; // public static final int TAG_ = 0x1024; // public static final int TAG_ = 0x1025; // public static final int TAG_ = 0x1030; // public static final int TAG_ = 0x1031; // public static final int TAG_ = 0x1032; // public static final int TAG_ = 0x1033; // public static final int TAG_ = 0x1038; // These 'sub'-tag values have been created for consistency -- they don't exist within the Makernote IFD // 16 missing // 25, 26 missing } [NotNull] protected internal static readonly Dictionary<int?, string> _tagNameMap = new Dictionary<int?, string>(); static OlympusMakernoteDirectory() { _tagNameMap.Put(TagMakernoteVersion, "Makernote Version"); _tagNameMap.Put(TagCameraSettings1, "Camera Settings"); _tagNameMap.Put(TagCameraSettings2, "Camera Settings"); _tagNameMap.Put(TagCompressedImageSize, "Compressed Image Size"); _tagNameMap.Put(TagMinoltaThumbnailOffset1, "Thumbnail Offset"); _tagNameMap.Put(TagMinoltaThumbnailOffset2, "Thumbnail Offset"); _tagNameMap.Put(TagMinoltaThumbnailLength, "Thumbnail Length"); _tagNameMap.Put(TagThumbnailImage, "Thumbnail Image"); _tagNameMap.Put(TagColourMode, "Colour Mode"); _tagNameMap.Put(TagImageQuality1, "Image Quality"); _tagNameMap.Put(TagImageQuality2, "Image Quality"); _tagNameMap.Put(TagBodyFirmwareVersion, "Body Firmware Version"); _tagNameMap.Put(TagSpecialMode, "Special Mode"); _tagNameMap.Put(TagJpegQuality, "JPEG Quality"); _tagNameMap.Put(TagMacroMode, "Macro"); _tagNameMap.Put(TagBwMode, "BW Mode"); _tagNameMap.Put(TagDigiZoomRatio, "DigiZoom Ratio"); _tagNameMap.Put(TagFocalPlaneDiagonal, "Focal Plane Diagonal"); _tagNameMap.Put(TagLensDistortionParameters, "Lens Distortion Parameters"); _tagNameMap.Put(TagFirmwareVersion, "Firmware Version"); _tagNameMap.Put(TagPictInfo, "Pict Info"); _tagNameMap.Put(TagCameraId, "Camera Id"); _tagNameMap.Put(TagImageWidth, "Image Width"); _tagNameMap.Put(TagImageHeight, "Image Height"); _tagNameMap.Put(TagOriginalManufacturerModel, "Original Manufacturer Model"); _tagNameMap.Put(TagPreviewImage, "Preview Image"); _tagNameMap.Put(TagPreCaptureFrames, "Pre Capture Frames"); _tagNameMap.Put(TagWhiteBoard, "White Board"); _tagNameMap.Put(TagOneTouchWb, "One Touch WB"); _tagNameMap.Put(TagWhiteBalanceBracket, "White Balance Bracket"); _tagNameMap.Put(TagWhiteBalanceBias, "White Balance Bias"); _tagNameMap.Put(TagSceneMode, "Scene Mode"); _tagNameMap.Put(TagFirmware, "Firmware"); _tagNameMap.Put(TagPrintImageMatchingInfo, "Print Image Matching (PIM) Info"); _tagNameMap.Put(TagDataDump1, "Data Dump"); _tagNameMap.Put(TagDataDump2, "Data Dump 2"); _tagNameMap.Put(TagShutterSpeedValue, "Shutter Speed Value"); _tagNameMap.Put(TagIsoValue, "ISO Value"); _tagNameMap.Put(TagApertureValue, "Aperture Value"); _tagNameMap.Put(TagBrightnessValue, "Brightness Value"); _tagNameMap.Put(TagFlashMode, "Flash Mode"); _tagNameMap.Put(TagFlashDevice, "Flash Device"); _tagNameMap.Put(TagBracket, "Bracket"); _tagNameMap.Put(TagSensorTemperature, "Sensor Temperature"); _tagNameMap.Put(TagLensTemperature, "Lens Temperature"); _tagNameMap.Put(TagLightCondition, "Light Condition"); _tagNameMap.Put(TagFocusRange, "Focus Range"); _tagNameMap.Put(TagFocusMode, "Focus Mode"); _tagNameMap.Put(TagFocusDistance, "Focus Distance"); _tagNameMap.Put(TagZoom, "Zoom"); _tagNameMap.Put(TagMacroFocus, "Macro Focus"); _tagNameMap.Put(TagSharpness, "Sharpness"); _tagNameMap.Put(TagFlashChargeLevel, "Flash Charge Level"); _tagNameMap.Put(TagColourMatrix, "Colour Matrix"); _tagNameMap.Put(TagBlackLevel, "Black Level"); _tagNameMap.Put(TagWhiteBalance, "White Balance"); _tagNameMap.Put(TagRedBias, "Red Bias"); _tagNameMap.Put(TagBlueBias, "Blue Bias"); _tagNameMap.Put(TagColorMatrixNumber, "Color Matrix Number"); _tagNameMap.Put(TagSerialNumber, "Serial Number"); _tagNameMap.Put(TagFlashBias, "Flash Bias"); _tagNameMap.Put(TagExternalFlashBounce, "External Flash Bounce"); _tagNameMap.Put(TagExternalFlashZoom, "External Flash Zoom"); _tagNameMap.Put(TagExternalFlashMode, "External Flash Mode"); _tagNameMap.Put(TagContrast, "Contrast"); _tagNameMap.Put(TagSharpnessFactor, "Sharpness Factor"); _tagNameMap.Put(TagColourControl, "Colour Control"); _tagNameMap.Put(TagValidBits, "Valid Bits"); _tagNameMap.Put(TagCoringFilter, "Coring Filter"); _tagNameMap.Put(TagFinalWidth, "Final Width"); _tagNameMap.Put(TagFinalHeight, "Final Height"); _tagNameMap.Put(TagCompressionRatio, "Compression Ratio"); _tagNameMap.Put(TagThumbnail, "Thumbnail"); _tagNameMap.Put(TagThumbnailOffset, "Thumbnail Offset"); _tagNameMap.Put(TagThumbnailLength, "Thumbnail Length"); _tagNameMap.Put(TagCcdScanMode, "CCD Scan Mode"); _tagNameMap.Put(TagNoiseReduction, "Noise Reduction"); _tagNameMap.Put(TagInfinityLensStep, "Infinity Lens Step"); _tagNameMap.Put(TagNearLensStep, "Near Lens Step"); _tagNameMap.Put(TagEquipment, "Equipment"); _tagNameMap.Put(TagCameraSettings, "Camera Settings"); _tagNameMap.Put(TagRawDevelopment, "Raw Development"); _tagNameMap.Put(TagRawDevelopment2, "Raw Development 2"); _tagNameMap.Put(TagImageProcessing, "Image Processing"); _tagNameMap.Put(TagFocusInfo, "Focus Info"); _tagNameMap.Put(TagRawInfo, "Raw Info"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagExposureMode, "Exposure Mode"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagFlashMode, "Flash Mode"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagWhiteBalance, "White Balance"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagImageSize, "Image Size"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagImageQuality, "Image Quality"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagShootingMode, "Shooting Mode"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagMeteringMode, "Metering Mode"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagApexFilmSpeedValue, "Apex Film Speed Value"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagApexShutterSpeedTimeValue, "Apex Shutter Speed Time Value"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagApexApertureValue, "Apex Aperture Value"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagMacroMode, "Macro Mode"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagDigitalZoom, "Digital Zoom"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagExposureCompensation, "Exposure Compensation"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagBracketStep, "Bracket Step"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagIntervalLength, "Interval Length"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagIntervalNumber, "Interval Number"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagFocalLength, "Focal Length"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagFocusDistance, "Focus Distance"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagFlashFired, "Flash Fired"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagDate, "Date"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagTime, "Time"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagMaxApertureAtFocalLength, "Max Aperture at Focal Length"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagFileNumberMemory, "File Number Memory"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagLastFileNumber, "Last File Number"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagWhiteBalanceRed, "White Balance Red"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagWhiteBalanceGreen, "White Balance Green"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagWhiteBalanceBlue, "White Balance Blue"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagSaturation, "Saturation"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagContrast, "Contrast"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagSharpness, "Sharpness"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagSubjectProgram, "Subject Program"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagFlashCompensation, "Flash Compensation"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagIsoSetting, "ISO Setting"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagCameraModel, "Camera Model"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagIntervalMode, "Interval Mode"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagFolderName, "Folder Name"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagColorMode, "Color Mode"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagColorFilter, "Color Filter"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagBlackAndWhiteFilter, "Black and White Filter"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagInternalFlash, "Internal Flash"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagApexBrightnessValue, "Apex Brightness Value"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagSpotFocusPointXCoordinate, "Spot Focus Point X Coordinate"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagSpotFocusPointYCoordinate, "Spot Focus Point Y Coordinate"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagWideFocusZone, "Wide Focus Zone"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagFocusMode, "Focus Mode"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagFocusArea, "Focus Area"); _tagNameMap.Put(OlympusMakernoteDirectory.CameraSettings.TagDecSwitchPosition, "DEC Switch Position"); } public OlympusMakernoteDirectory() { this.SetDescriptor(new OlympusMakernoteDescriptor(this)); } [NotNull] public override string GetName() { return "Olympus Makernote"; } public override void SetByteArray(int tagType, [NotNull] sbyte[] bytes) { if (tagType == TagCameraSettings1 || tagType == TagCameraSettings2) { ProcessCameraSettings(bytes); } else { base.SetByteArray(tagType, bytes); } } private void ProcessCameraSettings(sbyte[] bytes) { SequentialByteArrayReader reader = new SequentialByteArrayReader(bytes); reader.SetMotorolaByteOrder(true); int count = bytes.Length / 4; try { for (int i = 0; i < count; i++) { int value = reader.GetInt32(); SetInt(OlympusMakernoteDirectory.CameraSettings.Offset + i, value); } } catch (IOException e) { // Should never happen, given that we check the length of the bytes beforehand. Sharpen.Runtime.PrintStackTrace(e); } } public virtual bool IsIntervalMode() { long? value = GetLongObject(OlympusMakernoteDirectory.CameraSettings.TagShootingMode); return value != null && value == 5; } [NotNull] protected internal override Dictionary<int?, string> GetTagNameMap() { return _tagNameMap; } } }
// Copyright (c) .NET Foundation. 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.Data; using System.Data.Common; using System.Data.SqlClient; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Scaffolding; using Microsoft.EntityFrameworkCore.Scaffolding.Metadata; using Microsoft.EntityFrameworkCore.Scaffolding.Metadata.Internal; using Pomelo.EntityFrameworkCore.MySql.Internal; using Pomelo.EntityFrameworkCore.MySql.Metadata.Internal; using Microsoft.EntityFrameworkCore.Utilities; namespace Pomelo.EntityFrameworkCore.MySql.Scaffolding.Internal { /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public class MySqlDatabaseModelFactory : IDatabaseModelFactory { private readonly IDiagnosticsLogger<DbLoggerCategory.Scaffolding> _logger; private static readonly ISet<string> _dateTimePrecisionTypes = new HashSet<string> { "datetimeoffset", "datetime2", "time" }; private static readonly ISet<string> _maxLengthRequiredTypes = new HashSet<string> { "binary", "varbinary", "char", "varchar", "nchar", "nvarchar" }; private const string NamePartRegex = @"(?:(?:\[(?<part{0}>(?:(?:\]\])|[^\]])+)\])|(?<part{0}>[^\.\[\]]+))"; private static readonly Regex _partExtractor = new Regex( string.Format( CultureInfo.InvariantCulture, @"^{0}(?:\.{1})?$", string.Format(CultureInfo.InvariantCulture, NamePartRegex, 1), string.Format(CultureInfo.InvariantCulture, NamePartRegex, 2)), RegexOptions.Compiled, TimeSpan.FromMilliseconds(1000)); // see https://msdn.microsoft.com/en-us/library/ff878091.aspx // decimal/numeric are excluded because default value varies based on the precision. private static readonly Dictionary<string, long[]> _defaultSequenceMinMax = new Dictionary<string, long[]>(StringComparer.OrdinalIgnoreCase) { { "tinyint", new[] { 0L, 255L } }, { "smallint", new[] { -32768L, 32767L } }, { "int", new[] { -2147483648L, 2147483647L } }, { "bigint", new[] { -9223372036854775808L, 9223372036854775807L } } }; /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public MySqlDatabaseModelFactory([NotNull] IDiagnosticsLogger<DbLoggerCategory.Scaffolding> logger) { Check.NotNull(logger, nameof(logger)); _logger = logger; } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual DatabaseModel Create(string connectionString, IEnumerable<string> tables, IEnumerable<string> schemas) { Check.NotEmpty(connectionString, nameof(connectionString)); Check.NotNull(tables, nameof(tables)); Check.NotNull(schemas, nameof(schemas)); using (var connection = new SqlConnection(connectionString)) { return Create(connection, tables, schemas); } } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual DatabaseModel Create(DbConnection connection, IEnumerable<string> tables, IEnumerable<string> schemas) { Check.NotNull(connection, nameof(connection)); Check.NotNull(tables, nameof(tables)); Check.NotNull(schemas, nameof(schemas)); var databaseModel = new DatabaseModel(); var connectionStartedOpen = connection.State == ConnectionState.Open; if (!connectionStartedOpen) { connection.Open(); } try { databaseModel.DatabaseName = connection.Database; databaseModel.DefaultSchema = GetDefaultSchema(connection); var typeAliases = GetTypeAliases(connection); var schemaList = schemas.ToList(); var schemaFilter = GenerateSchemaFilter(schemaList); var tableList = tables.ToList(); var tableFilter = GenerateTableFilter(tableList.Select(Parse).ToList(), schemaFilter); if (Version.TryParse(connection.ServerVersion, out var serverVersion) && serverVersion.Major >= 11) { foreach (var sequence in GetSequences(connection, schemaFilter, typeAliases)) { sequence.Database = databaseModel; databaseModel.Sequences.Add(sequence); } } foreach (var table in GetTables(connection, tableFilter, typeAliases)) { table.Database = databaseModel; databaseModel.Tables.Add(table); } foreach (var schema in schemaList .Except( databaseModel.Sequences.Select(s => s.Schema) .Concat(databaseModel.Tables.Select(t => t.Schema)))) { _logger.MissingSchemaWarning(schema); } foreach (var table in tableList) { var (parsedSchema, parsedTableName) = Parse(table); if (!databaseModel.Tables.Any( t => !string.IsNullOrEmpty(parsedSchema) && t.Schema == parsedSchema || t.Name == parsedTableName)) { _logger.MissingTableWarning(table); } } return databaseModel; } finally { if (!connectionStartedOpen) { connection.Close(); } } } private string GetDefaultSchema(DbConnection connection) { using (var command = connection.CreateCommand()) { command.CommandText = "SELECT SCHEMA_NAME()"; if (command.ExecuteScalar() is string schema) { _logger.DefaultSchemaFound(schema); return schema; } return null; } } private static Func<string, string> GenerateSchemaFilter(IReadOnlyList<string> schemas) { return schemas.Count > 0 ? (s => { var schemaFilterBuilder = new StringBuilder(); schemaFilterBuilder.Append(s); schemaFilterBuilder.Append(" IN ("); schemaFilterBuilder.Append(string.Join(", ", schemas.Select(EscapeLiteral))); schemaFilterBuilder.Append(")"); return schemaFilterBuilder.ToString(); }) : (Func<string, string>)null; } private static (string Schema, string Table) Parse(string table) { var match = _partExtractor.Match(table.Trim()); if (!match.Success) { throw new InvalidOperationException(MySqlStrings.InvalidTableToIncludeInScaffolding(table)); } var part1 = match.Groups["part1"].Value.Replace("]]", "]"); var part2 = match.Groups["part2"].Value.Replace("]]", "]"); return string.IsNullOrEmpty(part2) ? (null, part1) : (part1, part2); } private static Func<string, string, string> GenerateTableFilter( IReadOnlyList<(string Schema, string Table)> tables, Func<string, string> schemaFilter) { return schemaFilter != null || tables.Count > 0 ? ((s, t) => { var tableFilterBuilder = new StringBuilder(); var openBracket = false; if (schemaFilter != null) { tableFilterBuilder .Append("(") .Append(schemaFilter(s)); openBracket = true; } if (tables.Count > 0) { if (openBracket) { tableFilterBuilder .AppendLine() .Append("OR "); } else { tableFilterBuilder.Append("("); openBracket = true; } var tablesWithoutSchema = tables.Where(e => string.IsNullOrEmpty(e.Schema)).ToList(); if (tablesWithoutSchema.Count > 0) { tableFilterBuilder.Append(t); tableFilterBuilder.Append(" IN ("); tableFilterBuilder.Append(string.Join(", ", tablesWithoutSchema.Select(e => EscapeLiteral(e.Table)))); tableFilterBuilder.Append(")"); } var tablesWithSchema = tables.Where(e => !string.IsNullOrEmpty(e.Schema)).ToList(); if (tablesWithSchema.Count > 0) { if (tablesWithoutSchema.Count > 0) { tableFilterBuilder.Append(" OR "); } tableFilterBuilder.Append(t); tableFilterBuilder.Append(" IN ("); tableFilterBuilder.Append(string.Join(", ", tablesWithSchema.Select(e => EscapeLiteral(e.Table)))); tableFilterBuilder.Append(") AND ("); tableFilterBuilder.Append(s); tableFilterBuilder.Append(" + N'.' + "); tableFilterBuilder.Append(t); tableFilterBuilder.Append(") IN ("); tableFilterBuilder.Append(string.Join(", ", tablesWithSchema.Select(e => EscapeLiteral($"{e.Schema}.{e.Table}")))); tableFilterBuilder.Append(")"); } } if (openBracket) { tableFilterBuilder.Append(")"); } return tableFilterBuilder.ToString(); }) : (Func<string, string, string>)null; } private static string EscapeLiteral(string s) { return $"N'{s}'"; } private IReadOnlyDictionary<string, (string, string)> GetTypeAliases(DbConnection connection) { using (var command = connection.CreateCommand()) { var typeAliasMap = new Dictionary<string, (string, string)>(StringComparer.OrdinalIgnoreCase); command.CommandText = @" SELECT SCHEMA_NAME([t].[schema_id]) AS [schema_name], [t].[name] AS [type_name], [t2].[name] AS [underlying_system_type], CAST([t].[max_length] AS int) AS [max_length], CAST([t].[precision] AS int) AS [precision], CAST([t].[scale] AS int) AS [scale] FROM [sys].[types] AS [t] JOIN [sys].[types] AS [t2] ON [t].[system_type_id] = [t2].[user_type_id] WHERE [t].[is_user_defined] = 1 OR [t].[system_type_id] <> [t].[user_type_id]"; using (var reader = command.ExecuteReader()) { while (reader.Read()) { var schema = reader.GetValueOrDefault<string>("schema_name"); var userType = reader.GetValueOrDefault<string>("type_name"); var systemType = reader.GetValueOrDefault<string>("underlying_system_type"); var maxLength = reader.GetValueOrDefault<int>("max_length"); var precision = reader.GetValueOrDefault<int>("precision"); var scale = reader.GetValueOrDefault<int>("scale"); var storeType = GetStoreType(systemType, maxLength, precision, scale); _logger.TypeAliasFound(DisplayName(schema, userType), storeType); typeAliasMap.Add($"[{schema}].[{userType}]", (storeType, systemType)); } } return typeAliasMap; } } private IEnumerable<DatabaseSequence> GetSequences( DbConnection connection, Func<string, string> schemaFilter, IReadOnlyDictionary<string, (string storeType, string)> typeAliases) { using (var command = connection.CreateCommand()) { command.CommandText = @" SELECT OBJECT_SCHEMA_NAME([s].[object_id]) AS [schema_name], [s].[name], SCHEMA_NAME([t].[schema_id]) AS [type_schema], TYPE_NAME([s].[user_type_id]) AS [type_name], CAST([s].[precision] AS int) AS [precision], CAST([s].[scale] AS int) AS [scale], [s].[is_cycling], CAST([s].[increment] AS int) AS [increment], CAST([s].[start_value] AS bigint) AS [start_value], CAST([s].[minimum_value] AS bigint) AS [minimum_value], CAST([s].[maximum_value] AS bigint) AS [maximum_value] FROM [sys].[sequences] AS [s] JOIN [sys].[types] AS [t] ON [s].[user_type_id] = [t].[user_type_id]"; if (schemaFilter != null) { command.CommandText += @" WHERE " + schemaFilter("OBJECT_SCHEMA_NAME([s].[object_id])"); } using (var reader = command.ExecuteReader()) { while (reader.Read()) { var schema = reader.GetValueOrDefault<string>("schema_name"); var name = reader.GetValueOrDefault<string>("name"); var storeTypeSchema = reader.GetValueOrDefault<string>("type_schema"); var storeType = reader.GetValueOrDefault<string>("type_name"); var precision = reader.GetValueOrDefault<int>("precision"); var scale = reader.GetValueOrDefault<int>("scale"); var isCyclic = reader.GetValueOrDefault<bool>("is_cycling"); var incrementBy = reader.GetValueOrDefault<int>("increment"); var startValue = reader.GetValueOrDefault<long>("start_value"); var minValue = reader.GetValueOrDefault<long>("minimum_value"); var maxValue = reader.GetValueOrDefault<long>("maximum_value"); // Swap store type if type alias is used if (typeAliases.TryGetValue($"[{storeTypeSchema}].[{storeType}]", out var value)) { storeType = value.storeType; } storeType = GetStoreType(storeType, maxLength: 0, precision: precision, scale: scale); _logger.SequenceFound(DisplayName(schema, name), storeType, isCyclic, incrementBy, startValue, minValue, maxValue); var sequence = new DatabaseSequence { Schema = schema, Name = name, StoreType = storeType, IsCyclic = isCyclic, IncrementBy = incrementBy, StartValue = startValue, MinValue = minValue, MaxValue = maxValue }; if (_defaultSequenceMinMax.ContainsKey(storeType)) { var defaultMin = _defaultSequenceMinMax[storeType][0]; sequence.MinValue = sequence.MinValue == defaultMin ? null : sequence.MinValue; sequence.StartValue = sequence.StartValue == defaultMin ? null : sequence.StartValue; sequence.MaxValue = sequence.MaxValue == _defaultSequenceMinMax[sequence.StoreType][1] ? null : sequence.MaxValue; } yield return sequence; } } } } private IEnumerable<DatabaseTable> GetTables( DbConnection connection, Func<string, string, string> tableFilter, IReadOnlyDictionary<string, (string, string)> typeAliases) { using (var command = connection.CreateCommand()) { var tables = new List<DatabaseTable>(); Version.TryParse(connection.ServerVersion, out var serverVersion); var supportsMemoryOptimizedTable = serverVersion?.Major >= 12; var supportsTemporalTable = serverVersion?.Major >= 13; var commandText = @" SELECT SCHEMA_NAME([t].[schema_id]) AS [schema], [t].[name]"; if (supportsMemoryOptimizedTable) { commandText += @", [t].[is_memory_optimized]"; } commandText += @" FROM [sys].[tables] AS [t]"; var filter = @"[t].[is_ms_shipped] = 0 AND NOT EXISTS (SELECT * FROM [sys].[extended_properties] AS [ep] WHERE [ep].[major_id] = [t].[object_id] AND [ep].[minor_id] = 0 AND [ep].[class] = 1 AND [ep].[name] = N'microsoft_database_tools_support' ) AND [t].[name] <> '" + HistoryRepository.DefaultTableName + "'"; if (supportsTemporalTable) { filter += @" AND [t].[temporal_type] <> 1"; } if (tableFilter != null) { filter += @" AND " + tableFilter("SCHEMA_NAME([t].[schema_id])", "[t].[name]"); } command.CommandText = commandText + @" WHERE " + filter; using (var reader = command.ExecuteReader()) { while (reader.Read()) { var schema = reader.GetValueOrDefault<string>("schema"); var name = reader.GetValueOrDefault<string>("name"); _logger.TableFound(DisplayName(schema, name)); var table = new DatabaseTable { Schema = schema, Name = name }; if (supportsMemoryOptimizedTable) { if (reader.GetValueOrDefault<bool>("is_memory_optimized")) { table[MySqlAnnotationNames.MemoryOptimized] = true; } } tables.Add(table); } } // This is done separately due to MARS property may be turned off GetColumns(connection, tables, filter, typeAliases); GetIndexes(connection, tables, filter); GetForeignKeys(connection, tables, filter); return tables; } } private void GetColumns( DbConnection connection, IReadOnlyList<DatabaseTable> tables, string tableFilter, IReadOnlyDictionary<string, (string storeType, string typeName)> typeAliases) { using (var command = connection.CreateCommand()) { var commandText = @" SELECT SCHEMA_NAME([t].[schema_id]) AS [table_schema], [t].[name] AS [table_name], [c].[name] AS [column_name], [c].[column_id] AS [ordinal], SCHEMA_NAME([tp].[schema_id]) AS [type_schema], [tp].[name] AS [type_name], CAST([c].[max_length] AS int) AS [max_length], CAST([c].[precision] AS int) AS [precision], CAST([c].[scale] AS int) AS [scale], [c].[is_nullable], [c].[is_identity], OBJECT_DEFINITION([c].[default_object_id]) AS [default_sql], [cc].[definition] AS [computed_sql] FROM [sys].[columns] AS [c] JOIN [sys].[tables] AS [t] ON [c].[object_id] = [t].[object_id] JOIN [sys].[types] AS [tp] ON [c].[user_type_id] = [tp].[user_type_id] LEFT JOIN [sys].[computed_columns] AS [cc] ON [c].[object_id] = [cc].[object_id] AND [c].[column_id] = [cc].[column_id] WHERE " + tableFilter; if (Version.TryParse(connection.ServerVersion, out var serverVersion) && serverVersion.Major >= 13) { commandText += " AND [c].[is_hidden] = 0"; } commandText += @" ORDER BY [table_schema], [table_name], [c].[column_id]"; command.CommandText = commandText; using (var reader = command.ExecuteReader()) { var tableColumnGroups = reader.Cast<DbDataRecord>() .GroupBy( ddr => (tableSchema: ddr.GetValueOrDefault<string>("table_schema"), tableName: ddr.GetValueOrDefault<string>("table_name"))); foreach (var tableColumnGroup in tableColumnGroups) { var tableSchema = tableColumnGroup.Key.tableSchema; var tableName = tableColumnGroup.Key.tableName; var table = tables.Single(t => t.Schema == tableSchema && t.Name == tableName); foreach (var dataRecord in tableColumnGroup) { var columnName = dataRecord.GetValueOrDefault<string>("column_name"); var ordinal = dataRecord.GetValueOrDefault<int>("ordinal"); var dataTypeSchemaName = dataRecord.GetValueOrDefault<string>("type_schema"); var dataTypeName = dataRecord.GetValueOrDefault<string>("type_name"); var maxLength = dataRecord.GetValueOrDefault<int>("max_length"); var precision = dataRecord.GetValueOrDefault<int>("precision"); var scale = dataRecord.GetValueOrDefault<int>("scale"); var nullable = dataRecord.GetValueOrDefault<bool>("is_nullable"); var isIdentity = dataRecord.GetValueOrDefault<bool>("is_identity"); var defaultValue = dataRecord.GetValueOrDefault<string>("default_sql"); var computedValue = dataRecord.GetValueOrDefault<string>("computed_sql"); _logger.ColumnFound( DisplayName(tableSchema, tableName), columnName, ordinal, DisplayName(dataTypeSchemaName, dataTypeName), maxLength, precision, scale, nullable, isIdentity, defaultValue, computedValue); string storeType; string systemTypeName; // Swap store type if type alias is used if (typeAliases.TryGetValue($"[{dataTypeSchemaName}].[{dataTypeName}]", out var value)) { storeType = value.storeType; systemTypeName = value.typeName; } else { storeType = GetStoreType(dataTypeName, maxLength, precision, scale); systemTypeName = dataTypeName; } defaultValue = FilterClrDefaults(systemTypeName, nullable, defaultValue); var column = new DatabaseColumn { Table = table, Name = columnName, StoreType = storeType, IsNullable = nullable, DefaultValueSql = defaultValue, ComputedColumnSql = computedValue, ValueGenerated = isIdentity ? ValueGenerated.OnAdd : storeType == "rowversion" ? ValueGenerated.OnAddOrUpdate #pragma warning disable IDE0034 // Simplify 'default' expression - Ternary expression causes default(ValueGenerated) which is non-nullable : default(ValueGenerated?) #pragma warning restore IDE0034 // Simplify 'default' expression }; if (storeType == "rowversion") { column[ScaffoldingAnnotationNames.ConcurrencyToken] = true; } table.Columns.Add(column); } } } } } private static string FilterClrDefaults(string dataTypeName, bool nullable, string defaultValue) { if (defaultValue == null || defaultValue == "(NULL)") { return null; } if (nullable) { return defaultValue; } if (defaultValue == "((0))") { if (dataTypeName == "bigint" || dataTypeName == "bit" || dataTypeName == "decimal" || dataTypeName == "float" || dataTypeName == "int" || dataTypeName == "money" || dataTypeName == "numeric" || dataTypeName == "real" || dataTypeName == "smallint" || dataTypeName == "smallmoney" || dataTypeName == "tinyint") { return null; } } else if (defaultValue == "((0.0))") { if (dataTypeName == "decimal" || dataTypeName == "float" || dataTypeName == "money" || dataTypeName == "numeric" || dataTypeName == "real" || dataTypeName == "smallmoney") { return null; } } else if ((defaultValue == "(CONVERT([real],(0)))" && dataTypeName == "real") || (defaultValue == "((0.0000000000000000e+000))" && dataTypeName == "float") || (defaultValue == "('0001-01-01')" && dataTypeName == "date") || (defaultValue == "('1900-01-01T00:00:00.000')" && (dataTypeName == "datetime" || dataTypeName == "smalldatetime")) || (defaultValue == "('0001-01-01T00:00:00.000')" && dataTypeName == "datetime2") || (defaultValue == "('0001-01-01T00:00:00.000+00:00')" && dataTypeName == "datetimeoffset") || (defaultValue == "('00:00:00')" && dataTypeName == "time") || (defaultValue == "('00000000-0000-0000-0000-000000000000')" && dataTypeName == "uniqueidentifier")) { return null; } return defaultValue; } private static string GetStoreType(string dataTypeName, int maxLength, int precision, int scale) { if (dataTypeName == "timestamp") { return "rowversion"; } if (dataTypeName == "decimal" || dataTypeName == "numeric") { return $"{dataTypeName}({precision}, {scale})"; } if (_dateTimePrecisionTypes.Contains(dataTypeName) && scale != 7) { return $"{dataTypeName}({scale})"; } if (_maxLengthRequiredTypes.Contains(dataTypeName)) { if (maxLength == -1) { return $"{dataTypeName}(max)"; } if (dataTypeName == "nvarchar" || dataTypeName == "nchar") { maxLength /= 2; } return $"{dataTypeName}({maxLength})"; } return dataTypeName; } private void GetIndexes(DbConnection connection, IReadOnlyList<DatabaseTable> tables, string tableFilter) { using (var command = connection.CreateCommand()) { command.CommandText = @" SELECT SCHEMA_NAME([t].[schema_id]) AS [table_schema], [t].[name] AS [table_name], [i].[name] AS [index_name], [i].[type_desc], [i].[is_primary_key], [i].[is_unique_constraint], [i].[is_unique], [i].[has_filter], [i].[filter_definition], COL_NAME([ic].[object_id], [ic].[column_id]) AS [column_name] FROM [sys].[indexes] AS [i] JOIN [sys].[tables] AS [t] ON [i].[object_id] = [t].[object_id] JOIN [sys].[index_columns] AS [ic] ON [i].[object_id] = [ic].[object_id] AND [i].[index_id] = [ic].[index_id] WHERE " + tableFilter + @" ORDER BY [table_schema], [table_name], [index_name], [ic].[key_ordinal]"; using (var reader = command.ExecuteReader()) { var tableIndexGroups = reader.Cast<DbDataRecord>() .GroupBy( ddr => (tableSchema: ddr.GetValueOrDefault<string>("table_schema"), tableName: ddr.GetValueOrDefault<string>("table_name"))); foreach (var tableIndexGroup in tableIndexGroups) { var tableSchema = tableIndexGroup.Key.tableSchema; var tableName = tableIndexGroup.Key.tableName; var table = tables.Single(t => t.Schema == tableSchema && t.Name == tableName); var primaryKeyGroups = tableIndexGroup .Where(ddr => ddr.GetValueOrDefault<bool>("is_primary_key")) .GroupBy( ddr => (Name: ddr.GetValueOrDefault<string>("index_name"), TypeDesc: ddr.GetValueOrDefault<string>("type_desc"))) .ToArray(); if (primaryKeyGroups.Length == 1) { var primaryKeyGroup = primaryKeyGroups[0]; _logger.PrimaryKeyFound(primaryKeyGroup.Key.Name, DisplayName(tableSchema, tableName)); var primaryKey = new DatabasePrimaryKey { Table = table, Name = primaryKeyGroup.Key.Name }; if (primaryKeyGroup.Key.TypeDesc == "NONCLUSTERED") { primaryKey[MySqlAnnotationNames.Clustered] = false; } foreach (var dataRecord in primaryKeyGroup) { var columnName = dataRecord.GetValueOrDefault<string>("column_name"); var column = table.Columns.FirstOrDefault(c => c.Name == columnName) ?? table.Columns.FirstOrDefault(c => c.Name.Equals(columnName, StringComparison.OrdinalIgnoreCase)); Debug.Assert(column != null, "column is null."); primaryKey.Columns.Add(column); } table.PrimaryKey = primaryKey; } var uniqueConstraintGroups = tableIndexGroup .Where(ddr => ddr.GetValueOrDefault<bool>("is_unique_constraint")) .GroupBy( ddr => (Name: ddr.GetValueOrDefault<string>("index_name"), TypeDesc: ddr.GetValueOrDefault<string>("type_desc"))) .ToArray(); foreach (var uniqueConstraintGroup in uniqueConstraintGroups) { _logger.UniqueConstraintFound(uniqueConstraintGroup.Key.Name, DisplayName(tableSchema, tableName)); var uniqueConstraint = new DatabaseUniqueConstraint { Table = table, Name = uniqueConstraintGroup.Key.Name }; if (uniqueConstraintGroup.Key.TypeDesc == "CLUSTERED") { uniqueConstraint[MySqlAnnotationNames.Clustered] = true; } foreach (var dataRecord in uniqueConstraintGroup) { var columnName = dataRecord.GetValueOrDefault<string>("column_name"); var column = table.Columns.FirstOrDefault(c => c.Name == columnName) ?? table.Columns.FirstOrDefault(c => c.Name.Equals(columnName, StringComparison.OrdinalIgnoreCase)); Debug.Assert(column != null, "column is null."); uniqueConstraint.Columns.Add(column); } table.UniqueConstraints.Add(uniqueConstraint); } var indexGroups = tableIndexGroup .Where( ddr => !ddr.GetValueOrDefault<bool>("is_primary_key") && !ddr.GetValueOrDefault<bool>("is_unique_constraint")) .GroupBy( ddr => (Name: ddr.GetValueOrDefault<string>("index_name"), TypeDesc: ddr.GetValueOrDefault<string>("type_desc"), IsUnique: ddr.GetValueOrDefault<bool>("is_unique"), HasFilter: ddr.GetValueOrDefault<bool>("has_filter"), FilterDefinition: ddr.GetValueOrDefault<string>("filter_definition"))) .ToArray(); foreach (var indexGroup in indexGroups) { _logger.IndexFound(indexGroup.Key.Name, DisplayName(tableSchema, tableName), indexGroup.Key.IsUnique); var index = new DatabaseIndex { Table = table, Name = indexGroup.Key.Name, IsUnique = indexGroup.Key.IsUnique, Filter = indexGroup.Key.HasFilter ? indexGroup.Key.FilterDefinition : null }; if (indexGroup.Key.TypeDesc == "CLUSTERED") { index[MySqlAnnotationNames.Clustered] = true; } foreach (var dataRecord in indexGroup) { var columnName = dataRecord.GetValueOrDefault<string>("column_name"); var column = table.Columns.FirstOrDefault(c => c.Name == columnName) ?? table.Columns.FirstOrDefault(c => c.Name.Equals(columnName, StringComparison.OrdinalIgnoreCase)); Debug.Assert(column != null, "column is null."); index.Columns.Add(column); } table.Indexes.Add(index); } } } } } private void GetForeignKeys(DbConnection connection, IReadOnlyList<DatabaseTable> tables, string tableFilter) { using (var command = connection.CreateCommand()) { command.CommandText = @" SELECT SCHEMA_NAME([t].[schema_id]) AS [table_schema], [t].[name] AS [table_name], [f].[name], OBJECT_SCHEMA_NAME([f].[referenced_object_id]) AS [principal_table_schema], OBJECT_NAME([f].[referenced_object_id]) AS [principal_table_name], [f].[delete_referential_action_desc], col_name([fc].[parent_object_id], [fc].[parent_column_id]) AS [column_name], col_name([fc].[referenced_object_id], [fc].[referenced_column_id]) AS [referenced_column_name] FROM [sys].[foreign_keys] AS [f] JOIN [sys].[tables] AS [t] ON [f].[parent_object_id] = [t].[object_id] JOIN [sys].[foreign_key_columns] AS [fc] ON [f].[object_id] = [fc].[constraint_object_id] WHERE " + tableFilter + @" ORDER BY [table_schema], [table_name], [f].[name], [fc].[constraint_column_id]"; using (var reader = command.ExecuteReader()) { var tableForeignKeyGroups = reader.Cast<DbDataRecord>() .GroupBy( ddr => (tableSchema: ddr.GetValueOrDefault<string>("table_schema"), tableName: ddr.GetValueOrDefault<string>("table_name"))); foreach (var tableForeignKeyGroup in tableForeignKeyGroups) { var tableSchema = tableForeignKeyGroup.Key.tableSchema; var tableName = tableForeignKeyGroup.Key.tableName; var table = tables.Single(t => t.Schema == tableSchema && t.Name == tableName); var foreignKeyGroups = tableForeignKeyGroup .GroupBy( c => (Name: c.GetValueOrDefault<string>("name"), PrincipalTableSchema: c.GetValueOrDefault<string>("principal_table_schema"), PrincipalTableName: c.GetValueOrDefault<string>("principal_table_name"), OnDeleteAction: c.GetValueOrDefault<string>("delete_referential_action_desc"))); foreach (var foreignKeyGroup in foreignKeyGroups) { var fkName = foreignKeyGroup.Key.Name; var principalTableSchema = foreignKeyGroup.Key.PrincipalTableSchema; var principalTableName = foreignKeyGroup.Key.PrincipalTableName; var onDeleteAction = foreignKeyGroup.Key.OnDeleteAction; _logger.ForeignKeyFound( fkName, DisplayName(table.Schema, table.Name), DisplayName(principalTableSchema, principalTableName), onDeleteAction); var principalTable = tables.FirstOrDefault( t => t.Schema == principalTableSchema && t.Name == principalTableName) ?? tables.FirstOrDefault( t => t.Schema.Equals(principalTableSchema, StringComparison.OrdinalIgnoreCase) && t.Name.Equals(principalTableName, StringComparison.OrdinalIgnoreCase)); if (principalTable == null) { _logger.ForeignKeyReferencesMissingPrincipalTableWarning( fkName, DisplayName(table.Schema, table.Name), DisplayName(principalTableSchema, principalTableName)); continue; } var foreignKey = new DatabaseForeignKey { Name = fkName, Table = table, PrincipalTable = principalTable, OnDelete = ConvertToReferentialAction(onDeleteAction) }; var invalid = false; foreach (var dataRecord in foreignKeyGroup) { var columnName = dataRecord.GetValueOrDefault<string>("column_name"); var column = table.Columns.FirstOrDefault(c => c.Name == columnName) ?? table.Columns.FirstOrDefault(c => c.Name.Equals(columnName, StringComparison.OrdinalIgnoreCase)); Debug.Assert(column != null, "column is null."); var principalColumnName = dataRecord.GetValueOrDefault<string>("referenced_column_name"); var principalColumn = foreignKey.PrincipalTable.Columns.FirstOrDefault(c => c.Name == principalColumnName) ?? foreignKey.PrincipalTable.Columns.FirstOrDefault(c => c.Name.Equals(principalColumnName, StringComparison.OrdinalIgnoreCase)); if (principalColumn == null) { invalid = true; _logger.ForeignKeyPrincipalColumnMissingWarning( fkName, DisplayName(table.Schema, table.Name), principalColumnName, DisplayName(principalTableSchema, principalTableName)); break; } foreignKey.Columns.Add(column); foreignKey.PrincipalColumns.Add(principalColumn); } if (!invalid) { if (foreignKey.Columns.SequenceEqual(foreignKey.PrincipalColumns)) { _logger.ReflexiveConstraintIgnored( foreignKey.Name, DisplayName(table.Schema, table.Name)); } else { table.ForeignKeys.Add(foreignKey); } } } } } } } private static string DisplayName(string schema, string name) => (!string.IsNullOrEmpty(schema) ? schema + "." : "") + name; private static ReferentialAction? ConvertToReferentialAction(string onDeleteAction) { switch (onDeleteAction) { case "NO_ACTION": return ReferentialAction.NoAction; case "CASCADE": return ReferentialAction.Cascade; case "SET_NULL": return ReferentialAction.SetNull; case "SET_DEFAULT": return ReferentialAction.SetDefault; default: return null; } } } }
// // Copyright (c) 2014 .NET Foundation // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Copyright (c) 2014 Couchbase, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. //using System; using System.Collections.Generic; using Couchbase.Lite; using Couchbase.Lite.Internal; using Couchbase.Lite.Replicator; using Couchbase.Lite.Support; using Sharpen; namespace Couchbase.Lite { public class DatabaseTest : LiteTestCase { /// <exception cref="System.Exception"></exception> public virtual void TestPruneRevsToMaxDepth() { IDictionary<string, object> properties = new Dictionary<string, object>(); properties.Put("testName", "testDatabaseCompaction"); properties.Put("tag", 1337); Document doc = CreateDocumentWithProperties(database, properties); SavedRevision rev = doc.GetCurrentRevision(); database.SetMaxRevTreeDepth(1); for (int i = 0; i < 10; i++) { IDictionary<string, object> properties2 = new Dictionary<string, object>(properties ); properties2.Put("tag", i); rev = rev.CreateRevision(properties2); } int numPruned = database.PruneRevsToMaxDepth(1); NUnit.Framework.Assert.AreEqual(10, numPruned); Document fetchedDoc = database.GetDocument(doc.GetId()); IList<SavedRevision> revisions = fetchedDoc.GetRevisionHistory(); NUnit.Framework.Assert.AreEqual(1, revisions.Count); numPruned = database.PruneRevsToMaxDepth(1); NUnit.Framework.Assert.AreEqual(0, numPruned); } /// <exception cref="System.Exception"></exception> public virtual void TestPruneRevsToMaxDepthViaCompact() { IDictionary<string, object> properties = new Dictionary<string, object>(); properties.Put("testName", "testDatabaseCompaction"); properties.Put("tag", 1337); Document doc = CreateDocumentWithProperties(database, properties); SavedRevision rev = doc.GetCurrentRevision(); database.SetMaxRevTreeDepth(1); for (int i = 0; i < 10; i++) { IDictionary<string, object> properties2 = new Dictionary<string, object>(properties ); properties2.Put("tag", i); rev = rev.CreateRevision(properties2); } database.Compact(); Document fetchedDoc = database.GetDocument(doc.GetId()); IList<SavedRevision> revisions = fetchedDoc.GetRevisionHistory(); NUnit.Framework.Assert.AreEqual(1, revisions.Count); } /// <summary> /// When making inserts in a transaction, the change notifications should /// be batched into a single change notification (rather than a change notification /// for each insert) /// </summary> /// <exception cref="System.Exception"></exception> public virtual void TestChangeListenerNotificationBatching() { int numDocs = 50; AtomicInteger atomicInteger = new AtomicInteger(0); CountDownLatch countDownLatch = new CountDownLatch(1); database.AddChangeListener(new _ChangeListener_81(atomicInteger)); database.RunInTransaction(new _TransactionalTask_88(this, numDocs, countDownLatch )); bool success = countDownLatch.Await(30, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); NUnit.Framework.Assert.AreEqual(1, atomicInteger.Get()); } private sealed class _ChangeListener_81 : Database.ChangeListener { public _ChangeListener_81(AtomicInteger atomicInteger) { this.atomicInteger = atomicInteger; } public void Changed(Database.ChangeEvent @event) { atomicInteger.IncrementAndGet(); } private readonly AtomicInteger atomicInteger; } private sealed class _TransactionalTask_88 : TransactionalTask { public _TransactionalTask_88(DatabaseTest _enclosing, int numDocs, CountDownLatch countDownLatch) { this._enclosing = _enclosing; this.numDocs = numDocs; this.countDownLatch = countDownLatch; } public bool Run() { LiteTestCase.CreateDocuments(this._enclosing.database, numDocs); countDownLatch.CountDown(); return true; } private readonly DatabaseTest _enclosing; private readonly int numDocs; private readonly CountDownLatch countDownLatch; } /// <summary> /// When making inserts outside of a transaction, there should be a change notification /// for each insert (no batching) /// </summary> /// <exception cref="System.Exception"></exception> public virtual void TestChangeListenerNotification() { int numDocs = 50; AtomicInteger atomicInteger = new AtomicInteger(0); CountDownLatch countDownLatch = new CountDownLatch(1); database.AddChangeListener(new _ChangeListener_115(atomicInteger)); CreateDocuments(database, numDocs); NUnit.Framework.Assert.AreEqual(numDocs, atomicInteger.Get()); } private sealed class _ChangeListener_115 : Database.ChangeListener { public _ChangeListener_115(AtomicInteger atomicInteger) { this.atomicInteger = atomicInteger; } public void Changed(Database.ChangeEvent @event) { atomicInteger.IncrementAndGet(); } private readonly AtomicInteger atomicInteger; } /// <exception cref="System.Exception"></exception> public virtual void TestGetActiveReplications() { Uri remote = GetReplicationURL(); Replication replication = (Replication)database.CreatePullReplication(remote); NUnit.Framework.Assert.AreEqual(0, database.GetAllReplications().Count); NUnit.Framework.Assert.AreEqual(0, database.GetActiveReplications().Count); replication.Start(); NUnit.Framework.Assert.AreEqual(1, database.GetAllReplications().Count); NUnit.Framework.Assert.AreEqual(1, database.GetActiveReplications().Count); CountDownLatch replicationDoneSignal = new CountDownLatch(1); LiteTestCase.ReplicationFinishedObserver replicationFinishedObserver = new LiteTestCase.ReplicationFinishedObserver (replicationDoneSignal); replication.AddChangeListener(replicationFinishedObserver); bool success = replicationDoneSignal.Await(60, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); NUnit.Framework.Assert.AreEqual(1, database.GetAllReplications().Count); NUnit.Framework.Assert.AreEqual(0, database.GetActiveReplications().Count); } /// <exception cref="System.Exception"></exception> public virtual void TestGetDatabaseNameFromPath() { NUnit.Framework.Assert.AreEqual("baz", FileDirUtils.GetDatabaseNameFromPath("foo/bar/baz.cblite" )); } /// <exception cref="System.Exception"></exception> public virtual void TestEncodeDocumentJSON() { IDictionary<string, object> props = new Dictionary<string, object>(); props.Put("_local_seq", string.Empty); RevisionInternal revisionInternal = new RevisionInternal(props, database); byte[] encoded = database.EncodeDocumentJSON(revisionInternal); NUnit.Framework.Assert.IsNotNull(encoded); } /// <exception cref="System.Exception"></exception> public virtual void TestWinningRevIDOfDoc() { IDictionary<string, object> properties = new Dictionary<string, object>(); properties.Put("testName", "testCreateRevisions"); properties.Put("tag", 1337); IDictionary<string, object> properties2a = new Dictionary<string, object>(); properties2a.Put("testName", "testCreateRevisions"); properties2a.Put("tag", 1338); IDictionary<string, object> properties2b = new Dictionary<string, object>(); properties2b.Put("testName", "testCreateRevisions"); properties2b.Put("tag", 1339); IList<bool> outIsDeleted = new AList<bool>(); IList<bool> outIsConflict = new AList<bool>(); // Create a conflict on purpose Document doc = database.CreateDocument(); UnsavedRevision newRev1 = doc.CreateRevision(); newRev1.SetUserProperties(properties); SavedRevision rev1 = newRev1.Save(); long docNumericId = database.GetDocNumericID(doc.GetId()); NUnit.Framework.Assert.IsTrue(docNumericId != 0); NUnit.Framework.Assert.AreEqual(rev1.GetId(), database.WinningRevIDOfDoc(docNumericId , outIsDeleted, outIsConflict)); NUnit.Framework.Assert.IsTrue(outIsConflict.Count == 0); outIsDeleted = new AList<bool>(); outIsConflict = new AList<bool>(); UnsavedRevision newRev2a = rev1.CreateRevision(); newRev2a.SetUserProperties(properties2a); SavedRevision rev2a = newRev2a.Save(); NUnit.Framework.Assert.AreEqual(rev2a.GetId(), database.WinningRevIDOfDoc(docNumericId , outIsDeleted, outIsConflict)); NUnit.Framework.Assert.IsTrue(outIsConflict.Count == 0); outIsDeleted = new AList<bool>(); outIsConflict = new AList<bool>(); UnsavedRevision newRev2b = rev1.CreateRevision(); newRev2b.SetUserProperties(properties2b); SavedRevision rev2b = newRev2b.Save(true); database.WinningRevIDOfDoc(docNumericId, outIsDeleted, outIsConflict); NUnit.Framework.Assert.IsTrue(outIsConflict.Count > 0); } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // // File: ContainerParaClient.cs // // Description: ContainerParaClient is responsible for handling display // related data of paragraph containers. // // History: // 05/05/2003 : [....] - moving from Avalon branch. // //--------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections; using System.Diagnostics; using System.Security; using System.Windows; using System.Windows.Media; using System.Windows.Documents; using MS.Internal.Documents; using MS.Internal.Text; using MS.Internal.PtsHost.UnsafeNativeMethods; namespace MS.Internal.PtsHost { /// <summary> /// ContainerParaClient is responsible for handling display related data /// of paragraph containers. /// </summary> internal class ContainerParaClient : BaseParaClient { /// <summary> /// Constructor. /// </summary> /// <param name="paragraph"> /// Paragraph associated with this object. /// </param> internal ContainerParaClient(ContainerParagraph paragraph) : base(paragraph) { } /// <summary> /// Arrange paragraph. /// </summary> /// <SecurityNote> /// Critical - as this calls Critical functions PTS.FsQuerySubtrackDetails, /// and some PtsHelper functions /// Safe - The IntPtr parameters passed to PTS.FsQuerySubtrackDetails are SecurityCriticalDataForSet /// which ensures that partial trust code won't be able to set it to a random value. /// The subtrackDetails parameter passed to other methods is generated securely in this function. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] protected override void OnArrange() { base.OnArrange(); // Query paragraph details PTS.FSSUBTRACKDETAILS subtrackDetails; PTS.Validate(PTS.FsQuerySubtrackDetails(PtsContext.Context, _paraHandle.Value, out subtrackDetails)); // Adjust rectangle and offset to take into account MBPs MbpInfo mbp = MbpInfo.FromElement(Paragraph.Element); if(ParentFlowDirection != PageFlowDirection) { mbp.MirrorMargin(); } _rect.u += mbp.MarginLeft; _rect.du -= mbp.MarginLeft + mbp.MarginRight; _rect.du = Math.Max(TextDpi.ToTextDpi(TextDpi.MinWidth), _rect.du); _rect.dv = Math.Max(TextDpi.ToTextDpi(TextDpi.MinWidth), _rect.dv); uint fswdirSubtrack = PTS.FlowDirectionToFswdir(_flowDirection); // There is possibility to get empty track. if (subtrackDetails.cParas != 0) { // Get list of paragraphs PTS.FSPARADESCRIPTION [] arrayParaDesc; PtsHelper.ParaListFromSubtrack(PtsContext, _paraHandle.Value, ref subtrackDetails, out arrayParaDesc); PtsHelper.ArrangeParaList(PtsContext, subtrackDetails.fsrc, arrayParaDesc, fswdirSubtrack); } } /// <summary> /// Hit tests to the correct IInputElement within the paragraph /// that the mouse is over. /// </summary> /// <param name="pt"> /// Point which gives location of Hit test /// </param> /// <SecurityNote> /// Critical - as this calls Critical functions PTS.FsQuerySubtrackDetails, /// Safe - The IntPtr parameters passed to PTS.FsQuerySubtrackDetails are SecurityCriticalDataForSet /// which ensures that partial trust code won't be able to set it to a random value. /// The subtrackDetails parameter passed to other methods is generated securely in this function. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal override IInputElement InputHitTest(PTS.FSPOINT pt) { IInputElement ie = null; // Query paragraph details PTS.FSSUBTRACKDETAILS subtrackDetails; PTS.Validate(PTS.FsQuerySubtrackDetails(PtsContext.Context, _paraHandle.Value, out subtrackDetails)); // Hittest subtrack content. // There might be possibility to get empty sub-track, skip the sub-track // in such case. if (subtrackDetails.cParas != 0) { // Get list of paragraphs PTS.FSPARADESCRIPTION [] arrayParaDesc; PtsHelper.ParaListFromSubtrack(PtsContext, _paraHandle.Value, ref subtrackDetails, out arrayParaDesc); // Render list of paragraphs ie = PtsHelper.InputHitTestParaList(PtsContext, pt, ref subtrackDetails.fsrc, arrayParaDesc); } // If nothing is hit, return the owner of the paragraph. if (ie == null && _rect.Contains(pt)) { ie = Paragraph.Element as IInputElement; } return ie; } /// <summary> /// Returns ArrayList of rectangles for the given ContentElement e if /// e lies in this client. Otherwise returns empty list. /// </summary> /// <param name="e"> /// ContentElement for which rectangles are needed /// </param> /// <param name="start"> /// Int representing start offset of e. /// </param> /// <param name="length"> /// int representing number of positions occupied by e. /// </param> /// <SecurityNote> /// Critical - as this calls Critical functions PTS.FsQuerySubtrackDetails, /// Safe - The IntPtr parameters passed to PTS.FsQuerySubtrackDetails are SecurityCriticalDataForSet /// which ensures that partial trust code won't be able to set it to a random value. /// The subtrackDetails parameter passed to other methods is generated securely in this function. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal override List<Rect> GetRectangles(ContentElement e, int start, int length) { List<Rect> rectangles = new List<Rect>(); if (this.Paragraph.Element as ContentElement == e) { // We have found the element. Return rectangles for this paragraph. GetRectanglesForParagraphElement(out rectangles); } else { // Element not found as Paragraph.Element. Look inside // Query paragraph details PTS.FSSUBTRACKDETAILS subtrackDetails; PTS.Validate(PTS.FsQuerySubtrackDetails(PtsContext.Context, _paraHandle.Value, out subtrackDetails)); // There might be possibility to get empty sub-track, skip the sub-track // in such case. if (subtrackDetails.cParas != 0) { // Get list of paragraphs // No changes to offset, since there are no subpages generated, only lists of paragraphs PTS.FSPARADESCRIPTION[] arrayParaDesc; PtsHelper.ParaListFromSubtrack(PtsContext, _paraHandle.Value, ref subtrackDetails, out arrayParaDesc); // Render list of paragraphs rectangles = PtsHelper.GetRectanglesInParaList(PtsContext, e, start, length, arrayParaDesc); } else { rectangles = new List<Rect>(); } } // Rectangles must be non-null Invariant.Assert(rectangles != null); return rectangles; } /// <summary> /// Validate visual node associated with paragraph. /// </summary> /// <param name="fskupdInherited"> /// Inherited update info /// </param> /// <SecurityNote> /// Critical - as this calls Critical functions PTS.FsQuerySubtrackDetails, /// Safe - The IntPtr parameters passed to PTS.FsQuerySubtrackDetails are SecurityCriticalDataForSet /// which ensures that partial trust code won't be able to set it to a random value. /// The subtrackDetails parameter passed to other methods is generated securely in this function. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal override void ValidateVisual(PTS.FSKUPDATE fskupdInherited) { // Query paragraph details PTS.FSSUBTRACKDETAILS subtrackDetails; PTS.Validate(PTS.FsQuerySubtrackDetails(PtsContext.Context, _paraHandle.Value, out subtrackDetails)); // Draw border and background info. // Adjust rectangle and offset to take into account MBPs MbpInfo mbp = MbpInfo.FromElement(Paragraph.Element); if(ThisFlowDirection != PageFlowDirection) { mbp.MirrorBP(); } Brush backgroundBrush = (Brush)Paragraph.Element.GetValue(TextElement.BackgroundProperty); _visual.DrawBackgroundAndBorder(backgroundBrush, mbp.BorderBrush, mbp.Border, _rect.FromTextDpi(), IsFirstChunk, IsLastChunk); // There might be possibility to get empty sub-track, skip the sub-track in such case. if (subtrackDetails.cParas != 0) { // Get list of paragraphs PTS.FSPARADESCRIPTION [] arrayParaDesc; PtsHelper.ParaListFromSubtrack(PtsContext, _paraHandle.Value, ref subtrackDetails, out arrayParaDesc); // Render list of paragraphs PtsHelper.UpdateParaListVisuals(PtsContext, _visual.Children, fskupdInherited, arrayParaDesc); } else { _visual.Children.Clear(); } } /// <summary> /// Updates the viewport for this para /// </summary> /// <param name="viewport"> /// Fsrect with viewport info /// </param> /// <SecurityNote> /// Critical - as this calls Critical functions PTS.FsQuerySubtrackDetails, /// and PtsHelper.ParaListFromSubtrack. /// Safe - The IntPtr parameters passed to PTS.FsQuerySubtrackDetails are SecurityCriticalDataForSet /// which ensures that partial trust code won't be able to set it to a random value. /// The subtrackDetails parameter passed to other methods is generated securely in this function. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal override void UpdateViewport(ref PTS.FSRECT viewport) { // Query paragraph details PTS.FSSUBTRACKDETAILS subtrackDetails; PTS.Validate(PTS.FsQuerySubtrackDetails(PtsContext.Context, _paraHandle.Value, out subtrackDetails)); // There might be possibility to get empty sub-track, skip the sub-track in such case. if (subtrackDetails.cParas != 0) { // Get list of paragraphs PTS.FSPARADESCRIPTION [] arrayParaDesc; PtsHelper.ParaListFromSubtrack(PtsContext, _paraHandle.Value, ref subtrackDetails, out arrayParaDesc); // Render list of paragraphs PtsHelper.UpdateViewportParaList(PtsContext, arrayParaDesc, ref viewport); } } /// <summary> /// Create and return paragraph result representing this paragraph. /// </summary> internal override ParagraphResult CreateParagraphResult() { /* // Query paragraph details PTS.FSSUBTRACKDETAILS subtrackDetails; PTS.Validate(PTS.FsQuerySubtrackDetails(PtsContext.Context, _paraHandle.Value, out subtrackDetails)); // If there is just one paragraph, do not create container. Return just this paragraph. if (subtrackDetails.cParas == 1) { // Get list of paragraphs PTS.FSPARADESCRIPTION [] arrayParaDesc; PtsHelper.ParaListFromSubtrack(_paraHandle.Value, ref subtrackDetails, out arrayParaDesc); BaseParaClient paraClient = PtsContext.HandleToObject(arrayParaDesc[0].pfsparaclient) as BaseParaClient; PTS.ValidateHandle(paraClient); return paraClient.CreateParagraphResult(); } */ return new ContainerParagraphResult(this); } /// <summary> /// Return TextContentRange for the content of the paragraph. /// </summary> /// <SecurityNote> /// Critical - as this calls Critical functions PTS.FsQuerySubtrackDetails /// Safe - The IntPtr parameters passed to PTS.FsQuerySubtrackDetails are SecurityCriticalDataForSet /// which ensures that partial trust code won't be able to set it to a random value. /// The subtrackDetails parameter passed to other methods is generated securely in this function. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal override TextContentRange GetTextContentRange() { TextElement elementOwner = this.Paragraph.Element as TextElement; TextContentRange textContentRange; BaseParaClient paraClient; PTS.FSSUBTRACKDETAILS subtrackDetails; PTS.FSPARADESCRIPTION[] arrayParaDesc; Invariant.Assert(elementOwner != null, "Expecting TextElement as owner of ContainerParagraph."); // Query paragraph details PTS.Validate(PTS.FsQuerySubtrackDetails(PtsContext.Context, _paraHandle.Value, out subtrackDetails)); // If container is empty, return range for the entire element. // If the beginning and the end of content of the paragraph is // part of this ParaClient, return range for the entire element. // Otherwise combine ranges from all nested paragraphs. if (subtrackDetails.cParas == 0 || (_isFirstChunk && _isLastChunk)) { textContentRange = TextContainerHelper.GetTextContentRangeForTextElement(elementOwner); } else { PtsHelper.ParaListFromSubtrack(PtsContext, _paraHandle.Value, ref subtrackDetails, out arrayParaDesc); // Merge TextContentRanges for all paragraphs textContentRange = new TextContentRange(); for (int i = 0; i < arrayParaDesc.Length; i++) { paraClient = Paragraph.StructuralCache.PtsContext.HandleToObject(arrayParaDesc[i].pfsparaclient) as BaseParaClient; PTS.ValidateHandle(paraClient); textContentRange.Merge(paraClient.GetTextContentRange()); } // If the first paragraph is the first paragraph in the container and it is the first chunk, // include start position of this element. if (_isFirstChunk) { textContentRange.Merge(TextContainerHelper.GetTextContentRangeForTextElementEdge( elementOwner, ElementEdge.BeforeStart)); } // If the last paragraph is the last paragraph in the container and it is the last chunk, // include end position of this element. if (_isLastChunk) { textContentRange.Merge(TextContainerHelper.GetTextContentRangeForTextElementEdge( elementOwner, ElementEdge.AfterEnd)); } } Invariant.Assert(textContentRange != null); return textContentRange; } /// <summary> /// Returns a new colleciton of ParagraphResults for the contained paragraphs. /// </summary> /// <SecurityNote> /// Critical - as this calls Critical functions PTS.FsQuerySubtrackDetails /// Safe - The IntPtr parameters passed to PTS.FsQuerySubtrackDetails are SecurityCriticalDataForSet /// which ensures that partial trust code won't be able to set it to a random value. /// The subtrackDetails parameter passed to other methods is generated securely in this function. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal ReadOnlyCollection<ParagraphResult> GetChildrenParagraphResults(out bool hasTextContent) { #if TEXTPANELLAYOUTDEBUG TextPanelDebug.IncrementCounter("ContainerPara.GetParagraphs", TextPanelDebug.Category.TextView); #endif // Query paragraph details PTS.FSSUBTRACKDETAILS subtrackDetails; PTS.Validate(PTS.FsQuerySubtrackDetails(PtsContext.Context, _paraHandle.Value, out subtrackDetails)); // hasTextContent is set to true if any of the children paragraphs has text content, not just attached objects hasTextContent = false; if (subtrackDetails.cParas == 0) { return new ReadOnlyCollection<ParagraphResult>(new List<ParagraphResult>(0)); } // Get list of paragraphs PTS.FSPARADESCRIPTION [] arrayParaDesc; PtsHelper.ParaListFromSubtrack(PtsContext, _paraHandle.Value, ref subtrackDetails, out arrayParaDesc); List<ParagraphResult> paragraphResults = new List<ParagraphResult>(arrayParaDesc.Length); for (int i = 0; i < arrayParaDesc.Length; i++) { BaseParaClient paraClient = PtsContext.HandleToObject(arrayParaDesc[i].pfsparaclient) as BaseParaClient; PTS.ValidateHandle(paraClient); ParagraphResult paragraphResult = paraClient.CreateParagraphResult(); if (paragraphResult.HasTextContent) { hasTextContent = true; } paragraphResults.Add(paragraphResult); } return new ReadOnlyCollection<ParagraphResult>(paragraphResults); } /// <summary> /// Update information about first/last chunk. /// </summary> /// <param name="isFirstChunk"> /// True if para is first chunk of paginated content /// </param> /// <param name="isLastChunk"> /// True if para is last chunk of paginated content /// </param> internal void SetChunkInfo(bool isFirstChunk, bool isLastChunk) { _isFirstChunk = isFirstChunk; _isLastChunk = isLastChunk; } /// <summary> /// Returns baseline for first text line /// </summary> /// <SecurityNote> /// Critical - as this calls Critical functions PTS.FsQuerySubtrackDetails /// Safe - The IntPtr parameters passed to PTS.FsQuerySubtrackDetails are SecurityCriticalDataForSet /// which ensures that partial trust code won't be able to set it to a random value. /// The subtrackDetails parameter passed to other methods is generated securely in this function. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal override int GetFirstTextLineBaseline() { PTS.FSSUBTRACKDETAILS subtrackDetails; PTS.Validate(PTS.FsQuerySubtrackDetails(PtsContext.Context, _paraHandle.Value, out subtrackDetails)); if (subtrackDetails.cParas == 0) { return _rect.v; } // Get list of paragraphs PTS.FSPARADESCRIPTION [] arrayParaDesc; PtsHelper.ParaListFromSubtrack(PtsContext, _paraHandle.Value, ref subtrackDetails, out arrayParaDesc); BaseParaClient paraClient = PtsContext.HandleToObject(arrayParaDesc[0].pfsparaclient) as BaseParaClient; PTS.ValidateHandle(paraClient); return paraClient.GetFirstTextLineBaseline(); } /// <summary> /// Returns tight bounding path geometry. /// </summary> internal Geometry GetTightBoundingGeometryFromTextPositions(ITextPointer startPosition, ITextPointer endPosition, Rect visibleRect) { bool hasTextContent; ReadOnlyCollection<ParagraphResult> paragraphs = GetChildrenParagraphResults(out hasTextContent); Invariant.Assert(paragraphs != null, "Paragraph collection is null."); if (paragraphs.Count > 0) { return (TextDocumentView.GetTightBoundingGeometryFromTextPositionsHelper(paragraphs, startPosition, endPosition, TextDpi.FromTextDpi(_dvrTopSpace), visibleRect)); } return null; } /// <summary> /// Is this the first chunk of paginated content. /// </summary> internal override bool IsFirstChunk { get { return _isFirstChunk; } } private bool _isFirstChunk; /// <summary> /// Is this the last chunk of paginated content. /// </summary> internal override bool IsLastChunk { get { return _isLastChunk; } } private bool _isLastChunk; } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Strategies.Algo File: StrategyHelper.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Strategies { using System; using System.ComponentModel; using Ecng.Common; using StockSharp.Algo.Strategies.Messages; using StockSharp.BusinessEntities; using StockSharp.Messages; using StockSharp.Localization; using StockSharp.Logging; /// <summary> /// Extension class for <see cref="Strategy"/>. /// </summary> public static partial class StrategyHelper { /// <summary> /// To create initialized object of buy order at market price. /// </summary> /// <param name="strategy">Strategy.</param> /// <param name="volume">The volume. If <see langword="null" /> value is passed, then <see cref="Strategy.Volume"/> value is used.</param> /// <returns>The initialized order object.</returns> /// <remarks> /// The order is not registered, only the object is created. /// </remarks> public static Order BuyAtMarket(this Strategy strategy, decimal? volume = null) { return strategy.CreateOrder(Sides.Buy, null, volume); } /// <summary> /// To create the initialized order object of sell order at market price. /// </summary> /// <param name="strategy">Strategy.</param> /// <param name="volume">The volume. If <see langword="null" /> value is passed, then <see cref="Strategy.Volume"/> value is used.</param> /// <returns>The initialized order object.</returns> /// <remarks> /// The order is not registered, only the object is created. /// </remarks> public static Order SellAtMarket(this Strategy strategy, decimal? volume = null) { return strategy.CreateOrder(Sides.Sell, null, volume); } /// <summary> /// To create the initialized order object for buy. /// </summary> /// <param name="strategy">Strategy.</param> /// <param name="price">Price.</param> /// <param name="volume">The volume. If <see langword="null" /> value is passed, then <see cref="Strategy.Volume"/> value is used.</param> /// <returns>The initialized order object.</returns> /// <remarks> /// The order is not registered, only the object is created. /// </remarks> public static Order BuyAtLimit(this Strategy strategy, decimal price, decimal? volume = null) { return strategy.CreateOrder(Sides.Buy, price, volume); } /// <summary> /// To create the initialized order object for sell. /// </summary> /// <param name="strategy">Strategy.</param> /// <param name="price">Price.</param> /// <param name="volume">The volume. If <see langword="null" /> value is passed, then <see cref="Strategy.Volume"/> value is used.</param> /// <returns>The initialized order object.</returns> /// <remarks> /// The order is not registered, only the object is created. /// </remarks> public static Order SellAtLimit(this Strategy strategy, decimal price, decimal? volume = null) { return strategy.CreateOrder(Sides.Sell, price, volume); } /// <summary> /// To create the initialized order object. /// </summary> /// <param name="strategy">Strategy.</param> /// <param name="direction">Order side.</param> /// <param name="price">The price. If <see langword="null" /> value is passed, the order is registered at market price.</param> /// <param name="volume">The volume. If <see langword="null" /> value is passed, then <see cref="Strategy.Volume"/> value is used.</param> /// <returns>The initialized order object.</returns> /// <remarks> /// The order is not registered, only the object is created. /// </remarks> public static Order CreateOrder(this Strategy strategy, Sides direction, decimal? price, decimal? volume = null) { if (strategy == null) throw new ArgumentNullException(nameof(strategy)); var security = strategy.Security; if (security == null) throw new InvalidOperationException(LocalizedStrings.Str1403Params.Put(strategy.Name)); var order = new Order { Portfolio = strategy.Portfolio, Security = strategy.Security, Direction = direction, Volume = volume ?? strategy.Volume, }; if (price == null) { //if (security.Board.IsSupportMarketOrders) order.Type = OrderTypes.Market; //else // order.Price = strategy.GetMarketPrice(direction) ?? 0; } else order.Price = price.Value; return order; } /// <summary> /// To close open position by market (to register the order of the type <see cref="OrderTypes.Market"/>). /// </summary> /// <param name="strategy">Strategy.</param> /// <param name="slippage">The slippage level, admissible at the order registration. It is used, if the order is registered using the limit order.</param> /// <remarks> /// The market order is not operable on all exchanges. /// </remarks> public static void ClosePosition(this Strategy strategy, decimal slippage = 0) { if (strategy == null) throw new ArgumentNullException(nameof(strategy)); var position = strategy.Position; if (position != 0) { var volume = position.Abs(); var order = position > 0 ? strategy.SellAtMarket(volume) : strategy.BuyAtMarket(volume); if (order.Type != OrderTypes.Market) { order.Price += (order.Direction == Sides.Buy ? slippage : -slippage); } strategy.RegisterOrder(order); } } private const string _isEmulationModeKey = "IsEmulationMode"; /// <summary> /// To get the strategy start-up mode (paper trading or real). /// </summary> /// <param name="strategy">Strategy.</param> /// <returns>If the paper trading mode is used - <see langword="true" />, otherwise - <see langword="false" />.</returns> public static bool GetIsEmulation(this Strategy strategy) { return strategy.Environment.GetValue(_isEmulationModeKey, false); } /// <summary> /// To get the strategy start-up mode (paper trading or real). /// </summary> /// <param name="strategy">Strategy.</param> /// <param name="isEmulation">If the paper trading mode is used - <see langword="true" />, otherwise - <see langword="false" />.</param> public static void SetIsEmulation(this Strategy strategy, bool isEmulation) { strategy.Environment.SetValue(_isEmulationModeKey, isEmulation); } /// <summary> /// To get market data value for the strategy instrument. /// </summary> /// <typeparam name="T">The type of the market data field value.</typeparam> /// <param name="strategy">Strategy.</param> /// <param name="field">Market-data field.</param> /// <returns>The field value. If no data, the <see langword="null" /> will be returned.</returns> public static T GetSecurityValue<T>(this Strategy strategy, Level1Fields field) { if (strategy == null) throw new ArgumentNullException(nameof(strategy)); return strategy.GetSecurityValue<T>(strategy.Security, field); } ///// <summary> ///// To get market price for the instrument by maximal and minimal possible prices. ///// </summary> ///// <param name="strategy">Strategy.</param> ///// <param name="side">Order side.</param> ///// <returns>The market price. If there is no information on maximal and minimal possible prices, then <see langword="null" /> will be returned.</returns> //public static decimal? GetMarketPrice(this Strategy strategy, Sides side) //{ // if (strategy == null) // throw new ArgumentNullException(nameof(strategy)); // return strategy.Security.GetMarketPrice(strategy.SafeGetConnector(), side); //} #region Strategy rules private abstract class StrategyRule<TArg> : MarketRule<Strategy, TArg> { protected StrategyRule(Strategy strategy) : base(strategy) { Strategy = strategy ?? throw new ArgumentNullException(nameof(strategy)); } protected Strategy Strategy { get; } } private sealed class PnLManagerStrategyRule : StrategyRule<decimal> { private readonly Func<decimal, bool> _changed; public PnLManagerStrategyRule(Strategy strategy) : this(strategy, v => true) { Name = LocalizedStrings.PnLChange; } public PnLManagerStrategyRule(Strategy strategy, Func<decimal, bool> changed) : base(strategy) { _changed = changed ?? throw new ArgumentNullException(nameof(changed)); Strategy.PnLChanged += OnPnLChanged; } private void OnPnLChanged() { if (_changed(Strategy.PnL)) Activate(Strategy.PnL); } protected override void DisposeManaged() { Strategy.PnLChanged -= OnPnLChanged; base.DisposeManaged(); } } private sealed class PositionManagerStrategyRule : StrategyRule<decimal> { private readonly Func<decimal, bool> _changed; public PositionManagerStrategyRule(Strategy strategy) : this(strategy, v => true) { Name = LocalizedStrings.Str1250; } public PositionManagerStrategyRule(Strategy strategy, Func<decimal, bool> changed) : base(strategy) { _changed = changed ?? throw new ArgumentNullException(nameof(changed)); Strategy.PositionChanged += OnPositionChanged; } private void OnPositionChanged() { if (_changed(Strategy.Position)) Activate(Strategy.Position); } protected override void DisposeManaged() { Strategy.PositionChanged -= OnPositionChanged; base.DisposeManaged(); } } private sealed class NewMyTradeStrategyRule : StrategyRule<MyTrade> { public NewMyTradeStrategyRule(Strategy strategy) : base(strategy) { Name = LocalizedStrings.Str1251 + " " + strategy; Strategy.NewMyTrade += OnStrategyNewMyTrade; } private void OnStrategyNewMyTrade(MyTrade trade) { Activate(trade); } protected override void DisposeManaged() { Strategy.NewMyTrade -= OnStrategyNewMyTrade; base.DisposeManaged(); } } private sealed class OrderRegisteredStrategyRule : StrategyRule<Order> { public OrderRegisteredStrategyRule(Strategy strategy) : base(strategy) { Name = LocalizedStrings.Str1252 + " " + strategy; Strategy.OrderRegistered += Activate; } protected override void DisposeManaged() { Strategy.OrderRegistered -= Activate; base.DisposeManaged(); } } private sealed class OrderChangedStrategyRule : StrategyRule<Order> { public OrderChangedStrategyRule(Strategy strategy) : base(strategy) { Name = LocalizedStrings.Str1253 + " " + strategy; Strategy.OrderChanged += Activate; } protected override void DisposeManaged() { Strategy.OrderChanged -= Activate; base.DisposeManaged(); } } private sealed class ProcessStateChangedStrategyRule : StrategyRule<Strategy> { private readonly Func<ProcessStates, bool> _condition; public ProcessStateChangedStrategyRule(Strategy strategy, Func<ProcessStates, bool> condition) : base(strategy) { _condition = condition ?? throw new ArgumentNullException(nameof(condition)); Strategy.ProcessStateChanged += OnProcessStateChanged; } private void OnProcessStateChanged(Strategy strategy) { if (_condition(Strategy.ProcessState)) Activate(Strategy); } protected override void DisposeManaged() { Strategy.ProcessStateChanged -= OnProcessStateChanged; base.DisposeManaged(); } } private sealed class PropertyChangedStrategyRule : StrategyRule<Strategy> { private readonly Func<Strategy, bool> _condition; public PropertyChangedStrategyRule(Strategy strategy, Func<Strategy, bool> condition) : base(strategy) { _condition = condition ?? throw new ArgumentNullException(nameof(condition)); Strategy.PropertyChanged += OnPropertyChanged; } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { if (_condition(Strategy)) Activate(Strategy); } protected override void DisposeManaged() { Strategy.PropertyChanged -= OnPropertyChanged; base.DisposeManaged(); } } private sealed class ErrorStrategyRule : StrategyRule<Exception> { private readonly bool _processChildStrategyErrors; public ErrorStrategyRule(Strategy strategy, bool processChildStrategyErrors) : base(strategy) { _processChildStrategyErrors = processChildStrategyErrors; Name = strategy + LocalizedStrings.Str1254; Strategy.Error += OnError; } private void OnError(Strategy strategy, Exception error) { if (!_processChildStrategyErrors && !Equals(Strategy, strategy)) return; Activate(error); } protected override void DisposeManaged() { Strategy.Error -= OnError; base.DisposeManaged(); } } /// <summary> /// To create a rule for the event of occurrence new strategy trade. /// </summary> /// <param name="strategy">The strategy, based on which trade occurrence will be traced.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, MyTrade> WhenNewMyTrade(this Strategy strategy) { return new NewMyTradeStrategyRule(strategy); } /// <summary> /// To create a rule for event of occurrence of new strategy order. /// </summary> /// <param name="strategy">The strategy, based on which order occurrence will be traced.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, Order> WhenOrderRegistered(this Strategy strategy) { return new OrderRegisteredStrategyRule(strategy); } /// <summary> /// To create a rule for event of change of any strategy order. /// </summary> /// <param name="strategy">The strategy, based on which orders change will be traced.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, Order> WhenOrderChanged(this Strategy strategy) { return new OrderChangedStrategyRule(strategy); } /// <summary> /// To create a rule for the event of strategy position change. /// </summary> /// <param name="strategy">The strategy, based on which position change will be traced.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, decimal> WhenPositionChanged(this Strategy strategy) { return new PositionManagerStrategyRule(strategy); } /// <summary> /// To create a rule for event of position event reduction below the specified level. /// </summary> /// <param name="strategy">The strategy, based on which position change will be traced.</param> /// <param name="value">The level. If the <see cref="Unit.Type"/> type equals to <see cref="UnitTypes.Limit"/>, specified price is set. Otherwise, shift value is specified.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, decimal> WhenPositionLess(this Strategy strategy, Unit value) { if (strategy == null) throw new ArgumentNullException(nameof(strategy)); if (value == null) throw new ArgumentNullException(nameof(value)); var finishPosition = value.Type == UnitTypes.Limit ? value : strategy.Position - value; return new PositionManagerStrategyRule(strategy, pos => pos < finishPosition) { Name = LocalizedStrings.Str1255Params.Put(finishPosition) }; } /// <summary> /// To create a rule for event of position event increase above the specified level. /// </summary> /// <param name="strategy">The strategy, based on which position change will be traced.</param> /// <param name="value">The level. If the <see cref="Unit.Type"/> type equals to <see cref="UnitTypes.Limit"/>, specified price is set. Otherwise, shift value is specified.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, decimal> WhenPositionMore(this Strategy strategy, Unit value) { if (strategy == null) throw new ArgumentNullException(nameof(strategy)); if (value == null) throw new ArgumentNullException(nameof(value)); var finishPosition = value.Type == UnitTypes.Limit ? value : strategy.Position + value; return new PositionManagerStrategyRule(strategy, pos => pos > finishPosition) { Name = LocalizedStrings.Str1256Params.Put(finishPosition) }; } /// <summary> /// To create a rule for event of profit reduction below the specified level. /// </summary> /// <param name="strategy">The strategy, based on which the profit change will be traced.</param> /// <param name="value">The level. If the <see cref="Unit.Type"/> type equals to <see cref="UnitTypes.Limit"/>, specified price is set. Otherwise, shift value is specified.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, decimal> WhenPnLLess(this Strategy strategy, Unit value) { if (strategy == null) throw new ArgumentNullException(nameof(strategy)); if (value == null) throw new ArgumentNullException(nameof(value)); var finishPosition = value.Type == UnitTypes.Limit ? value : strategy.PnL - value; return new PnLManagerStrategyRule(strategy, pos => pos < finishPosition) { Name = LocalizedStrings.Str1257Params.Put(finishPosition) }; } /// <summary> /// To create a rule for event of profit increase above the specified level. /// </summary> /// <param name="strategy">The strategy, based on which the profit change will be traced.</param> /// <param name="value">The level. If the <see cref="Unit.Type"/> type equals to <see cref="UnitTypes.Limit"/>, specified price is set. Otherwise, shift value is specified.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, decimal> WhenPnLMore(this Strategy strategy, Unit value) { if (strategy == null) throw new ArgumentNullException(nameof(strategy)); if (value == null) throw new ArgumentNullException(nameof(value)); var finishPosition = value.Type == UnitTypes.Limit ? value : strategy.PnL + value; return new PnLManagerStrategyRule(strategy, pos => pos > finishPosition) { Name = LocalizedStrings.Str1258Params.Put(finishPosition) }; } /// <summary> /// To create a rule for event of profit change. /// </summary> /// <param name="strategy">The strategy, based on which the profit change will be traced.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, decimal> WhenPnLChanged(this Strategy strategy) { return new PnLManagerStrategyRule(strategy); } /// <summary> /// To create a rule for event of start of strategy operation. /// </summary> /// <param name="strategy">The strategy, based on which the start of strategy operation will be expected.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, Strategy> WhenStarted(this Strategy strategy) { return new ProcessStateChangedStrategyRule(strategy, s => s == ProcessStates.Started) { Name = strategy + LocalizedStrings.Str1259, }; } /// <summary> /// To create a rule for event of beginning of the strategy operation stop. /// </summary> /// <param name="strategy">The strategy, based on which the beginning of stop will be determined.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, Strategy> WhenStopping(this Strategy strategy) { return new ProcessStateChangedStrategyRule(strategy, s => s == ProcessStates.Stopping) { Name = strategy + LocalizedStrings.Str1260, }; } /// <summary> /// To create a rule for event full stop of strategy operation. /// </summary> /// <param name="strategy">The strategy, based on which the full stop will be expected.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, Strategy> WhenStopped(this Strategy strategy) { return new ProcessStateChangedStrategyRule(strategy, s => s == ProcessStates.Stopped) { Name = strategy + LocalizedStrings.Str1261, }; } /// <summary> /// To create a rule for event of strategy error (transition of state <see cref="Strategy.ErrorState"/> into <see cref="LogLevels.Error"/>). /// </summary> /// <param name="strategy">The strategy, based on which error will be expected.</param> /// <param name="processChildStrategyErrors">Process the child strategies errors.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, Exception> WhenError(this Strategy strategy, bool processChildStrategyErrors = false) { return new ErrorStrategyRule(strategy, processChildStrategyErrors); } /// <summary> /// To create a rule for event of strategy warning (transition of state <see cref="Strategy.ErrorState"/> into <see cref="LogLevels.Warning"/>). /// </summary> /// <param name="strategy">The strategy, based on which the warning will be expected.</param> /// <returns>Rule.</returns> public static MarketRule<Strategy, Strategy> WhenWarning(this Strategy strategy) { return new PropertyChangedStrategyRule(strategy, s => s.ErrorState == LogLevels.Warning) { Name = strategy + LocalizedStrings.Str1262, }; } #endregion #region Order actions /// <summary> /// To create an action, registering the order. /// </summary> /// <param name="rule">Rule.</param> /// <param name="order">The order to be registered.</param> /// <returns>Rule.</returns> public static IMarketRule Register(this IMarketRule rule, Order order) { if (rule == null) throw new ArgumentNullException(nameof(rule)); if (order == null) throw new ArgumentNullException(nameof(order)); return rule.Do(() => GetRuleStrategy(rule).RegisterOrder(order)); } /// <summary> /// To create an action, re-registering the order. /// </summary> /// <param name="rule">Rule.</param> /// <param name="oldOrder">The order to be re-registered.</param> /// <param name="newOrder">Information about new order.</param> /// <returns>Rule.</returns> public static IMarketRule ReRegister(this IMarketRule rule, Order oldOrder, Order newOrder) { if (rule == null) throw new ArgumentNullException(nameof(rule)); if (oldOrder == null) throw new ArgumentNullException(nameof(oldOrder)); if (newOrder == null) throw new ArgumentNullException(nameof(newOrder)); return rule.Do(() => GetRuleStrategy(rule).ReRegisterOrder(oldOrder, newOrder)); } /// <summary> /// To create an action, cancelling the order. /// </summary> /// <param name="rule">Rule.</param> /// <param name="order">The order to be cancelled.</param> /// <returns>Rule.</returns> public static IMarketRule Cancel(this IMarketRule rule, Order order) { if (rule == null) throw new ArgumentNullException(nameof(rule)); if (order == null) throw new ArgumentNullException(nameof(order)); return rule.Do(() => GetRuleStrategy(rule).CancelOrder(order)); } #endregion private static Strategy GetRuleStrategy(IMarketRule rule) { if (rule == null) throw new ArgumentNullException(nameof(rule)); if (rule.Container is not Strategy strategy) throw new ArgumentException(LocalizedStrings.Str1263Params.Put(rule), nameof(rule)); return strategy; } /// <summary> /// Convert <see cref="Type"/> to <see cref="StrategyTypeMessage"/>. /// </summary> /// <param name="strategyType">Strategy type.</param> /// <param name="transactionId">ID of the original message <see cref="ITransactionIdMessage.TransactionId"/> for which this message is a response.</param> /// <returns>The message contains information about strategy type.</returns> public static StrategyTypeMessage ToTypeMessage(this Type strategyType, long transactionId = 0) { if (strategyType == null) throw new ArgumentNullException(nameof(strategyType)); return new StrategyTypeMessage { StrategyTypeId = strategyType.GetTypeName(false), StrategyName = strategyType.Name, OriginalTransactionId = transactionId, }; } } }
using System; using System.Collections.Generic; using System.Linq; using Signum.Entities.MachineLearning; using CNTK; using Signum.Entities.DynamicQuery; using Signum.Utilities; using Signum.Entities; using System.Diagnostics; using Signum.Engine.Files; using Signum.Engine.Operations; using Signum.Entities.UserAssets; using System.IO; namespace Signum.Engine.MachineLearning.CNTK { public class CNTKNeuralNetworkPredictorAlgorithm : IPredictorAlgorithm { public Dictionary<PredictorColumnEncodingSymbol, ICNTKEncoding> Encodings = new Dictionary<PredictorColumnEncodingSymbol, ICNTKEncoding> { { DefaultColumnEncodings.None, new NoneCNTKEncoding() }, { DefaultColumnEncodings.OneHot, new OneHotCNTKEncoding() }, { DefaultColumnEncodings.NormalizeZScore, new NormalizeZScoreCNTKEncoding() }, { DefaultColumnEncodings.NormalizeMinMax, new NormalizeMinMaxCNTKEncoding() }, { DefaultColumnEncodings.NormalizeLog, new NormalizeLogCNTKEncoding() }, { DefaultColumnEncodings.SplitWords, new SplitWordsCNTKEncoding() }, }; public void InitialSetup() { if (!Environment.Is64BitProcess) throw new InvalidOperationException("CNTK only works with starting projects compiled for x64"); /// This is a workaround to load unmanaged CNTK dlls from the applications \bin directory. var dir = AppDomain.CurrentDomain.BaseDirectory; if (!Directory.GetFiles(dir, "Cntk.Core.*.dll").Any()) { dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory!, "bin"); if (!Directory.Exists(dir) || !Directory.GetFiles(dir, "Cntk.Core.*.dll").Any()) throw new InvalidOperationException($@"No CNTK dll found in {AppDomain.CurrentDomain.BaseDirectory} or {Path.Combine(AppDomain.CurrentDomain.BaseDirectory!, "bin")}"); } var oldPath = Environment.GetEnvironmentVariable("Path")!; if (!oldPath.Contains(dir + ";")) Environment.SetEnvironmentVariable("Path", dir + ";" + oldPath, EnvironmentVariableTarget.Process); } public string? ValidateEncodingProperty(PredictorEntity predictor, PredictorSubQueryEntity? subQuery, PredictorColumnEncodingSymbol encoding, PredictorColumnUsage usage, QueryTokenEmbedded token) { return Encodings.GetOrThrow(encoding).ValidateEncodingProperty(predictor, subQuery, encoding, usage, token); } public List<PredictorCodification> GenerateCodifications(PredictorColumnEncodingSymbol encoding, ResultColumn resultColumn, PredictorColumnBase column) { return Encodings.GetOrThrow(encoding).GenerateCodifications(resultColumn, column); } public IEnumerable<PredictorColumnEncodingSymbol> GetRegisteredEncodingSymbols() { return Encodings.Keys; } public string[] GetAvailableDevices() { InitialSetup(); return DeviceDescriptor.AllDevices().Select(a => a.AsString()).ToArray(); } private DeviceDescriptor GetDevice(NeuralNetworkSettingsEntity nnSettings) { if (!nnSettings.Device.HasText()) return DeviceDescriptor.UseDefaultDevice(); var dev = DeviceDescriptor.AllDevices().FirstOrDefault(a => a.AsString() == nnSettings.Device); if(dev == null) return DeviceDescriptor.UseDefaultDevice(); return dev; } //Errors with CNTK: https://github.com/Microsoft/CNTK/issues/2614 public void Train(PredictorTrainingContext ctx) { InitialSetup(); var p = ctx.Predictor; var nn = (NeuralNetworkSettingsEntity)p.AlgorithmSettings; DeviceDescriptor device = GetDevice(nn); Variable inputVariable = Variable.InputVariable(new[] { ctx.InputCodifications.Count }, DataType.Float, "input"); Variable outputVariable = Variable.InputVariable(new[] { ctx.OutputCodifications.Count }, DataType.Float, "output"); Variable currentVar = inputVariable; nn.HiddenLayers.ForEach((layer, i) => { currentVar = NetworkBuilder.DenseLayer(currentVar, layer.Size, device, layer.Activation, layer.Initializer, p.Settings.Seed ?? 0, "hidden" + i); }); Function calculatedOutputs = NetworkBuilder.DenseLayer(currentVar, ctx.OutputCodifications.Count, device, nn.OutputActivation, nn.OutputInitializer, p.Settings.Seed ?? 0, "output"); Function loss = NetworkBuilder.GetEvalFunction(nn.LossFunction, calculatedOutputs, outputVariable); Function evalError = NetworkBuilder.GetEvalFunction(nn.EvalErrorFunction, calculatedOutputs, outputVariable); // prepare for training Learner learner = NetworkBuilder.GetInitializer(calculatedOutputs.Parameters(), nn); Trainer trainer = Trainer.CreateTrainer(calculatedOutputs, loss, evalError, new List<Learner>() { learner }); Random rand = p.Settings.Seed == null ? new Random() : new Random(p.Settings.Seed.Value); var (training, validation) = ctx.SplitTrainValidation(rand); var minibachtSize = nn.MinibatchSize; var numMinibatches = nn.NumMinibatches; Stopwatch sw = Stopwatch.StartNew(); List<FinalCandidate> candidate = new List<FinalCandidate>(); for (int i = 0; i < numMinibatches; i++) { using (HeavyProfiler.Log("MiniBatch", () => i.ToString())) { ctx.ReportProgress("Training Minibatches", (i + 1) / (decimal)numMinibatches); { var trainMinibatch = 0.To(minibachtSize).Select(_ => rand.NextElement(training)).ToList(); using (Value inputValue = CreateValue(ctx, trainMinibatch, ctx.InputCodifications.Count, ctx.InputCodificationsByColumn, device)) using (Value outputValue = CreateValue(ctx, trainMinibatch, ctx.OutputCodifications.Count, ctx.OutputCodificationsByColumn, device)) { using (HeavyProfiler.Log("TrainMinibatch", () => i.ToString())) trainer.TrainMinibatch(new Dictionary<Variable, Value>() { { inputVariable, inputValue }, { outputVariable, outputValue }, }, false, device); } } var ep = new EpochProgress { Ellapsed = sw.ElapsedMilliseconds, Epoch = i, TrainingExamples = (int)trainer.TotalNumberOfSamplesSeen(), LossTraining = trainer.PreviousMinibatchLossAverage(), EvaluationTraining = trainer.PreviousMinibatchEvaluationAverage(), LossValidation = null, EvaluationValidation = null, }; ctx.Progresses.Enqueue(ep); if (ctx.StopTraining) p = ctx.Predictor = ctx.Predictor.ToLite().RetrieveAndRemember(); var isLast = numMinibatches - nn.BestResultFromLast <= i; if (isLast || (i % nn.SaveProgressEvery) == 0 || ctx.StopTraining) { if (isLast || (i % nn.SaveValidationProgressEvery) == 0 || ctx.StopTraining) { using (HeavyProfiler.LogNoStackTrace("Validation")) { var validateMinibatch = 0.To(minibachtSize).Select(_ => rand.NextElement(validation)).ToList(); using (Value inputValValue = CreateValue(ctx, validateMinibatch, ctx.InputCodifications.Count, ctx.InputCodificationsByColumn, device)) using (Value outputValValue = CreateValue(ctx, validateMinibatch, ctx.OutputCodifications.Count, ctx.OutputCodificationsByColumn, device)) { var inputs = new Dictionary<Variable, Value>() { { inputVariable, inputValValue }, { outputVariable, outputValValue }, }; ep.LossValidation = loss.EvaluateAvg(inputs, device); ep.EvaluationValidation = evalError.EvaluateAvg(inputs, device); } } } var progress = ep.SaveEntity(ctx.Predictor); if (isLast || ctx.StopTraining) { using (HeavyProfiler.LogNoStackTrace("FinalCandidate")) { candidate.Add(new FinalCandidate { Model = calculatedOutputs.Save(), ResultTraining = new PredictorMetricsEmbedded { Evaluation = progress.EvaluationTraining, Loss = progress.LossTraining }, ResultValidation = new PredictorMetricsEmbedded { Evaluation = progress.EvaluationValidation, Loss = progress.LossValidation }, }); } } } if (ctx.StopTraining) break; } } var best = candidate.WithMin(a => a.ResultValidation.Loss!.Value); p.ResultTraining = best.ResultTraining; p.ResultValidation = best.ResultValidation; var fp = new Entities.Files.FilePathEmbedded(PredictorFileType.PredictorFile, "Model.cntk", best.Model); p.Files.Add(fp); using (OperationLogic.AllowSave<PredictorEntity>()) p.Save(); } #pragma warning disable CS8618 // Non-nullable field is uninitialized. public class FinalCandidate { public byte[] Model; public PredictorMetricsEmbedded ResultTraining; public PredictorMetricsEmbedded ResultValidation; } #pragma warning restore CS8618 // Non-nullable field is uninitialized. Value CreateValue(PredictorTrainingContext ctx, List<ResultRow> rows, int codificationCount, Dictionary<PredictorColumnBase, List<PredictorCodification>> codificationByColumn, DeviceDescriptor device) { using (HeavyProfiler.Log("CreateValue", () => $"Rows {rows.Count} Codifications {codificationCount}")) { float[] inputValues = new float[rows.Count * codificationCount]; for (int i = 0; i < rows.Count; i++) { ResultRow mainRow = rows[i]; var mainKey = ctx.MainQuery.GetParentKey(mainRow); int offset = i * codificationCount; foreach (var kvp in codificationByColumn) { PredictorColumnBase col = kvp.Key; object? value; if (col is PredictorColumnMain pcm) { value = mainRow[pcm.PredictorColumnIndex]; } else if (col is PredictorColumnSubQuery pcsq) { SubQuery sq = ctx.SubQueries.GetOrThrow(pcsq.SubQuery); object?[]? rowValues = sq.GroupedValues.TryGetC(mainKey)?.TryGetC(pcsq.Keys); value = rowValues == null ? null : rowValues[sq.ColumnIndexToValueIndex[pcsq.PredictorColumnIndex]]; } else { throw new UnexpectedValueException(col); } using (HeavyProfiler.LogNoStackTrace("EncodeValue")) { ICNTKEncoding encoding = Encodings.GetOrThrow(col.Encoding); encoding.EncodeValue(value ?? CNTKDefault.GetDefaultValue(kvp.Value.FirstOrDefault()), col, kvp.Value, inputValues, offset); } } } using (HeavyProfiler.LogNoStackTrace("CreateBatch")) return Value.CreateBatch<float>(new int[] { codificationCount }, inputValues, device); } } public PredictDictionary Predict(PredictorPredictContext ctx, PredictDictionary input) { return PredictMultiple(ctx, new List<PredictDictionary> { input }).SingleEx(); } public List<PredictDictionary> PredictMultiple(PredictorPredictContext ctx, List<PredictDictionary> inputs) { using (HeavyProfiler.LogNoStackTrace("PredictMultiple")) { var nnSettings = (NeuralNetworkSettingsEntity)ctx.Predictor.AlgorithmSettings; lock (lockKey) //https://docs.microsoft.com/en-us/cognitive-toolkit/cntk-library-evaluation-on-windows#evaluation-of-multiple-requests-in-parallel { Function calculatedOutputs = (Function)ctx.Model!; var device = GetDevice(nnSettings); Value inputValue = GetValueForPredict(ctx, inputs, device); var inputVar = calculatedOutputs.Inputs.SingleEx(i => i.Name == "input"); var inputDic = new Dictionary<Variable, Value> { { inputVar, inputValue } }; var outputDic = new Dictionary<Variable, Value> { { calculatedOutputs, null! } }; calculatedOutputs.Evaluate(inputDic, outputDic, device); Value output = outputDic[calculatedOutputs]; IList<IList<float>> values = output.GetDenseData<float>(calculatedOutputs); var result = values.Select((val, i) => GetPredictionDictionary(val.ToArray(), ctx, inputs[i].Options!)).ToList(); return result; } } } private PredictDictionary GetPredictionDictionary(float[] outputValues, PredictorPredictContext ctx, PredictionOptions options) { using (HeavyProfiler.LogNoStackTrace("GetPredictionDictionary")) { return new PredictDictionary(ctx.Predictor, options, null) { MainQueryValues = ctx.MainOutputCodifications.SelectDictionary(col => col, (col, list) => Encodings.GetOrThrow(col.Encoding).DecodeValue(list.First().Column, list, outputValues, options)), SubQueries = ctx.Predictor.SubQueries.ToDictionary(sq => sq, sq => new PredictSubQueryDictionary(sq) { SubQueryGroups = ctx.SubQueryOutputCodifications.TryGetC(sq)?.Groups.ToDictionary( kvp => kvp.Key, kvp => kvp.Value .Where(a => a.Key.Usage == PredictorSubQueryColumnUsage.Output) .ToDictionary(a => a.Key, a => Encodings.GetOrThrow(a.Key.Encoding).DecodeValue(a.Value.FirstEx().Column, a.Value, outputValues, options)), ObjectArrayComparer.Instance ) ?? new Dictionary<object?[], Dictionary<PredictorSubQueryColumnEmbedded, object?>>(ObjectArrayComparer.Instance), }) }; } } private Value GetValueForPredict(PredictorPredictContext ctx, List<PredictDictionary> inputs, DeviceDescriptor device) { using (HeavyProfiler.Log("GetValueForPredict", () => $"Inputs {inputs.Count} Codifications {ctx.InputCodifications.Count}")) { if (inputs.First().SubQueries.Values.Any(a => a.SubQueryGroups.Comparer != ObjectArrayComparer.Instance)) throw new Exception("Unexpected dictionary comparer"); float[] inputValues = new float[inputs.Count * ctx.InputCodifications.Count]; var groups = ctx.InputCodificationsByColumn; for (int i = 0; i < inputs.Count; i++) { PredictDictionary input = inputs[i]; int offset = i * ctx.InputCodifications.Count; foreach (var kvp in groups) { PredictorColumnBase col = kvp.Key; object? value; if (col is PredictorColumnMain pcm) { value = input.MainQueryValues.GetOrThrow(pcm.PredictorColumn); } else if (col is PredictorColumnSubQuery pcsq) { var sq = input.SubQueries.GetOrThrow(pcsq.SubQuery); var dic = sq.SubQueryGroups.TryGetC(pcsq.Keys); value = dic == null ? null : dic.GetOrThrow(pcsq.PredictorSubQueryColumn); } else { throw new UnexpectedValueException(col); } using (HeavyProfiler.LogNoStackTrace("EncodeValue")) { var enc = Encodings.GetOrThrow(col.Encoding); enc.EncodeValue(value ?? CNTKDefault.GetDefaultValue(kvp.Value.FirstOrDefault()), col, kvp.Value, inputValues, offset); } } } using (HeavyProfiler.LogNoStackTrace("CreateBatch")) return Value.CreateBatch<float>(new int[] { ctx.InputCodifications.Count }, inputValues, device); } } static object lockKey = new object(); public void LoadModel(PredictorPredictContext ctx) { lock (lockKey) { this.InitialSetup(); var nnSettings = (NeuralNetworkSettingsEntity)ctx.Predictor.AlgorithmSettings; ctx.Model = Function.Load(ctx.Predictor.Files.SingleEx().GetByteArray(), GetDevice(nnSettings)); } } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A motorcycle repair shop. /// </summary> public class MotorcycleRepair_Core : TypeCore, IAutomotiveBusiness { public MotorcycleRepair_Core() { this._TypeId = 167; this._Id = "MotorcycleRepair"; this._Schema_Org_Url = "http://schema.org/MotorcycleRepair"; string label = ""; GetLabel(out label, "MotorcycleRepair", typeof(MotorcycleRepair_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155,30}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{30}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
using UnityEngine; using UnityEditor; using System.Collections.Generic; public static class tk2dSpriteGuiUtility { public static int NameCompare(string na, string nb) { if (na.Length == 0 && nb.Length != 0) return 1; else if (na.Length != 0 && nb.Length == 0) return -1; else if (na.Length == 0 && nb.Length == 0) return 0; int numStartA = na.Length - 1; // last char is not a number, compare as regular strings if (na[numStartA] < '0' || na[numStartA] > '9') return System.String.Compare(na, nb, true); while (numStartA > 0 && na[numStartA - 1] >= '0' && na[numStartA - 1] <= '9') numStartA--; int comp = System.String.Compare(na, 0, nb, 0, numStartA); if (comp == 0) { if (nb.Length > numStartA) { bool numeric = true; for (int i = numStartA; i < nb.Length; ++i) { if (nb[i] < '0' || nb[i] > '9') { numeric = false; break; } } if (numeric) { int numA = System.Convert.ToInt32(na.Substring(numStartA)); int numB = System.Convert.ToInt32(nb.Substring(numStartA)); return numA - numB; } } } return System.String.Compare(na, nb); } public delegate void SpriteChangedCallback(tk2dSpriteCollectionData spriteCollection, int spriteIndex, object callbackData); class SpriteCollectionLUT { public int buildKey; public string[] sortedSpriteNames; public int[] spriteIdToSortedList; public int[] sortedListToSpriteId; } static Dictionary<string, SpriteCollectionLUT> spriteSelectorLUT = new Dictionary<string, SpriteCollectionLUT>(); public static void SpriteSelector( tk2dSpriteCollectionData spriteCollection, int spriteId, SpriteChangedCallback callback, object callbackData) { tk2dSpriteCollectionData newCollection = spriteCollection; int newSpriteId = spriteId; GUILayout.BeginHorizontal(); GUILayout.BeginVertical(); GUILayout.BeginHorizontal(); newCollection = SpriteCollectionList("Collection", spriteCollection); if (GUILayout.Button("o", EditorStyles.miniButton, GUILayout.Width(18))) { EditorGUIUtility.PingObject(spriteCollection); } GUILayout.EndHorizontal(); if (spriteCollection != null && spriteCollection.Count != 0) { if (spriteId < 0 || spriteId >= spriteCollection.Count || !spriteCollection.inst.spriteDefinitions[spriteId].Valid) { newSpriteId = spriteCollection.FirstValidDefinitionIndex; } GUILayout.BeginHorizontal(); newSpriteId = SpriteList( "Sprite", newSpriteId, spriteCollection ); if ( spriteCollection != null && spriteCollection.dataGuid != TransientGUID && GUILayout.Button( "e", EditorStyles.miniButton, GUILayout.Width(18), GUILayout.MaxHeight( 14f ) ) ) { tk2dSpriteCollection gen = AssetDatabase.LoadAssetAtPath( AssetDatabase.GUIDToAssetPath(spriteCollection.spriteCollectionGUID), typeof(tk2dSpriteCollection) ) as tk2dSpriteCollection; if ( gen != null ) { tk2dSpriteCollectionEditorPopup v = EditorWindow.GetWindow( typeof(tk2dSpriteCollectionEditorPopup), false, "Sprite Collection Editor" ) as tk2dSpriteCollectionEditorPopup; v.SetGeneratorAndSelectedSprite(gen, spriteId); } } GUILayout.EndHorizontal(); } if (callback != null && (newCollection != spriteCollection || newSpriteId != spriteId)) { callback(newCollection, newSpriteId, callbackData); } GUILayout.EndVertical(); if (GUILayout.Button("...", GUILayout.Height(32), GUILayout.Width(32))) { SpriteSelectorPopup( spriteCollection, spriteId, callback, callbackData ); } GUILayout.EndHorizontal(); } public static void SpriteSelectorPopup( tk2dSpriteCollectionData spriteCollection, int spriteId, SpriteChangedCallback callback, object callbackData) { tk2dSpritePickerPopup.DoPickSprite(spriteCollection, spriteId, "Select sprite", callback, callbackData); } static int SpriteList(string label, int spriteId, tk2dSpriteCollectionData rootSpriteCollection) { tk2dSpriteCollectionData spriteCollection = rootSpriteCollection.inst; int newSpriteId = spriteId; // cope with guid not existing if (spriteCollection.dataGuid == null || spriteCollection.dataGuid.Length == 0) { spriteCollection.dataGuid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(spriteCollection)); } SpriteCollectionLUT lut = null; spriteSelectorLUT.TryGetValue(spriteCollection.dataGuid, out lut); if (lut == null) { lut = new SpriteCollectionLUT(); lut.buildKey = spriteCollection.buildKey - 1; // force mismatch spriteSelectorLUT[spriteCollection.dataGuid] = lut; } if (lut.buildKey != spriteCollection.buildKey) { var spriteDefs = spriteCollection.spriteDefinitions; string[] spriteNames = new string[spriteDefs.Length]; int[] spriteLookupIndices = new int[spriteNames.Length]; for (int i = 0; i < spriteDefs.Length; ++i) { if (spriteDefs[i].name != null && spriteDefs[i].name.Length > 0) { if (tk2dPreferences.inst.showIds) spriteNames[i] = spriteDefs[i].name + "\t[" + i.ToString() + "]"; else spriteNames[i] = spriteDefs[i].name; spriteLookupIndices[i] = i; } } System.Array.Sort(spriteLookupIndices, (int a, int b) => tk2dSpriteGuiUtility.NameCompare((spriteDefs[a]!=null)?spriteDefs[a].name:"", (spriteDefs[b]!=null)?spriteDefs[b].name:"")); lut.sortedSpriteNames = new string[spriteNames.Length]; lut.sortedListToSpriteId = new int[spriteNames.Length]; lut.spriteIdToSortedList = new int[spriteNames.Length]; for (int i = 0; i < spriteLookupIndices.Length; ++i) { lut.spriteIdToSortedList[spriteLookupIndices[i]] = i; lut.sortedListToSpriteId[i] = spriteLookupIndices[i]; lut.sortedSpriteNames[i] = spriteNames[spriteLookupIndices[i]]; } lut.buildKey = spriteCollection.buildKey; } GUILayout.BeginHorizontal(); int spriteLocalIndex = lut.spriteIdToSortedList[spriteId]; int newSpriteLocalIndex = (label == null)?EditorGUILayout.Popup(spriteLocalIndex, lut.sortedSpriteNames):EditorGUILayout.Popup(label, spriteLocalIndex, lut.sortedSpriteNames); if (newSpriteLocalIndex != spriteLocalIndex) { newSpriteId = lut.sortedListToSpriteId[newSpriteLocalIndex]; } GUILayout.EndHorizontal(); return newSpriteId; } static List<tk2dSpriteCollectionIndex> allSpriteCollections = new List<tk2dSpriteCollectionIndex>(); static Dictionary<string, int> allSpriteCollectionLookup = new Dictionary<string, int>(); static string[] spriteCollectionNames = new string[0]; static string[] spriteCollectionNamesInclTransient = new string[0]; public static tk2dSpriteCollectionData GetDefaultSpriteCollection() { BuildLookupIndex(false); foreach (tk2dSpriteCollectionIndex indexEntry in allSpriteCollections) { if (!indexEntry.managedSpriteCollection && indexEntry.spriteNames != null) { foreach (string name in indexEntry.spriteNames) { if (name != null && name.Length > 0) { GameObject scgo = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(indexEntry.spriteCollectionDataGUID), typeof(GameObject)) as GameObject; if (scgo != null) return scgo.GetComponent<tk2dSpriteCollectionData>(); } } } } Debug.LogError("Unable to find any sprite collections."); return null; } static void BuildLookupIndex(bool force) { if (force) tk2dEditorUtility.ForceCreateIndex(); allSpriteCollections = new List<tk2dSpriteCollectionIndex>(); tk2dSpriteCollectionIndex[] mainIndex = tk2dEditorUtility.GetOrCreateIndex().GetSpriteCollectionIndex(); foreach (tk2dSpriteCollectionIndex i in mainIndex) { if (!i.managedSpriteCollection) allSpriteCollections.Add(i); } allSpriteCollections.Sort( (a, b) => tk2dSpriteGuiUtility.NameCompare(a.name, b.name) ); allSpriteCollectionLookup = new Dictionary<string, int>(); spriteCollectionNames = new string[allSpriteCollections.Count]; spriteCollectionNamesInclTransient = new string[allSpriteCollections.Count + 1]; for (int i = 0; i < allSpriteCollections.Count; ++i) { allSpriteCollectionLookup[allSpriteCollections[i].spriteCollectionDataGUID] = i; spriteCollectionNames[i] = allSpriteCollections[i].name; spriteCollectionNamesInclTransient[i] = allSpriteCollections[i].name; } spriteCollectionNamesInclTransient[allSpriteCollections.Count] = "-"; // transient sprite collection } public static void ResetCache() { allSpriteCollections.Clear(); } static tk2dSpriteCollectionData GetSpriteCollectionDataAtIndex(int index, tk2dSpriteCollectionData defaultValue) { if (index >= allSpriteCollections.Count) return defaultValue; GameObject go = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(allSpriteCollections[index].spriteCollectionDataGUID), typeof(GameObject)) as GameObject; if (go == null) return defaultValue; tk2dSpriteCollectionData data = go.GetComponent<tk2dSpriteCollectionData>(); if (data == null) return defaultValue; return data; } public static string TransientGUID { get { return "transient"; } } public static int GetValidSpriteId(tk2dSpriteCollectionData spriteCollection, int spriteId) { if (! (spriteId > 0 && spriteId < spriteCollection.spriteDefinitions.Length && spriteCollection.spriteDefinitions[spriteId].Valid) ) { spriteId = spriteCollection.FirstValidDefinitionIndex; if (spriteId == -1) spriteId = 0; } return spriteId; } public static tk2dSpriteCollectionData SpriteCollectionList(tk2dSpriteCollectionData currentValue) { // Initialize guid if not present if (currentValue != null && (currentValue.dataGuid == null || currentValue.dataGuid.Length == 0)) { string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(currentValue)); currentValue.dataGuid = (guid.Length == 0)?TransientGUID:guid; } if (allSpriteCollections == null || allSpriteCollections.Count == 0) BuildLookupIndex(false); if (currentValue == null || currentValue.dataGuid == TransientGUID) { int currentSelection = allSpriteCollections.Count; int newSelection = EditorGUILayout.Popup(currentSelection, spriteCollectionNamesInclTransient); if (newSelection != currentSelection) { currentValue = GetSpriteCollectionDataAtIndex(newSelection, currentValue); GUI.changed = true; } } else { int currentSelection = -1; for (int iter = 0; iter < 2; ++iter) // 2 passes in worst case { for (int i = 0; i < allSpriteCollections.Count; ++i) { if (allSpriteCollections[i].spriteCollectionDataGUID == currentValue.dataGuid) { currentSelection = i; break; } } if (currentSelection != -1) break; // found something on first pass // we are missing a sprite collection, rebuild index BuildLookupIndex(true); } if (currentSelection == -1) { Debug.LogError("Unable to find sprite collection. This is a serious problem."); GUILayout.Label(currentValue.spriteCollectionName, EditorStyles.popup); } else { int newSelection = EditorGUILayout.Popup(currentSelection, spriteCollectionNames); if (newSelection != currentSelection) { tk2dSpriteCollectionData newData = GetSpriteCollectionDataAtIndex(newSelection, currentValue); if (newData == null) { Debug.LogError("Unable to load sprite collection. Please rebuild index and try again."); } else if (newData.Count == 0) { EditorUtility.DisplayDialog("Error", string.Format("Sprite collection '{0}' has no sprites", newData.name), "Ok"); } else if (newData != currentValue) { currentValue = newData; GUI.changed = true; } } } } return currentValue; } static tk2dSpriteCollectionData SpriteCollectionList(string label, tk2dSpriteCollectionData currentValue) { GUILayout.BeginHorizontal(); if (label.Length > 0) EditorGUILayout.PrefixLabel(label); currentValue = SpriteCollectionList(currentValue); GUILayout.EndHorizontal(); return currentValue; } }
//////////////////////////////////////////////////////////////////////////////// // // // MIT X11 license, Copyright (c) 2005-2006 by: // // // // Authors: // // Michael Dominic K. <michaldominik@gmail.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. // // // //////////////////////////////////////////////////////////////////////////////// namespace Diva.Editor.Model { using System; public sealed class Window : IModelPart { // Fields ///////////////////////////////////////////////////// Root modelRoot = null; MessageStack messageStack; bool locked; // Events ///////////////////////////////////////////////////// public event ExceptionHandler InternalException; public event RequisitionHandler WaitCursorRequest; public event RequisitionHandler ProgressBarRequest; public event ProgressHandler UpdateProgress; public event RequisitionHandler HistoryWindowRequest; public event RequisitionHandler TagsWindowRequest; public event RequisitionHandler AboutWindowRequest; public event RequisitionHandler FullscreenRequest; public event RequisitionHandler ExportWindowRequest; public event RequisitionHandler LockRequest; public event MessageHandler UpdateMessage; // Properties ///////////////////////////////////////////////// public Root Root { get { return modelRoot; } } public string CurrentMessage { get { return messageStack.Message; } } public bool Locked { get { return locked; } } // Public methods ///////////////////////////////////////////// /* CONSTRUCTOR */ public Window (Root root) { modelRoot = root; locked = false; messageStack = new MessageStack (); messageStack.MessageChange += OnMessageChange; } public void RequestWaitCursor (bool requisition) { if (WaitCursorRequest != null) WaitCursorRequest (modelRoot, new RequisitionArgs (requisition)); } public void RequestProgressBar (bool requisition) { if (ProgressBarRequest != null) ProgressBarRequest (modelRoot, new RequisitionArgs (requisition)); } public void UpdateProgressBar (string message, double fraction) { if (UpdateProgress != null) UpdateProgress (modelRoot, new ProgressArgs (fraction, message, false)); } public void PulseProgressBar () { if (UpdateProgress != null) UpdateProgress (modelRoot, new ProgressArgs ()); } public void ShowHistoryWindow () { if (HistoryWindowRequest != null) HistoryWindowRequest (modelRoot, new RequisitionArgs (true)); } public void HideHistoryWindow () { if (HistoryWindowRequest != null) HistoryWindowRequest (modelRoot, new RequisitionArgs (false)); } public void ShowTagsWindow () { if (TagsWindowRequest != null) TagsWindowRequest (modelRoot, new RequisitionArgs (true)); } public void HideTagsWindow () { if (TagsWindowRequest != null) TagsWindowRequest (modelRoot, new RequisitionArgs (false)); } public void ShowAboutWindow () { if (AboutWindowRequest != null) AboutWindowRequest (modelRoot, new RequisitionArgs (true)); } public void HideAboutWindow () { if (AboutWindowRequest != null) AboutWindowRequest (modelRoot, new RequisitionArgs (false)); } public void PushInstantMessage (string message) { messageStack.PushInstantMessage (message); } public long PushMessage (string message, MessageLayer layer) { return messageStack.PushMessage (message, (int) layer); } public void PopMessage (long token) { messageStack.RemoveMessage (token); } internal void PushException (Exception excp) { // if (InternalException != null) // InternalException (modelRoot, new ExceptionArgs (excp)); // else throw excp; } public void StartFullscreen () { if (FullscreenRequest != null) FullscreenRequest (modelRoot, new RequisitionArgs (true)); } public void StopFullscreen () { if (FullscreenRequest != null) FullscreenRequest (modelRoot, new RequisitionArgs (false)); } public void Lock () { if (locked) return; if (LockRequest != null) LockRequest (modelRoot, new RequisitionArgs (true)); locked = true; } public void UnLock () { if (! locked) return; if (LockRequest != null) LockRequest (modelRoot, new RequisitionArgs (false)); locked = false; } public void ShowExportWindow () { if (ExportWindowRequest != null) ExportWindowRequest (modelRoot, new RequisitionArgs (true)); } public void HideExportWindow () { if (ExportWindowRequest != null) ExportWindowRequest (modelRoot, new RequisitionArgs (false)); } // Private methods ///////////////////////////////////////////// void OnMessageChange (object o, MessageArgs args) { if (UpdateMessage != null) UpdateMessage (modelRoot, args); } } }
using System; using System.Numerics; using System.Runtime.InteropServices; using System.Text; namespace ZenLibSharp.Parsing { public class ParserImplBinSafe : ParserImpl { /* ---------------------------------------------------------------------------------------------------------------------------------- */ public ParserImplBinSafe(ZenParser parser) : base(parser) { } /* ---------------------------------------------------------------------------------------------------------------------------------- */ public override bool readChunkStart(out ChunkHeader header) { int seek = m_pParser.m_Seek; try { EZenValueType type; int size; // Check if this actually will be a string readTypeAndSizeBinSafe(out type, out size); m_pParser.m_Seek = seek; if(type != EZenValueType.ZVT_STRING) { header = null; return false; // Next property isn't a string or the end } // Read chunk-header string vobDescriptor = readString(); // Early exit if this is a chunk-end or not a chunk header bool isChunkHeader = !string.IsNullOrEmpty (vobDescriptor) && vobDescriptor[0] == '[' && vobDescriptor[vobDescriptor.Length - 1] == ']' && vobDescriptor.Length > 2; if (!isChunkHeader) { m_pParser.m_Seek = seek; header = null; return false; } header = new ChunkHeader (); vobDescriptor = vobDescriptor.Substring (1, vobDescriptor.Length - 1); // Special case for camera keyframes if (vobDescriptor.IndexOf('%') > 0 && vobDescriptor.IndexOf('\xA7') > 0) { // Make a header with createObject = true and ref as classname var parts = vobDescriptor.Split (' '); header.createObject = true; header.classname = "\xA7"; header.name = "%"; header.size = 0; header.version = 0; header.objectID = uint.Parse (parts[parts.Length - 1]); return true; } // Save chunks starting-position (right after chunk-header) header.startPosition = (uint)m_pParser.m_Seek; // Parse chunk-header string[] vec = vobDescriptor.Split (' '); string name = null; string className = null; int classVersion = 0; int objectID = 0; bool createObject = false; ParserState state = ParserState.S_OBJECT_NAME; foreach (var arg in vec) { switch(state) { case ParserState.S_OBJECT_NAME: if (arg != "%") { name = arg; state = ParserState.S_REFERENCE; break; } else { goto case ParserState.S_REFERENCE; } case ParserState.S_REFERENCE: if(arg == "%") { createObject = true; state = ParserState.S_CLASS_NAME; break; } else if(arg == "\xA7") { createObject = false; state = ParserState.S_CLASS_NAME; break; } else { createObject = true; goto case ParserState.S_CLASS_NAME; } case ParserState.S_CLASS_NAME: int num; if (!int.TryParse (arg, out num)) { className = arg; state = ParserState.S_CLASS_VERSION; break; } else { goto case ParserState.S_CLASS_VERSION; } case ParserState.S_CLASS_VERSION: classVersion = int.Parse (arg); state = ParserState.S_OBJECT_ID; break; case ParserState.S_OBJECT_ID: objectID = int.Parse (arg); state = ParserState.S_FINISHED; break; default: throw new InvalidOperationException("Strange parser state"); } } if(state != ParserState.S_FINISHED) throw new InvalidOperationException("Parser did not finish"); header.classname = className; header.createObject = createObject; header.name = name; header.objectID = (uint)objectID; header.size = 0; // Doesn't matter in ASCII header.version = (uint)classVersion; } catch (Exception e) { Logger.LogError ($"Failed to read chunk header due to an error: {e}"); m_pParser.m_Seek = seek; header = null; return false; } return true; } /* ---------------------------------------------------------------------------------------------------------------------------------- */ public override bool readChunkEnd() { int seek = m_pParser.m_Seek; try { EZenValueType type; int size; // Check if this actually will be a string readTypeAndSizeBinSafe(out type, out size); m_pParser.m_Seek = seek; if(type != EZenValueType.ZVT_STRING) return false; // Next property isn't a string or the end string l = readString(); if(l != "[]") { m_pParser.m_Seek = seek; return false; } } catch(Exception e) { Logger.LogError ($"Failed to read chunk end due to an error: {e}"); m_pParser.m_Seek = seek; return false; // Next property isn't a string or the end } return true; } /* ---------------------------------------------------------------------------------------------------------------------------------- */ public override void readImplHeader() { // Bin-Safe archiver has its own version stored again for some reason m_pParser.m_Header.binSafeHeader.bsVersion = m_pParser.readBinaryDWord(); // Read object count m_pParser.m_Header.objectCount = (int)m_pParser.readBinaryDWord(); // Read offset of where to find the global hash-table of all objects m_pParser.m_Header.binSafeHeader.bsHashTableOffset = m_pParser.readBinaryDWord(); // Read hashtable int s = m_pParser.m_Seek; m_pParser.m_Seek = ((int)m_pParser.m_Header.binSafeHeader.bsHashTableOffset); UInt32 htSize = m_pParser.readBinaryDWord(); for(UInt32 i = 0; i < htSize; i++) { UInt16 keyLen = m_pParser.readBinaryWord(); UInt16 insIdx = m_pParser.readBinaryWord(); UInt32 hashValue = m_pParser.readBinaryDWord(); // Read the keys data from the archive byte[] keyData = new byte[keyLen]; m_pParser.readBinaryRaw (keyData, keyLen); } // Restore old position m_pParser.m_Seek = s; } /* ---------------------------------------------------------------------------------------------------------------------------------- */ public override string readString() { EZenValueType type; int size; // These values start with a small header readTypeAndSizeBinSafe(out type, out size); if(type != EZenValueType.ZVT_STRING) throw new ArgumentException("Expected string-type"); byte[] stringBuffer = new byte[size]; m_pParser.readBinaryRaw (stringBuffer, size); // Skip potential hash-value at the end of the string EZenValueType t = (EZenValueType)(m_pParser.readBinaryByte()); if(t != EZenValueType.ZVT_HASH) m_pParser.m_Seek -= -sizeof(byte); else m_pParser.m_Seek += sizeof(UInt32); return Encoding.ASCII.GetString (stringBuffer); } /* ---------------------------------------------------------------------------------------------------------------------------------- */ void readTypeAndSizeBinSafe (out EZenValueType type, out int size) { type = (EZenValueType)m_pParser.readBinaryByte (); size = 0; switch(type) { case EZenValueType.ZVT_VEC3: size = sizeof(float) * 3; break; case EZenValueType.ZVT_BYTE: size = sizeof(byte); break; case EZenValueType.ZVT_WORD: size = sizeof(UInt16); break; case EZenValueType.ZVT_RAW: case EZenValueType.ZVT_RAW_FLOAT: case EZenValueType.ZVT_STRING: size = m_pParser.readBinaryWord(); break; case EZenValueType.ZVT_INT: case EZenValueType.ZVT_ENUM: case EZenValueType.ZVT_BOOL: case EZenValueType.ZVT_HASH: case EZenValueType.ZVT_FLOAT: case EZenValueType.ZVT_COLOR: size = sizeof(UInt32); // FIXME: Bool might be only 8 bytes break; default: throw new InvalidOperationException("BinSafe: Datatype not implemented"); } } /* ---------------------------------------------------------------------------------------------------------------------------------- */ public override unsafe void readEntry(string expectedName, void* target, int targetSize, EZenValueType expectedType = EZenValueType.ZVT_0) { EZenValueType type; int size; // Read type and size of the entry readTypeAndSizeBinSafe (out type, out size); // These are the same in size if(expectedType == EZenValueType.ZVT_INT) { if(type == EZenValueType.ZVT_COLOR) type = EZenValueType.ZVT_INT; if(type == EZenValueType.ZVT_ENUM && size == sizeof(UInt32)) type = EZenValueType.ZVT_INT; // Enum seems the be there in both 1 and 4 byte? } if(expectedType != EZenValueType.ZVT_BYTE || type != EZenValueType.ZVT_ENUM) // International CSLibs have this if(expectedType != EZenValueType.ZVT_0 && type != expectedType) throw new InvalidOperationException("Valuetype name does not match expected type. Value:" + expectedName); switch(type) { case EZenValueType.ZVT_0: break; case EZenValueType.ZVT_STRING: { byte[] stringBuffer = new byte[size]; m_pParser.readBinaryRaw (stringBuffer, size); var stringHandle = GCHandle.FromIntPtr ((IntPtr)target); stringHandle.Target = Encoding.ASCII.GetString (stringBuffer); } break; case EZenValueType.ZVT_HASH: case EZenValueType.ZVT_INT: *(UInt32*)(target) = m_pParser.readBinaryDWord(); break; case EZenValueType.ZVT_FLOAT: *(float*)(target) = m_pParser.readBinaryFloat(); break; case EZenValueType.ZVT_BYTE: *(byte*)(target) = m_pParser.readBinaryByte(); break; case EZenValueType.ZVT_WORD: *(UInt16*)(target) = m_pParser.readBinaryWord(); break; case EZenValueType.ZVT_BOOL: *(bool*)(target) = m_pParser.readBinaryDWord() != 0; break; case EZenValueType.ZVT_VEC3: ((Vector3*)target)->X = m_pParser.readBinaryFloat(); ((Vector3*)target)->Y = m_pParser.readBinaryFloat(); ((Vector3*)target)->Z = m_pParser.readBinaryFloat(); break; case EZenValueType.ZVT_COLOR: ((byte*)target)[0] = m_pParser.readBinaryByte(); // FIXME: These are/may ordered wrong ((byte*)target)[1] = m_pParser.readBinaryByte(); ((byte*)target)[2] = m_pParser.readBinaryByte(); ((byte*)target)[3] = m_pParser.readBinaryByte(); break; case EZenValueType.ZVT_RAW_FLOAT: case EZenValueType.ZVT_RAW: m_pParser.readBinaryRaw((byte*)target, size); break; case EZenValueType.ZVT_10: break; case EZenValueType.ZVT_11: break; case EZenValueType.ZVT_12: break; case EZenValueType.ZVT_13: break; case EZenValueType.ZVT_14: break; case EZenValueType.ZVT_15: break; case EZenValueType.ZVT_ENUM: *(byte*)(target) = (byte)m_pParser.readBinaryDWord(); break; // TODO: Check why the hell there is a DWORD read when parsing to a byte? } // Skip potential hash-value at the end of the entry EZenValueType t = (EZenValueType)m_pParser.readBinaryByte(); if (t != EZenValueType.ZVT_HASH) m_pParser.m_Seek -= -sizeof (byte); else m_pParser.m_Seek += sizeof (UInt32); } /* ---------------------------------------------------------------------------------------------------------------------------------- */ public override void readEntryType(out EZenValueType type, out int size) { readTypeAndSizeBinSafe(out type, out size); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; using Lucene.Net.Documents; namespace Lucene.Net.Index { using Lucene.Net.Support; using BinaryDocValuesField = BinaryDocValuesField; using Bits = Lucene.Net.Util.Bits; using BytesRef = Lucene.Net.Util.BytesRef; /* * 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 Codec = Lucene.Net.Codecs.Codec; using Directory = Lucene.Net.Store.Directory; using DocValuesConsumer = Lucene.Net.Codecs.DocValuesConsumer; using DocValuesFormat = Lucene.Net.Codecs.DocValuesFormat; using IOContext = Lucene.Net.Store.IOContext; using IOUtils = Lucene.Net.Util.IOUtils; using LiveDocsFormat = Lucene.Net.Codecs.LiveDocsFormat; using MutableBits = Lucene.Net.Util.MutableBits; using NumericDocValuesField = NumericDocValuesField; using TrackingDirectoryWrapper = Lucene.Net.Store.TrackingDirectoryWrapper; // Used by IndexWriter to hold open SegmentReaders (for // searching or merging), plus pending deletes and updates, // for a given segment public class ReadersAndUpdates { // Not final because we replace (clone) when we need to // change it and it's been shared: public readonly SegmentCommitInfo Info; // Tracks how many consumers are using this instance: private readonly AtomicInteger RefCount_Renamed = new AtomicInteger(1); private readonly IndexWriter Writer; // Set once (null, and then maybe set, and never set again): private SegmentReader Reader; // TODO: it's sometimes wasteful that we hold open two // separate SRs (one for merging one for // reading)... maybe just use a single SR? The gains of // not loading the terms index (for merging in the // non-NRT case) are far less now... and if the app has // any deletes it'll open real readers anyway. // Set once (null, and then maybe set, and never set again): private SegmentReader MergeReader; // Holds the current shared (readable and writable) // liveDocs. this is null when there are no deleted // docs, and it's copy-on-write (cloned whenever we need // to change it but it's been shared to an external NRT // reader). private Bits LiveDocs_Renamed; // How many further deletions we've done against // liveDocs vs when we loaded it or last wrote it: private int PendingDeleteCount_Renamed; // True if the current liveDocs is referenced by an // external NRT reader: private bool LiveDocsShared; // Indicates whether this segment is currently being merged. While a segment // is merging, all field updates are also registered in the // mergingNumericUpdates map. Also, calls to writeFieldUpdates merge the // updates with mergingNumericUpdates. // That way, when the segment is done merging, IndexWriter can apply the // updates on the merged segment too. private bool IsMerging = false; private readonly IDictionary<string, DocValuesFieldUpdates> MergingDVUpdates = new Dictionary<string, DocValuesFieldUpdates>(); public ReadersAndUpdates(IndexWriter writer, SegmentCommitInfo info) { this.Info = info; this.Writer = writer; LiveDocsShared = true; } public virtual void IncRef() { int rc = RefCount_Renamed.IncrementAndGet(); Debug.Assert(rc > 1); } public virtual void DecRef() { int rc = RefCount_Renamed.DecrementAndGet(); Debug.Assert(rc >= 0); } public virtual int RefCount() { int rc = RefCount_Renamed.Get(); Debug.Assert(rc >= 0); return rc; } public virtual int PendingDeleteCount { get { lock (this) { return PendingDeleteCount_Renamed; } } } // Call only from assert! public virtual bool VerifyDocCounts() { lock (this) { int count; if (LiveDocs_Renamed != null) { count = 0; for (int docID = 0; docID < Info.Info.DocCount; docID++) { if (LiveDocs_Renamed.Get(docID)) { count++; } } } else { count = Info.Info.DocCount; } Debug.Assert(Info.Info.DocCount - Info.DelCount - PendingDeleteCount_Renamed == count, "info.docCount=" + Info.Info.DocCount + " info.getDelCount()=" + Info.DelCount + " pendingDeleteCount=" + PendingDeleteCount_Renamed + " count=" + count); return true; } } /// <summary> /// Returns a <seealso cref="SegmentReader"/>. </summary> public virtual SegmentReader GetReader(IOContext context) { if (Reader == null) { // We steal returned ref: Reader = new SegmentReader(Info, Writer.Config.ReaderTermsIndexDivisor, context); if (LiveDocs_Renamed == null) { LiveDocs_Renamed = Reader.LiveDocs; } } // Ref for caller Reader.IncRef(); return Reader; } // Get reader for merging (does not load the terms // index): public virtual SegmentReader GetMergeReader(IOContext context) { lock (this) { //System.out.println(" livedocs=" + rld.liveDocs); if (MergeReader == null) { if (Reader != null) { // Just use the already opened non-merge reader // for merging. In the NRT case this saves us // pointless double-open: //System.out.println("PROMOTE non-merge reader seg=" + rld.info); // Ref for us: Reader.IncRef(); MergeReader = Reader; //System.out.println(Thread.currentThread().getName() + ": getMergeReader share seg=" + info.name); } else { //System.out.println(Thread.currentThread().getName() + ": getMergeReader seg=" + info.name); // We steal returned ref: MergeReader = new SegmentReader(Info, -1, context); if (LiveDocs_Renamed == null) { LiveDocs_Renamed = MergeReader.LiveDocs; } } } // Ref for caller MergeReader.IncRef(); return MergeReader; } } public virtual void Release(SegmentReader sr) { lock (this) { Debug.Assert(Info == sr.SegmentInfo); sr.DecRef(); } } public virtual bool Delete(int docID) { lock (this) { Debug.Assert(LiveDocs_Renamed != null); //Debug.Assert(Thread.holdsLock(Writer)); Debug.Assert(docID >= 0 && docID < LiveDocs_Renamed.Length(), "out of bounds: docid=" + docID + " liveDocsLength=" + LiveDocs_Renamed.Length() + " seg=" + Info.Info.Name + " docCount=" + Info.Info.DocCount); Debug.Assert(!LiveDocsShared); bool didDelete = LiveDocs_Renamed.Get(docID); if (didDelete) { ((MutableBits)LiveDocs_Renamed).Clear(docID); PendingDeleteCount_Renamed++; //System.out.println(" new del seg=" + info + " docID=" + docID + " pendingDelCount=" + pendingDeleteCount + " totDelCount=" + (info.docCount-liveDocs.count())); } return didDelete; } } // NOTE: removes callers ref public virtual void DropReaders() { lock (this) { // TODO: can we somehow use IOUtils here...? problem is // we are calling .decRef not .close)... try { if (Reader != null) { //System.out.println(" pool.drop info=" + info + " rc=" + reader.getRefCount()); try { Reader.DecRef(); } finally { Reader = null; } } } finally { if (MergeReader != null) { //System.out.println(" pool.drop info=" + info + " merge rc=" + mergeReader.getRefCount()); try { MergeReader.DecRef(); } finally { MergeReader = null; } } } DecRef(); } } /// <summary> /// Returns a ref to a clone. NOTE: you should decRef() the reader when you're /// dont (ie do not call close()). /// </summary> public virtual SegmentReader GetReadOnlyClone(IOContext context) { lock (this) { if (Reader == null) { GetReader(context).DecRef(); Debug.Assert(Reader != null); } LiveDocsShared = true; if (LiveDocs_Renamed != null) { return new SegmentReader(Reader.SegmentInfo, Reader, LiveDocs_Renamed, Info.Info.DocCount - Info.DelCount - PendingDeleteCount_Renamed); } else { Debug.Assert(Reader.LiveDocs == LiveDocs_Renamed); Reader.IncRef(); return Reader; } } } public virtual void InitWritableLiveDocs() { lock (this) { //Debug.Assert(Thread.holdsLock(Writer)); Debug.Assert(Info.Info.DocCount > 0); //System.out.println("initWritableLivedocs seg=" + info + " liveDocs=" + liveDocs + " shared=" + shared); if (LiveDocsShared) { // Copy on write: this means we've cloned a // SegmentReader sharing the current liveDocs // instance; must now make a private clone so we can // change it: LiveDocsFormat liveDocsFormat = Info.Info.Codec.LiveDocsFormat(); if (LiveDocs_Renamed == null) { //System.out.println("create BV seg=" + info); LiveDocs_Renamed = liveDocsFormat.NewLiveDocs(Info.Info.DocCount); } else { LiveDocs_Renamed = liveDocsFormat.NewLiveDocs(LiveDocs_Renamed); } LiveDocsShared = false; } } } public virtual Bits LiveDocs { get { lock (this) { //Debug.Assert(Thread.holdsLock(Writer)); return LiveDocs_Renamed; } } } public virtual Bits ReadOnlyLiveDocs { get { lock (this) { //System.out.println("getROLiveDocs seg=" + info); //Debug.Assert(Thread.holdsLock(Writer)); LiveDocsShared = true; //if (liveDocs != null) { //System.out.println(" liveCount=" + liveDocs.count()); //} return LiveDocs_Renamed; } } } public virtual void DropChanges() { lock (this) { // Discard (don't save) changes when we are dropping // the reader; this is used only on the sub-readers // after a successful merge. If deletes had // accumulated on those sub-readers while the merge // is running, by now we have carried forward those // deletes onto the newly merged segment, so we can // discard them on the sub-readers: PendingDeleteCount_Renamed = 0; DropMergingUpdates(); } } // Commit live docs (writes new _X_N.del files) and field updates (writes new // _X_N updates files) to the directory; returns true if it wrote any file // and false if there were no new deletes or updates to write: // TODO (DVU_RENAME) to writeDeletesAndUpdates public virtual bool WriteLiveDocs(Directory dir) { lock (this) { //Debug.Assert(Thread.holdsLock(Writer)); //System.out.println("rld.writeLiveDocs seg=" + info + " pendingDelCount=" + pendingDeleteCount + " numericUpdates=" + numericUpdates); if (PendingDeleteCount_Renamed == 0) { return false; } // We have new deletes Debug.Assert(LiveDocs_Renamed.Length() == Info.Info.DocCount); // Do this so we can delete any created files on // exception; this saves all codecs from having to do // it: TrackingDirectoryWrapper trackingDir = new TrackingDirectoryWrapper(dir); // We can write directly to the actual name (vs to a // .tmp & renaming it) because the file is not live // until segments file is written: bool success = false; try { Codec codec = Info.Info.Codec; codec.LiveDocsFormat().WriteLiveDocs((MutableBits)LiveDocs_Renamed, trackingDir, Info, PendingDeleteCount_Renamed, IOContext.DEFAULT); success = true; } finally { if (!success) { // Advance only the nextWriteDelGen so that a 2nd // attempt to write will write to a new file Info.AdvanceNextWriteDelGen(); // Delete any partially created file(s): foreach (string fileName in trackingDir.CreatedFiles) { try { dir.DeleteFile(fileName); } catch (Exception) { // Ignore so we throw only the first exc } } } } // If we hit an exc in the line above (eg disk full) // then info's delGen remains pointing to the previous // (successfully written) del docs: Info.AdvanceDelGen(); Info.DelCount = Info.DelCount + PendingDeleteCount_Renamed; PendingDeleteCount_Renamed = 0; return true; } } // Writes field updates (new _X_N updates files) to the directory public virtual void WriteFieldUpdates(Directory dir, DocValuesFieldUpdates.Container dvUpdates) { lock (this) { //Debug.Assert(Thread.holdsLock(Writer)); //System.out.println("rld.writeFieldUpdates: seg=" + info + " numericFieldUpdates=" + numericFieldUpdates); Debug.Assert(dvUpdates.Any()); // Do this so we can delete any created files on // exception; this saves all codecs from having to do // it: TrackingDirectoryWrapper trackingDir = new TrackingDirectoryWrapper(dir); FieldInfos fieldInfos = null; bool success = false; try { Codec codec = Info.Info.Codec; // reader could be null e.g. for a just merged segment (from // IndexWriter.commitMergedDeletes). SegmentReader reader = this.Reader == null ? new SegmentReader(Info, Writer.Config.ReaderTermsIndexDivisor, IOContext.READONCE) : this.Reader; try { // clone FieldInfos so that we can update their dvGen separately from // the reader's infos and write them to a new fieldInfos_gen file FieldInfos.Builder builder = new FieldInfos.Builder(Writer.GlobalFieldNumberMap); // cannot use builder.add(reader.getFieldInfos()) because it does not // clone FI.attributes as well FI.dvGen foreach (FieldInfo fi in reader.FieldInfos) { FieldInfo clone = builder.Add(fi); // copy the stuff FieldInfos.Builder doesn't copy if (fi.Attributes() != null) { foreach (KeyValuePair<string, string> e in fi.Attributes()) { clone.PutAttribute(e.Key, e.Value); } } clone.DocValuesGen = fi.DocValuesGen; } // create new fields or update existing ones to have NumericDV type foreach (string f in dvUpdates.NumericDVUpdates.Keys) { builder.AddOrUpdate(f, NumericDocValuesField.TYPE); } // create new fields or update existing ones to have BinaryDV type foreach (string f in dvUpdates.BinaryDVUpdates.Keys) { builder.AddOrUpdate(f, BinaryDocValuesField.fType); } fieldInfos = builder.Finish(); long nextFieldInfosGen = Info.NextFieldInfosGen; string segmentSuffix = nextFieldInfosGen.ToString(CultureInfo.InvariantCulture);//Convert.ToString(nextFieldInfosGen, Character.MAX_RADIX)); SegmentWriteState state = new SegmentWriteState(null, trackingDir, Info.Info, fieldInfos, Writer.Config.TermIndexInterval, null, IOContext.DEFAULT, segmentSuffix); DocValuesFormat docValuesFormat = codec.DocValuesFormat(); DocValuesConsumer fieldsConsumer = docValuesFormat.FieldsConsumer(state); bool fieldsConsumerSuccess = false; try { // System.out.println("[" + Thread.currentThread().getName() + "] RLD.writeFieldUpdates: applying numeric updates; seg=" + info + " updates=" + numericFieldUpdates); foreach (KeyValuePair<string, NumericDocValuesFieldUpdates> e in dvUpdates.NumericDVUpdates) { string field = e.Key; NumericDocValuesFieldUpdates fieldUpdates = e.Value; FieldInfo fieldInfo = fieldInfos.FieldInfo(field); Debug.Assert(fieldInfo != null); fieldInfo.DocValuesGen = nextFieldInfosGen; // write the numeric updates to a new gen'd docvalues file fieldsConsumer.AddNumericField(fieldInfo, GetLongEnumerable(reader, field, fieldUpdates)); } // System.out.println("[" + Thread.currentThread().getName() + "] RAU.writeFieldUpdates: applying binary updates; seg=" + info + " updates=" + dvUpdates.binaryDVUpdates); foreach (KeyValuePair<string, BinaryDocValuesFieldUpdates> e in dvUpdates.BinaryDVUpdates) { string field = e.Key; BinaryDocValuesFieldUpdates dvFieldUpdates = e.Value; FieldInfo fieldInfo = fieldInfos.FieldInfo(field); Debug.Assert(fieldInfo != null); // System.out.println("[" + Thread.currentThread().getName() + "] RAU.writeFieldUpdates: applying binary updates; seg=" + info + " f=" + dvFieldUpdates + ", updates=" + dvFieldUpdates); fieldInfo.DocValuesGen = nextFieldInfosGen; // write the numeric updates to a new gen'd docvalues file fieldsConsumer.AddBinaryField(fieldInfo, GetBytesRefEnumerable(reader, field, dvFieldUpdates)); } codec.FieldInfosFormat().FieldInfosWriter.Write(trackingDir, Info.Info.Name, segmentSuffix, fieldInfos, IOContext.DEFAULT); fieldsConsumerSuccess = true; } finally { if (fieldsConsumerSuccess) { fieldsConsumer.Dispose(); } else { IOUtils.CloseWhileHandlingException(fieldsConsumer); } } } finally { if (reader != this.Reader) { // System.out.println("[" + Thread.currentThread().getName() + "] RLD.writeLiveDocs: closeReader " + reader); reader.Dispose(); } } success = true; } finally { if (!success) { // Advance only the nextWriteDocValuesGen so that a 2nd // attempt to write will write to a new file Info.AdvanceNextWriteFieldInfosGen(); // Delete any partially created file(s): foreach (string fileName in trackingDir.CreatedFiles) { try { dir.DeleteFile(fileName); } catch (Exception) { // Ignore so we throw only the first exc } } } } Info.AdvanceFieldInfosGen(); // copy all the updates to mergingUpdates, so they can later be applied to the merged segment if (IsMerging) { foreach (KeyValuePair<string, NumericDocValuesFieldUpdates> e in dvUpdates.NumericDVUpdates) { DocValuesFieldUpdates updates; if (!MergingDVUpdates.TryGetValue(e.Key, out updates)) { MergingDVUpdates[e.Key] = e.Value; } else { updates.Merge(e.Value); } } foreach (KeyValuePair<string, BinaryDocValuesFieldUpdates> e in dvUpdates.BinaryDVUpdates) { DocValuesFieldUpdates updates; if (!MergingDVUpdates.TryGetValue(e.Key, out updates)) { MergingDVUpdates[e.Key] = e.Value; } else { updates.Merge(e.Value); } } } // create a new map, keeping only the gens that are in use IDictionary<long, ISet<string>> genUpdatesFiles = Info.UpdatesFiles; IDictionary<long, ISet<string>> newGenUpdatesFiles = new Dictionary<long, ISet<string>>(); long fieldInfosGen = Info.FieldInfosGen; foreach (FieldInfo fi in fieldInfos) { long dvGen = fi.DocValuesGen; if (dvGen != -1 && !newGenUpdatesFiles.ContainsKey(dvGen)) { if (dvGen == fieldInfosGen) { newGenUpdatesFiles[fieldInfosGen] = trackingDir.CreatedFiles; } else { newGenUpdatesFiles[dvGen] = genUpdatesFiles[dvGen]; } } } Info.GenUpdatesFiles = newGenUpdatesFiles; // wrote new files, should checkpoint() Writer.Checkpoint(); // if there is a reader open, reopen it to reflect the updates if (Reader != null) { SegmentReader newReader = new SegmentReader(Info, Reader, LiveDocs_Renamed, Info.Info.DocCount - Info.DelCount - PendingDeleteCount_Renamed); bool reopened = false; try { Reader.DecRef(); Reader = newReader; reopened = true; } finally { if (!reopened) { newReader.DecRef(); } } } } } private IEnumerable<long?> GetLongEnumerable(SegmentReader reader, string field, NumericDocValuesFieldUpdates fieldUpdates) { int maxDoc = reader.MaxDoc; Bits DocsWithField = reader.GetDocsWithField(field); NumericDocValues currentValues = reader.GetNumericDocValues(field); NumericDocValuesFieldUpdates.Iterator iter = (NumericDocValuesFieldUpdates.Iterator)fieldUpdates.GetIterator(); int updateDoc = iter.NextDoc(); for (int curDoc = 0; curDoc < maxDoc; ++curDoc) { if (curDoc == updateDoc) //document has an updated value { long? value = (long?)iter.Value(); // either null or updated updateDoc = iter.NextDoc(); //prepare for next round yield return value; } else { // no update for this document if (currentValues != null && DocsWithField.Get(curDoc)) { // only read the current value if the document had a value before yield return currentValues.Get(curDoc); } else { yield return null; } } } } private IEnumerable<BytesRef> GetBytesRefEnumerable(SegmentReader reader, string field, BinaryDocValuesFieldUpdates fieldUpdates) { BinaryDocValues currentValues = reader.GetBinaryDocValues(field); Bits DocsWithField = reader.GetDocsWithField(field); int maxDoc = reader.MaxDoc; var iter = (BinaryDocValuesFieldUpdates.Iterator)fieldUpdates.GetIterator(); int updateDoc = iter.NextDoc(); for (int curDoc = 0; curDoc < maxDoc; ++curDoc) { if (curDoc == updateDoc) //document has an updated value { BytesRef value = (BytesRef)iter.Value(); // either null or updated updateDoc = iter.NextDoc(); //prepare for next round yield return value; } else { // no update for this document if (currentValues != null && DocsWithField.Get(curDoc)) { var scratch = new BytesRef(); // only read the current value if the document had a value before currentValues.Get(curDoc, scratch); yield return scratch; } else { yield return null; } } } } /* private class IterableAnonymousInnerClassHelper : IEnumerable<Number> { private readonly ReadersAndUpdates OuterInstance; private Lucene.Net.Index.SegmentReader Reader; private string Field; private Lucene.Net.Index.NumericDocValuesFieldUpdates FieldUpdates; public IterableAnonymousInnerClassHelper(ReadersAndUpdates outerInstance, Lucene.Net.Index.SegmentReader reader, string field, Lucene.Net.Index.NumericDocValuesFieldUpdates fieldUpdates) { this.OuterInstance = outerInstance; this.Reader = reader; this.Field = field; this.FieldUpdates = fieldUpdates; currentValues = reader.GetNumericDocValues(field); docsWithField = reader.GetDocsWithField(field); maxDoc = reader.MaxDoc; updatesIter = fieldUpdates.Iterator(); } internal readonly NumericDocValues currentValues; internal readonly Bits docsWithField; internal readonly int maxDoc; internal readonly NumericDocValuesFieldUpdates.Iterator updatesIter; public virtual IEnumerator<Number> GetEnumerator() { updatesIter.Reset(); return new IteratorAnonymousInnerClassHelper(this); } private class IteratorAnonymousInnerClassHelper : IEnumerator<Number> { private readonly IterableAnonymousInnerClassHelper OuterInstance; public IteratorAnonymousInnerClassHelper(IterableAnonymousInnerClassHelper outerInstance) { this.OuterInstance = outerInstance; curDoc = -1; updateDoc = updatesIter.NextDoc(); } internal int curDoc; internal int updateDoc; public virtual bool HasNext() { return curDoc < maxDoc - 1; } public virtual Number Next() { if (++curDoc >= maxDoc) { throw new NoSuchElementException("no more documents to return values for"); } if (curDoc == updateDoc) // this document has an updated value { long? value = updatesIter.value(); // either null (unset value) or updated value updateDoc = updatesIter.nextDoc(); // prepare for next round return value; } else { // no update for this document Debug.Assert(curDoc < updateDoc); if (currentValues != null && docsWithField.Get(curDoc)) { // only read the current value if the document had a value before return currentValues.Get(curDoc); } else { return null; } } } public virtual void Remove() { throw new System.NotSupportedException("this iterator does not support removing elements"); } } }*/ /* private class IterableAnonymousInnerClassHelper2 : IEnumerable<BytesRef> { private readonly ReadersAndUpdates OuterInstance; private Lucene.Net.Index.SegmentReader Reader; private string Field; private Lucene.Net.Index.BinaryDocValuesFieldUpdates DvFieldUpdates; public IterableAnonymousInnerClassHelper2(ReadersAndUpdates outerInstance, Lucene.Net.Index.SegmentReader reader, string field, Lucene.Net.Index.BinaryDocValuesFieldUpdates dvFieldUpdates) { this.OuterInstance = outerInstance; this.Reader = reader; this.Field = field; this.DvFieldUpdates = dvFieldUpdates; currentValues = reader.GetBinaryDocValues(field); docsWithField = reader.GetDocsWithField(field); maxDoc = reader.MaxDoc; updatesIter = dvFieldUpdates.Iterator(); } internal readonly BinaryDocValues currentValues; internal readonly Bits docsWithField; internal readonly int maxDoc; internal readonly BinaryDocValuesFieldUpdates.Iterator updatesIter; public virtual IEnumerator<BytesRef> GetEnumerator() { updatesIter.Reset(); return new IteratorAnonymousInnerClassHelper2(this); } private class IteratorAnonymousInnerClassHelper2 : IEnumerator<BytesRef> { private readonly IterableAnonymousInnerClassHelper2 OuterInstance; public IteratorAnonymousInnerClassHelper2(IterableAnonymousInnerClassHelper2 outerInstance) { this.OuterInstance = outerInstance; curDoc = -1; updateDoc = updatesIter.nextDoc(); scratch = new BytesRef(); } internal int curDoc; internal int updateDoc; internal BytesRef scratch; public virtual bool HasNext() { return curDoc < maxDoc - 1; } public virtual BytesRef Next() { if (++curDoc >= maxDoc) { throw new NoSuchElementException("no more documents to return values for"); } if (curDoc == updateDoc) // this document has an updated value { BytesRef value = updatesIter.value(); // either null (unset value) or updated value updateDoc = updatesIter.nextDoc(); // prepare for next round return value; } else { // no update for this document Debug.Assert(curDoc < updateDoc); if (currentValues != null && docsWithField.get(curDoc)) { // only read the current value if the document had a value before currentValues.get(curDoc, scratch); return scratch; } else { return null; } } } public virtual void Remove() { throw new System.NotSupportedException("this iterator does not support removing elements"); } } }*/ /// <summary> /// Returns a reader for merge. this method applies field updates if there are /// any and marks that this segment is currently merging. /// </summary> internal virtual SegmentReader GetReaderForMerge(IOContext context) { lock (this) { //Debug.Assert(Thread.holdsLock(Writer)); // must execute these two statements as atomic operation, otherwise we // could lose updates if e.g. another thread calls writeFieldUpdates in // between, or the updates are applied to the obtained reader, but then // re-applied in IW.commitMergedDeletes (unnecessary work and potential // bugs). IsMerging = true; return GetReader(context); } } /// <summary> /// Drops all merging updates. Called from IndexWriter after this segment /// finished merging (whether successfully or not). /// </summary> public virtual void DropMergingUpdates() { lock (this) { MergingDVUpdates.Clear(); IsMerging = false; } } /// <summary> /// Returns updates that came in while this segment was merging. </summary> public virtual IDictionary<string, DocValuesFieldUpdates> MergingFieldUpdates { get { lock (this) { return MergingDVUpdates; } } } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("ReadersAndLiveDocs(seg=").Append(Info); sb.Append(" pendingDeleteCount=").Append(PendingDeleteCount_Renamed); sb.Append(" liveDocsShared=").Append(LiveDocsShared); return sb.ToString(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Diagnostics; using System.Net; using Microsoft.Rest.Generator.ClientModel; using Microsoft.Rest.Generator.Logging; using Microsoft.Rest.Generator.Utilities; using Microsoft.Rest.Modeler.Swagger.Model; using Microsoft.Rest.Modeler.Swagger.Properties; using ParameterLocation = Microsoft.Rest.Modeler.Swagger.Model.ParameterLocation; using System.Globalization; namespace Microsoft.Rest.Modeler.Swagger { /// <summary> /// The builder for building swagger operations into client model methods. /// </summary> public class OperationBuilder { private IList<string> _effectiveProduces; private SwaggerModeler _swaggerModeler; private Operation _operation; public OperationBuilder(Operation operation, SwaggerModeler swaggerModeler) { if (operation == null) { throw new ArgumentNullException("operation"); } if (swaggerModeler == null) { throw new ArgumentNullException("swaggerModeler"); } this._operation = operation; this._swaggerModeler = swaggerModeler; this._effectiveProduces = operation.Produces ?? swaggerModeler.ServiceDefinition.Produces; } public Method BuildMethod(HttpMethod httpMethod, string url, string methodName, string methodGroup) { EnsureUniqueMethodName(methodName, methodGroup); var method = new Method { HttpMethod = httpMethod, Url = url, Name = methodName }; method.Documentation = _operation.Description; // Service parameters if (_operation.Parameters != null) { foreach (var swaggerParameter in DeduplicateParameters(_operation.Parameters)) { var parameter = ((ParameterBuilder) swaggerParameter.GetBuilder(_swaggerModeler)).Build(); method.Parameters.Add(parameter); StringBuilder parameterName = new StringBuilder(parameter.Name); parameterName = CollectionFormatBuilder.OnBuildMethodParameter(method, swaggerParameter, parameterName); if (swaggerParameter.In == ParameterLocation.Header) { method.RequestHeaders[swaggerParameter.Name] = string.Format(CultureInfo.InvariantCulture, "{{{0}}}", parameterName); } } } // Response format var typesList = new List<Stack<IType>>(); _operation.Responses.ForEach(response => { if (string.Equals(response.Key, "default", StringComparison.OrdinalIgnoreCase)) { TryBuildDefaultResponse(methodName, response.Value, method); } else { if ( !(TryBuildResponse(methodName, response.Key.ToHttpStatusCode(), response.Value, method, typesList) || TryBuildStreamResponse(response.Key.ToHttpStatusCode(), response.Value, method, typesList) || TryBuildEmptyResponse(methodName, response.Key.ToHttpStatusCode(), response.Value, method, typesList))) { throw new InvalidOperationException( string.Format(CultureInfo.InvariantCulture, Resources.UnsupportedMimeTypeForResponseBody, methodName, response.Key)); } } }); method.ReturnType = BuildMethodReturnType(typesList); if (method.Responses.Count == 0 && method.DefaultResponse != null) { method.ReturnType = method.DefaultResponse; } // Copy extensions _operation.Extensions.ForEach(extention => method.Extensions.Add(extention.Key, extention.Value)); return method; } private static IEnumerable<SwaggerParameter> DeduplicateParameters(IEnumerable<SwaggerParameter> parameters) { return parameters .Select(s => { // if parameter with the same name exists in Body and Path/Query then we need to give it a unique name if (s.In == ParameterLocation.Body) { string newName = s.Name; while (parameters.Any(t => t.In != ParameterLocation.Body && string.Equals(t.Name, newName, StringComparison.OrdinalIgnoreCase))) { newName += "Body"; } s.Name = newName; } // if parameter with same name exists in Query and Path, make Query one required if (s.In == ParameterLocation.Query && parameters.Any(t => t.In == ParameterLocation.Path && string.Equals(t.Name, s.Name, StringComparison.OrdinalIgnoreCase))) { s.IsRequired = true; } return s; }); } private static void BuildMethodReturnTypeStack(IType type, List<Stack<IType>> types) { var typeStack = new Stack<IType>(); typeStack.Push(type); types.Add(typeStack); } private IType BuildMethodReturnType(List<Stack<IType>> types) { IType baseType = PrimaryType.Object; // Return null if no response is specified if (types.Count == 0) { return null; } // Return first if only one return type if (types.Count == 1) { return types.First().Pop(); } // BuildParameter up type inheritance tree types.ForEach(typeStack => { IType type = typeStack.Peek(); while (!Equals(type, baseType)) { if (type is CompositeType && _swaggerModeler.ExtendedTypes.ContainsKey(type.Name)) { type = _swaggerModeler.GeneratedTypes[_swaggerModeler.ExtendedTypes[type.Name]]; } else { type = baseType; } typeStack.Push(type); } }); // Eliminate commonly shared base classes while (!types.First().IsNullOrEmpty()) { IType currentType = types.First().Peek(); foreach (var typeStack in types) { IType t = typeStack.Pop(); if (!Equals(t, currentType)) { return baseType; } } baseType = currentType; } return baseType; } private bool TryBuildStreamResponse(HttpStatusCode responseStatusCode, Response response, Method method, List<Stack<IType>> types) { bool handled = false; if (SwaggerOperationProducesNotEmpty()) { if (response.Schema != null) { IType serviceType = response.Schema.GetBuilder(_swaggerModeler) .BuildServiceType(response.Schema.Reference.StripDefinitionPath()); Debug.Assert(serviceType != null); BuildMethodReturnTypeStack(serviceType, types); var compositeType = serviceType as CompositeType; if (compositeType != null) { VerifyFirstPropertyIsByteArray(compositeType); } method.Responses[responseStatusCode] = serviceType; handled = true; } } return handled; } private void VerifyFirstPropertyIsByteArray(CompositeType serviceType) { var referenceKey = serviceType.Name; var responseType = _swaggerModeler.GeneratedTypes[referenceKey]; var property = responseType.Properties.FirstOrDefault(p => p.Type == PrimaryType.ByteArray); if (property == null) { throw new KeyNotFoundException( "Please specify a field with type of System.Byte[] to deserialize the file contents to"); } } private bool TryBuildResponse(string methodName, HttpStatusCode responseStatusCode, Response response, Method method, List<Stack<IType>> types) { bool handled = false; IType serviceType; if (SwaggerOperationProducesJson()) { if (TryBuildResponseBody(methodName, response, s => GenerateResponseObjectName(s, responseStatusCode), out serviceType)) { method.Responses[responseStatusCode] = serviceType; BuildMethodReturnTypeStack(serviceType, types); handled = true; } } return handled; } private bool TryBuildEmptyResponse(string methodName, HttpStatusCode responseStatusCode, Response response, Method method, List<Stack<IType>> types) { bool handled = false; if (response.Schema == null) { method.Responses[responseStatusCode] = null; handled = true; } else { if (_operation.Produces.IsNullOrEmpty()) { method.Responses[responseStatusCode] = PrimaryType.Object; BuildMethodReturnTypeStack(PrimaryType.Object, types); handled = true; } var unwrapedSchemaProperties = _swaggerModeler.Resolver.Unwrap(response.Schema).Properties; if (unwrapedSchemaProperties != null && unwrapedSchemaProperties.Any()) { Logger.LogWarning(Resources.NoProduceOperationWithBody, methodName); } } return handled; } private void TryBuildDefaultResponse(string methodName, Response response, Method method) { IType errorModel = null; if (SwaggerOperationProducesJson()) { if (TryBuildResponseBody(methodName, response, s => GenerateErrorModelName(s), out errorModel)) { method.DefaultResponse = errorModel; } } } private bool TryBuildResponseBody(string methodName, Response response, Func<string, string> typeNamer, out IType responseType) { bool handled = false; responseType = null; if (SwaggerOperationProducesJson()) { if (response.Schema != null) { string referenceKey; if (response.Schema.Reference != null) { referenceKey = response.Schema.Reference.StripDefinitionPath(); response.Schema.Reference = referenceKey; } else { referenceKey = typeNamer(methodName); } responseType = response.Schema.GetBuilder(_swaggerModeler).BuildServiceType(referenceKey); handled = true; } } return handled; } private bool SwaggerOperationProducesJson() { return _effectiveProduces != null && _effectiveProduces.Contains("application/json", StringComparer.OrdinalIgnoreCase); } private bool SwaggerOperationProducesNotEmpty() { return _effectiveProduces != null && _effectiveProduces.Any(); } private void EnsureUniqueMethodName(string methodName, string methodGroup) { string serviceOperationPrefix = ""; if (methodGroup != null) { serviceOperationPrefix = methodGroup + "_"; } if (_swaggerModeler.ServiceClient.Methods.Any(m => m.Group == methodGroup && m.Name == methodName)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.DuplicateOperationIdException, serviceOperationPrefix + methodName)); } } private static string GenerateResponseObjectName(string methodName, HttpStatusCode responseStatusCode) { return string.Format(CultureInfo.InvariantCulture, "{0}{1}Response", methodName, responseStatusCode); } private static string GenerateErrorModelName(string methodName) { return string.Format(CultureInfo.InvariantCulture, "{0}ErrorModel", methodName); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------ // </copyright> //------------------------------------------------------------------------------ namespace System.Xml.Serialization { using System; using System.IO; using System.Collections; using System.Reflection; using System.Reflection.Emit; using System.Xml.Schema; using System.ComponentModel; using System.Diagnostics; using System.CodeDom.Compiler; using System.Globalization; using System.Text; using System.Threading; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Xml.Extensions; using Hashtable = System.Collections.Generic.Dictionary<object, object>; using DictionaryEntry = System.Collections.Generic.KeyValuePair<object, object>; using XmlSchema = System.ServiceModel.Dispatcher.XmlSchemaConstants; /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter"]/*' /> ///<internalonly/> public abstract class XmlSerializationWriter : XmlSerializationGeneratedCode { private XmlWriter _w; private XmlSerializerNamespaces _namespaces; private int _tempNamespacePrefix; private InternalHashtable _usedPrefixes; private InternalHashtable _objectsInUse; private string _aliasBase = "q"; private bool _escapeName = true; // this method must be called before any generated serialization methods are called internal void Init(XmlWriter w, XmlSerializerNamespaces namespaces, string encodingStyle, string idBase) { _w = w; _namespaces = namespaces; } // this method must be called before any generated serialization methods are called internal void Init(XmlWriter w, XmlSerializerNamespaces namespaces, string encodingStyle, string idBase, TempAssembly tempAssembly) { Init(w, namespaces, encodingStyle, idBase); Init(tempAssembly); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.EscapeName"]/*' /> protected bool EscapeName { get { return _escapeName; } set { _escapeName = value; } } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.Writer"]/*' /> protected XmlWriter Writer { get { return _w; } set { _w = value; } } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.Namespaces"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected IList XmlNamespaces { get { return _namespaces == null ? null : _namespaces.NamespaceList; } set { if (value == null) { _namespaces = null; } else { XmlQualifiedName[] qnames = (XmlQualifiedName[])ArrayList.ToArray(value, typeof(XmlQualifiedName)); _namespaces = new XmlSerializerNamespaces(qnames); } } } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromByteArrayBase64"]/*' /> protected static byte[] FromByteArrayBase64(byte[] value) { // Unlike other "From" functions that one is just a place holder for automatic code generation. // The reason is performance and memory consumption for (potentially) big 64base-encoded chunks // And it is assumed that the caller generates the code that will distinguish between byte[] and string return types // return value; } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromByteArrayHex"]/*' /> protected static string FromByteArrayHex(byte[] value) { return XmlCustomFormatter.FromByteArrayHex(value); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromDateTime"]/*' /> protected static string FromDateTime(DateTime value) { return XmlCustomFormatter.FromDateTime(value); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromDate"]/*' /> protected static string FromDate(DateTime value) { return XmlCustomFormatter.FromDate(value); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromTime"]/*' /> protected static string FromTime(DateTime value) { return XmlCustomFormatter.FromTime(value); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromChar"]/*' /> protected static string FromChar(char value) { return XmlCustomFormatter.FromChar(value); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromEnum"]/*' /> protected static string FromEnum(long value, string[] values, long[] ids) { return XmlCustomFormatter.FromEnum(value, values, ids, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromEnum1"]/*' /> protected static string FromEnum(long value, string[] values, long[] ids, string typeName) { return XmlCustomFormatter.FromEnum(value, values, ids, typeName); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromXmlName"]/*' /> protected static string FromXmlName(string name) { return XmlCustomFormatter.FromXmlName(name); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromXmlNCName"]/*' /> protected static string FromXmlNCName(string ncName) { return XmlCustomFormatter.FromXmlNCName(ncName); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromXmlNmToken"]/*' /> protected static string FromXmlNmToken(string nmToken) { return XmlCustomFormatter.FromXmlNmToken(nmToken); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromXmlNmTokens"]/*' /> protected static string FromXmlNmTokens(string nmTokens) { return XmlCustomFormatter.FromXmlNmTokens(nmTokens); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteXsiType"]/*' /> protected void WriteXsiType(string name, string ns) { WriteAttribute("type", XmlSchema.InstanceNamespace, GetQualifiedName(name, ns)); } private XmlQualifiedName GetPrimitiveTypeName(Type type) { return GetPrimitiveTypeName(type, true); } private XmlQualifiedName GetPrimitiveTypeName(Type type, bool throwIfUnknown) { XmlQualifiedName qname = GetPrimitiveTypeNameInternal(type); if (throwIfUnknown && qname == null) throw CreateUnknownTypeException(type); return qname; } internal static XmlQualifiedName GetPrimitiveTypeNameInternal(Type type) { string typeName; string typeNs = XmlSchema.Namespace; switch (type.GetTypeCode()) { case TypeCode.String: typeName = "string"; break; case TypeCode.Int32: typeName = "int"; break; case TypeCode.Boolean: typeName = "boolean"; break; case TypeCode.Int16: typeName = "short"; break; case TypeCode.Int64: typeName = "long"; break; case TypeCode.Single: typeName = "float"; break; case TypeCode.Double: typeName = "double"; break; case TypeCode.Decimal: typeName = "decimal"; break; case TypeCode.DateTime: typeName = "dateTime"; break; case TypeCode.Byte: typeName = "unsignedByte"; break; case TypeCode.SByte: typeName = "byte"; break; case TypeCode.UInt16: typeName = "unsignedShort"; break; case TypeCode.UInt32: typeName = "unsignedInt"; break; case TypeCode.UInt64: typeName = "unsignedLong"; break; case TypeCode.Char: typeName = "char"; typeNs = UrtTypes.Namespace; break; default: if (type == typeof(XmlQualifiedName)) typeName = "QName"; else if (type == typeof(byte[])) typeName = "base64Binary"; else if (type == typeof(Guid)) { typeName = "guid"; typeNs = UrtTypes.Namespace; } else if (type == typeof (TimeSpan)) { typeName = "TimeSpan"; typeNs = UrtTypes.Namespace; } else if (type == typeof (XmlNode[])) { typeName = Soap.UrType; } else return null; break; } return new XmlQualifiedName(typeName, typeNs); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteTypedPrimitive"]/*' /> protected void WriteTypedPrimitive(string name, string ns, object o, bool xsiType) { string value = null; string type; string typeNs = XmlSchema.Namespace; bool writeRaw = true; bool writeDirect = false; Type t = o.GetType(); bool wroteStartElement = false; switch (t.GetTypeCode()) { case TypeCode.String: value = (string)o; type = "string"; writeRaw = false; break; case TypeCode.Int32: value = XmlConvert.ToString((int)o); type = "int"; break; case TypeCode.Boolean: value = XmlConvert.ToString((bool)o); type = "boolean"; break; case TypeCode.Int16: value = XmlConvert.ToString((short)o); type = "short"; break; case TypeCode.Int64: value = XmlConvert.ToString((long)o); type = "long"; break; case TypeCode.Single: value = XmlConvert.ToString((float)o); type = "float"; break; case TypeCode.Double: value = XmlConvert.ToString((double)o); type = "double"; break; case TypeCode.Decimal: value = XmlConvert.ToString((decimal)o); type = "decimal"; break; case TypeCode.DateTime: value = FromDateTime((DateTime)o); type = "dateTime"; break; case TypeCode.Char: value = FromChar((char)o); type = "char"; typeNs = UrtTypes.Namespace; break; case TypeCode.Byte: value = XmlConvert.ToString((byte)o); type = "unsignedByte"; break; case TypeCode.SByte: value = XmlConvert.ToString((sbyte)o); type = "byte"; break; case TypeCode.UInt16: value = XmlConvert.ToString((UInt16)o); type = "unsignedShort"; break; case TypeCode.UInt32: value = XmlConvert.ToString((UInt32)o); type = "unsignedInt"; break; case TypeCode.UInt64: value = XmlConvert.ToString((UInt64)o); type = "unsignedLong"; break; default: if (t == typeof(XmlQualifiedName)) { type = "QName"; // need to write start element ahead of time to establish context // for ns definitions by FromXmlQualifiedName wroteStartElement = true; if (name == null) _w.WriteStartElement(type, typeNs); else _w.WriteStartElement(name, ns); value = FromXmlQualifiedName((XmlQualifiedName)o, false); } else if (t == typeof(byte[])) { value = String.Empty; writeDirect = true; type = "base64Binary"; } else if (t == typeof(Guid)) { value = XmlConvert.ToString((Guid)o); type = "guid"; typeNs = UrtTypes.Namespace; } else if (t == typeof(TimeSpan)) { value = XmlConvert.ToString((TimeSpan)o); type = "TimeSpan"; typeNs = UrtTypes.Namespace; } else if (typeof(XmlNode[]).IsAssignableFrom(t)) { if (name == null) _w.WriteStartElement(Soap.UrType, XmlSchema.Namespace); else _w.WriteStartElement(name, ns); XmlNode[] xmlNodes = (XmlNode[])o; for (int i = 0; i < xmlNodes.Length; i++) { if (xmlNodes[i] == null) continue; xmlNodes[i].WriteTo(_w); } _w.WriteEndElement(); return; } else throw CreateUnknownTypeException(t); break; } if (!wroteStartElement) { if (name == null) _w.WriteStartElement(type, typeNs); else _w.WriteStartElement(name, ns); } if (xsiType) WriteXsiType(type, typeNs); if (value == null) { _w.WriteAttributeString("nil", XmlSchema.InstanceNamespace, "true"); } else if (writeDirect) { // only one type currently writes directly to XML stream XmlCustomFormatter.WriteArrayBase64(_w, (byte[])o, 0, ((byte[])o).Length); } else if (writeRaw) { _w.WriteRaw(value); } else _w.WriteString(value); _w.WriteEndElement(); } private string GetQualifiedName(string name, string ns) { if (ns == null || ns.Length == 0) return name; string prefix = _w.LookupPrefix(ns); if (prefix == null) { if (ns == XmlReservedNs.NsXml) { prefix = "xml"; } else { prefix = NextPrefix(); WriteAttribute("xmlns", prefix, null, ns); } } else if (prefix.Length == 0) { return name; } return prefix + ":" + name; } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromXmlQualifiedName"]/*' /> protected string FromXmlQualifiedName(XmlQualifiedName xmlQualifiedName) { return FromXmlQualifiedName(xmlQualifiedName, true); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.FromXmlQualifiedName"]/*' /> protected string FromXmlQualifiedName(XmlQualifiedName xmlQualifiedName, bool ignoreEmpty) { if (xmlQualifiedName == null) return null; if (xmlQualifiedName.IsEmpty && ignoreEmpty) return null; return GetQualifiedName(EscapeName ? XmlConvert.EncodeLocalName(xmlQualifiedName.Name) : xmlQualifiedName.Name, xmlQualifiedName.Namespace); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteStartElement"]/*' /> protected void WriteStartElement(string name) { WriteStartElement(name, null, null, false, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteStartElement1"]/*' /> protected void WriteStartElement(string name, string ns) { WriteStartElement(name, ns, null, false, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteStartElement4"]/*' /> protected void WriteStartElement(string name, string ns, bool writePrefixed) { WriteStartElement(name, ns, null, writePrefixed, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteStartElement2"]/*' /> protected void WriteStartElement(string name, string ns, object o) { WriteStartElement(name, ns, o, false, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteStartElement3"]/*' /> protected void WriteStartElement(string name, string ns, object o, bool writePrefixed) { WriteStartElement(name, ns, o, writePrefixed, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteStartElement5"]/*' /> protected void WriteStartElement(string name, string ns, object o, bool writePrefixed, XmlSerializerNamespaces xmlns) { if (o != null && _objectsInUse != null) { if (_objectsInUse.ContainsKey(o)) throw new InvalidOperationException(SR.Format(SR.XmlCircularReference, o.GetType().FullName)); _objectsInUse.Add(o, o); } string prefix = null; bool needEmptyDefaultNamespace = false; if (_namespaces != null) { foreach (string alias in _namespaces.Namespaces.Keys) { string aliasNs = (string)_namespaces.Namespaces[alias]; if (alias.Length > 0 && aliasNs == ns) prefix = alias; if (alias.Length == 0) { if (aliasNs == null || aliasNs.Length == 0) needEmptyDefaultNamespace = true; if (ns != aliasNs) writePrefixed = true; } } _usedPrefixes = ListUsedPrefixes(_namespaces.Namespaces, _aliasBase); } if (writePrefixed && prefix == null && ns != null && ns.Length > 0) { prefix = _w.LookupPrefix(ns); if (prefix == null || prefix.Length == 0) { prefix = NextPrefix(); } } if (prefix == null && xmlns != null) { prefix = xmlns.LookupPrefix(ns); } if (needEmptyDefaultNamespace && prefix == null && ns != null && ns.Length != 0) prefix = NextPrefix(); _w.WriteStartElement(prefix, name, ns); if (_namespaces != null) { foreach (string alias in _namespaces.Namespaces.Keys) { string aliasNs = (string)_namespaces.Namespaces[alias]; if (alias.Length == 0 && (aliasNs == null || aliasNs.Length == 0)) continue; if (aliasNs == null || aliasNs.Length == 0) { if (alias.Length > 0) throw new InvalidOperationException(SR.Format(SR.XmlInvalidXmlns, alias)); WriteAttribute("xmlns", alias, null, aliasNs); } else { if (_w.LookupPrefix(aliasNs) == null) { // write the default namespace declaration only if we have not written it already, over wise we just ignore one provided by the user if (prefix == null && alias.Length == 0) break; WriteAttribute("xmlns", alias, null, aliasNs); } } } } WriteNamespaceDeclarations(xmlns); } private InternalHashtable ListUsedPrefixes(InternalHashtable nsList, string prefix) { InternalHashtable qnIndexes = new InternalHashtable(); int prefixLength = prefix.Length; const string MaxInt32 = "2147483647"; foreach (string alias in _namespaces.Namespaces.Keys) { string name; if (alias.Length > prefixLength) { name = alias; if (name.Length > prefixLength && name.Length <= prefixLength + MaxInt32.Length && name.StartsWith(prefix, StringComparison.Ordinal)) { bool numeric = true; for (int j = prefixLength; j < name.Length; j++) { if (!Char.IsDigit(name, j)) { numeric = false; break; } } if (numeric) { Int64 index = Int64.Parse(name.Substring(prefixLength), NumberStyles.Integer, CultureInfo.InvariantCulture); if (index <= Int32.MaxValue) { Int32 newIndex = (Int32)index; if (!qnIndexes.ContainsKey(newIndex)) { qnIndexes.Add(newIndex, newIndex); } } } } } } if (qnIndexes.Count > 0) { return qnIndexes; } return null; } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullTagEncoded"]/*' /> protected void WriteNullTagEncoded(string name) { WriteNullTagEncoded(name, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullTagEncoded1"]/*' /> protected void WriteNullTagEncoded(string name, string ns) { if (name == null || name.Length == 0) return; WriteStartElement(name, ns, null, true); _w.WriteAttributeString("nil", XmlSchema.InstanceNamespace, "true"); _w.WriteEndElement(); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullTagLiteral"]/*' /> protected void WriteNullTagLiteral(string name) { WriteNullTagLiteral(name, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullTag1"]/*' /> protected void WriteNullTagLiteral(string name, string ns) { if (name == null || name.Length == 0) return; WriteStartElement(name, ns, null, false); _w.WriteAttributeString("nil", XmlSchema.InstanceNamespace, "true"); _w.WriteEndElement(); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteEmptyTag"]/*' /> protected void WriteEmptyTag(string name) { WriteEmptyTag(name, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteEmptyTag1"]/*' /> protected void WriteEmptyTag(string name, string ns) { if (name == null || name.Length == 0) return; WriteStartElement(name, ns, null, false); _w.WriteEndElement(); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteEndElement"]/*' /> protected void WriteEndElement() { _w.WriteEndElement(); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteEndElement1"]/*' /> protected void WriteEndElement(object o) { _w.WriteEndElement(); if (o != null && _objectsInUse != null) { #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (!_objectsInUse.ContainsKey(o)) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "missing stack object of type " + o.GetType().FullName)); #endif _objectsInUse.Remove(o); } } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteSerializable"]/*' /> protected void WriteSerializable(IXmlSerializable serializable, string name, string ns, bool isNullable) { WriteSerializable(serializable, name, ns, isNullable, true); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteSerializable1"]/*' /> protected void WriteSerializable(IXmlSerializable serializable, string name, string ns, bool isNullable, bool wrapped) { if (serializable == null) { if (isNullable) WriteNullTagLiteral(name, ns); return; } if (wrapped) { _w.WriteStartElement(name, ns); } serializable.WriteXml(_w); if (wrapped) { _w.WriteEndElement(); } } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullableStringEncoded"]/*' /> protected void WriteNullableStringEncoded(string name, string ns, string value, XmlQualifiedName xsiType) { if (value == null) WriteNullTagEncoded(name, ns); else WriteElementString(name, ns, value, xsiType); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullableStringLiteral"]/*' /> protected void WriteNullableStringLiteral(string name, string ns, string value) { if (value == null) WriteNullTagLiteral(name, ns); else WriteElementString(name, ns, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullableStringEncodedRaw"]/*' /> protected void WriteNullableStringEncodedRaw(string name, string ns, string value, XmlQualifiedName xsiType) { if (value == null) WriteNullTagEncoded(name, ns); else WriteElementStringRaw(name, ns, value, xsiType); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullableStringEncodedRaw1"]/*' /> protected void WriteNullableStringEncodedRaw(string name, string ns, byte[] value, XmlQualifiedName xsiType) { if (value == null) WriteNullTagEncoded(name, ns); else WriteElementStringRaw(name, ns, value, xsiType); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullableStringLiteralRaw"]/*' /> protected void WriteNullableStringLiteralRaw(string name, string ns, string value) { if (value == null) WriteNullTagLiteral(name, ns); else WriteElementStringRaw(name, ns, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullableStringLiteralRaw1"]/*' /> protected void WriteNullableStringLiteralRaw(string name, string ns, byte[] value) { if (value == null) WriteNullTagLiteral(name, ns); else WriteElementStringRaw(name, ns, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullableQualifiedNameEncoded"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected void WriteNullableQualifiedNameEncoded(string name, string ns, XmlQualifiedName value, XmlQualifiedName xsiType) { if (value == null) WriteNullTagEncoded(name, ns); else WriteElementQualifiedName(name, ns, value, xsiType); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNullableQualifiedNameLiteral"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected void WriteNullableQualifiedNameLiteral(string name, string ns, XmlQualifiedName value) { if (value == null) WriteNullTagLiteral(name, ns); else WriteElementQualifiedName(name, ns, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementLiteral"]/*' /> protected void WriteElementLiteral(XmlNode node, string name, string ns, bool isNullable, bool any) { if (node == null) { if (isNullable) WriteNullTagLiteral(name, ns); return; } WriteElement(node, name, ns, isNullable, any); } private void WriteElement(XmlNode node, string name, string ns, bool isNullable, bool any) { if (typeof(XmlAttribute).IsAssignableFrom(node.GetType())) throw new InvalidOperationException(SR.XmlNoAttributeHere); if (node is XmlDocument) { node = ((XmlDocument)node).DocumentElement; if (node == null) { if (isNullable) WriteNullTagEncoded(name, ns); return; } } if (any) { if (node is XmlElement && name != null && name.Length > 0) { // need to check against schema if (node.LocalName != name || node.NamespaceURI != ns) throw new InvalidOperationException(SR.Format(SR.XmlElementNameMismatch, node.LocalName, node.NamespaceURI, name, ns)); } } else _w.WriteStartElement(name, ns); node.WriteTo(_w); if (!any) _w.WriteEndElement(); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.CreateUnknownTypeException"]/*' /> protected Exception CreateUnknownTypeException(object o) { return CreateUnknownTypeException(o.GetType()); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.CreateUnknownTypeException1"]/*' /> protected Exception CreateUnknownTypeException(Type type) { if (typeof(IXmlSerializable).IsAssignableFrom(type)) return new InvalidOperationException(SR.Format(SR.XmlInvalidSerializable, type.FullName)); TypeDesc typeDesc = new TypeScope().GetTypeDesc(type); if (!typeDesc.IsStructLike) return new InvalidOperationException(SR.Format(SR.XmlInvalidUseOfType, type.FullName)); return new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, type.FullName)); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.CreateMismatchChoiceException"]/*' /> protected Exception CreateMismatchChoiceException(string value, string elementName, string enumValue) { // Value of {0} mismatches the type of {1}, you need to set it to {2}. return new InvalidOperationException(SR.Format(SR.XmlChoiceMismatchChoiceException, elementName, value, enumValue)); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.CreateUnknownAnyElementException"]/*' /> protected Exception CreateUnknownAnyElementException(string name, string ns) { return new InvalidOperationException(SR.Format(SR.XmlUnknownAnyElement, name, ns)); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.CreateInvalidChoiceIdentifierValueException"]/*' /> protected Exception CreateInvalidChoiceIdentifierValueException(string type, string identifier) { return new InvalidOperationException(SR.Format(SR.XmlInvalidChoiceIdentifierValue, type, identifier)); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.CreateChoiceIdentifierValueException"]/*' /> protected Exception CreateChoiceIdentifierValueException(string value, string identifier, string name, string ns) { // XmlChoiceIdentifierMismatch=Value '{0}' of the choice identifier '{1}' does not match element '{2}' from namespace '{3}'. return new InvalidOperationException(SR.Format(SR.XmlChoiceIdentifierMismatch, value, identifier, name, ns)); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.CreateInvalidEnumValueException"]/*' /> protected Exception CreateInvalidEnumValueException(object value, string typeName) { return new InvalidOperationException(SR.Format(SR.XmlUnknownConstant, value, typeName)); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.CreateInvalidAnyTypeException"]/*' /> protected Exception CreateInvalidAnyTypeException(object o) { return CreateInvalidAnyTypeException(o.GetType()); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.CreateInvalidAnyTypeException1"]/*' /> protected Exception CreateInvalidAnyTypeException(Type type) { return new InvalidOperationException(SR.Format(SR.XmlIllegalAnyElement, type.FullName)); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteXmlAttribute1"]/*' /> protected void WriteXmlAttribute(XmlNode node) { WriteXmlAttribute(node, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteXmlAttribute2"]/*' /> protected void WriteXmlAttribute(XmlNode node, object container) { XmlAttribute attr = node as XmlAttribute; if (attr == null) throw new InvalidOperationException(SR.XmlNeedAttributeHere); if (attr.Value != null) { if (attr.NamespaceURI == Wsdl.Namespace && attr.LocalName == Wsdl.ArrayType) { string dims; XmlQualifiedName qname = TypeScope.ParseWsdlArrayType(attr.Value, out dims, (container is XmlSchemaObject) ? (XmlSchemaObject)container : null); string value = FromXmlQualifiedName(qname, true) + dims; //<xsd:attribute xmlns:q3="s0" wsdl:arrayType="q3:FoosBase[]" xmlns:q4="http://schemas.xmlsoap.org/soap/encoding/" ref="q4:arrayType" /> WriteAttribute(Wsdl.ArrayType, Wsdl.Namespace, value); } else { WriteAttribute(attr.Name, attr.NamespaceURI, attr.Value); } } } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteAttribute"]/*' /> protected void WriteAttribute(string localName, string ns, string value) { if (value == null) return; if (localName == "xmlns" || localName.StartsWith("xmlns:", StringComparison.Ordinal)) { ; } else { int colon = localName.IndexOf(':'); if (colon < 0) { if (ns == XmlReservedNs.NsXml) { string prefix = _w.LookupPrefix(ns); if (prefix == null || prefix.Length == 0) prefix = "xml"; _w.WriteAttributeString(prefix, localName, ns, value); } else { _w.WriteAttributeString(localName, ns, value); } } else { string prefix = localName.Substring(0, colon); _w.WriteAttributeString(prefix, localName.Substring(colon + 1), ns, value); } } } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteAttribute0"]/*' /> protected void WriteAttribute(string localName, string ns, byte[] value) { if (value == null) return; if (localName == "xmlns" || localName.StartsWith("xmlns:", StringComparison.Ordinal)) { ; } else { int colon = localName.IndexOf(':'); if (colon < 0) { if (ns == XmlReservedNs.NsXml) { string prefix = _w.LookupPrefix(ns); if (prefix == null || prefix.Length == 0) prefix = "xml"; _w.WriteStartAttribute("xml", localName, ns); } else { _w.WriteStartAttribute(null, localName, ns); } } else { string prefix = _w.LookupPrefix(ns); _w.WriteStartAttribute(prefix, localName.Substring(colon + 1), ns); } XmlCustomFormatter.WriteArrayBase64(_w, value, 0, value.Length); _w.WriteEndAttribute(); } } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteAttribute1"]/*' /> protected void WriteAttribute(string localName, string value) { if (value == null) return; _w.WriteAttributeString(localName, null, value); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteAttribute01"]/*' /> protected void WriteAttribute(string localName, byte[] value) { if (value == null) return; _w.WriteStartAttribute(null, localName, (string)null); XmlCustomFormatter.WriteArrayBase64(_w, value, 0, value.Length); _w.WriteEndAttribute(); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteAttribute2"]/*' /> protected void WriteAttribute(string prefix, string localName, string ns, string value) { if (value == null) return; _w.WriteAttributeString(prefix, localName, null, value); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteValue"]/*' /> protected void WriteValue(string value) { if (value == null) return; _w.WriteString(value); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteValue01"]/*' /> protected void WriteValue(byte[] value) { if (value == null) return; XmlCustomFormatter.WriteArrayBase64(_w, value, 0, value.Length); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteStartDocument"]/*' /> protected void WriteStartDocument() { if (_w.WriteState == WriteState.Start) { _w.WriteStartDocument(); } } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementString"]/*' /> protected void WriteElementString(String localName, String value) { WriteElementString(localName, null, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementString1"]/*' /> protected void WriteElementString(String localName, String ns, String value) { WriteElementString(localName, ns, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementString2"]/*' /> protected void WriteElementString(String localName, String value, XmlQualifiedName xsiType) { WriteElementString(localName, null, value, xsiType); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementString3"]/*' /> protected void WriteElementString(String localName, String ns, String value, XmlQualifiedName xsiType) { if (value == null) return; if (xsiType == null) _w.WriteElementString(localName, ns, value); else { _w.WriteStartElement(localName, ns); WriteXsiType(xsiType.Name, xsiType.Namespace); _w.WriteString(value); _w.WriteEndElement(); } } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementStringRaw"]/*' /> protected void WriteElementStringRaw(String localName, String value) { WriteElementStringRaw(localName, null, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementStringRaw0"]/*' /> protected void WriteElementStringRaw(String localName, byte[] value) { WriteElementStringRaw(localName, null, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementStringRaw1"]/*' /> protected void WriteElementStringRaw(String localName, String ns, String value) { WriteElementStringRaw(localName, ns, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementStringRaw01"]/*' /> protected void WriteElementStringRaw(String localName, String ns, byte[] value) { WriteElementStringRaw(localName, ns, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementStringRaw2"]/*' /> protected void WriteElementStringRaw(String localName, String value, XmlQualifiedName xsiType) { WriteElementStringRaw(localName, null, value, xsiType); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementStringRaw02"]/*' /> protected void WriteElementStringRaw(String localName, byte[] value, XmlQualifiedName xsiType) { WriteElementStringRaw(localName, null, value, xsiType); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementStringRaw3"]/*' /> protected void WriteElementStringRaw(String localName, String ns, String value, XmlQualifiedName xsiType) { if (value == null) return; _w.WriteStartElement(localName, ns); if (xsiType != null) WriteXsiType(xsiType.Name, xsiType.Namespace); _w.WriteRaw(value); _w.WriteEndElement(); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementStringRaw03"]/*' /> protected void WriteElementStringRaw(String localName, String ns, byte[] value, XmlQualifiedName xsiType) { if (value == null) return; _w.WriteStartElement(localName, ns); if (xsiType != null) WriteXsiType(xsiType.Name, xsiType.Namespace); XmlCustomFormatter.WriteArrayBase64(_w, value, 0, value.Length); _w.WriteEndElement(); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementQualifiedName"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected void WriteElementQualifiedName(String localName, XmlQualifiedName value) { WriteElementQualifiedName(localName, null, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementQualifiedName1"]/*' /> protected void WriteElementQualifiedName(string localName, XmlQualifiedName value, XmlQualifiedName xsiType) { WriteElementQualifiedName(localName, null, value, xsiType); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementQualifiedName2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected void WriteElementQualifiedName(String localName, String ns, XmlQualifiedName value) { WriteElementQualifiedName(localName, ns, value, null); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteElementQualifiedName3"]/*' /> protected void WriteElementQualifiedName(string localName, string ns, XmlQualifiedName value, XmlQualifiedName xsiType) { if (value == null) return; if (value.Namespace == null || value.Namespace.Length == 0) { WriteStartElement(localName, ns, null, true); WriteAttribute("xmlns", ""); } else _w.WriteStartElement(localName, ns); if (xsiType != null) WriteXsiType(xsiType.Name, xsiType.Namespace); _w.WriteString(FromXmlQualifiedName(value, false)); _w.WriteEndElement(); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.InitCallbacks"]/*' /> protected abstract void InitCallbacks(); /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.TopLevelElement"]/*' /> protected void TopLevelElement() { _objectsInUse = new InternalHashtable(); } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriter.WriteNamespaceDeclarations"]/*' /> ///<internalonly/> protected void WriteNamespaceDeclarations(XmlSerializerNamespaces xmlns) { if (xmlns != null) { foreach (DictionaryEntry entry in xmlns.Namespaces) { string prefix = (string)entry.Key; string ns = (string)entry.Value; if (_namespaces != null) { string oldNs = _namespaces.Namespaces[prefix] as string; if (oldNs != null && oldNs != ns) { throw new InvalidOperationException(SR.Format(SR.XmlDuplicateNs, prefix, ns)); } } string oldPrefix = (ns == null || ns.Length == 0) ? null : Writer.LookupPrefix(ns); if (oldPrefix == null || oldPrefix != prefix) { WriteAttribute("xmlns", prefix, null, ns); } } } _namespaces = null; } private string NextPrefix() { if (_usedPrefixes == null) { return _aliasBase + (++_tempNamespacePrefix); } while (_usedPrefixes.ContainsKey(++_tempNamespacePrefix)) {; } return _aliasBase + _tempNamespacePrefix; } } /// <include file='doc\XmlSerializationWriter.uex' path='docs/doc[@for="XmlSerializationWriteCallback"]/*' /> ///<internalonly/> public delegate void XmlSerializationWriteCallback(object o); }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Compute { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// VirtualMachineImagesOperations operations. /// </summary> internal partial class VirtualMachineImagesOperations : IServiceOperations<ComputeManagementClient>, IVirtualMachineImagesOperations { /// <summary> /// Initializes a new instance of the VirtualMachineImagesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal VirtualMachineImagesOperations(ComputeManagementClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the ComputeManagementClient /// </summary> public ComputeManagementClient Client { get; private set; } /// <summary> /// Gets a virtual machine image. /// </summary> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='offer'> /// </param> /// <param name='skus'> /// </param> /// <param name='version'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<VirtualMachineImage>> GetWithHttpMessagesAsync(string location, string publisherName, string offer, string skus, string version, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (publisherName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "publisherName"); } if (offer == null) { throw new ValidationException(ValidationRules.CannotBeNull, "offer"); } if (skus == null) { throw new ValidationException(ValidationRules.CannotBeNull, "skus"); } if (version == null) { throw new ValidationException(ValidationRules.CannotBeNull, "version"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("publisherName", publisherName); tracingParameters.Add("offer", offer); tracingParameters.Add("skus", skus); tracingParameters.Add("version", version); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus/{skus}/versions/{version}").ToString(); _url = _url.Replace("{location}", Uri.EscapeDataString(location)); _url = _url.Replace("{publisherName}", Uri.EscapeDataString(publisherName)); _url = _url.Replace("{offer}", Uri.EscapeDataString(offer)); _url = _url.Replace("{skus}", Uri.EscapeDataString(skus)); _url = _url.Replace("{version}", Uri.EscapeDataString(version)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200) { string _responseContent = null; var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, null); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new AzureOperationResponse<VirtualMachineImage>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject<VirtualMachineImage>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a list of virtual machine images. /// </summary> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='offer'> /// </param> /// <param name='skus'> /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IList<VirtualMachineImageResource>>> ListWithHttpMessagesAsync(string location, string publisherName, string offer, string skus, ODataQuery<VirtualMachineImageResource> odataQuery = default(ODataQuery<VirtualMachineImageResource>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (publisherName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "publisherName"); } if (offer == null) { throw new ValidationException(ValidationRules.CannotBeNull, "offer"); } if (skus == null) { throw new ValidationException(ValidationRules.CannotBeNull, "skus"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("location", location); tracingParameters.Add("publisherName", publisherName); tracingParameters.Add("offer", offer); tracingParameters.Add("skus", skus); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus/{skus}/versions").ToString(); _url = _url.Replace("{location}", Uri.EscapeDataString(location)); _url = _url.Replace("{publisherName}", Uri.EscapeDataString(publisherName)); _url = _url.Replace("{offer}", Uri.EscapeDataString(offer)); _url = _url.Replace("{skus}", Uri.EscapeDataString(skus)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200) { string _responseContent = null; var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, null); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new AzureOperationResponse<IList<VirtualMachineImageResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject<IList<VirtualMachineImageResource>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a list of virtual machine image offers. /// </summary> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IList<VirtualMachineImageResource>>> ListOffersWithHttpMessagesAsync(string location, string publisherName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (publisherName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "publisherName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("publisherName", publisherName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListOffers", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers").ToString(); _url = _url.Replace("{location}", Uri.EscapeDataString(location)); _url = _url.Replace("{publisherName}", Uri.EscapeDataString(publisherName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200) { string _responseContent = null; var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, null); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new AzureOperationResponse<IList<VirtualMachineImageResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject<IList<VirtualMachineImageResource>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a list of virtual machine image publishers. /// </summary> /// <param name='location'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IList<VirtualMachineImageResource>>> ListPublishersWithHttpMessagesAsync(string location, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListPublishers", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers").ToString(); _url = _url.Replace("{location}", Uri.EscapeDataString(location)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200) { string _responseContent = null; var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, null); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new AzureOperationResponse<IList<VirtualMachineImageResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject<IList<VirtualMachineImageResource>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a list of virtual machine image skus. /// </summary> /// <param name='location'> /// </param> /// <param name='publisherName'> /// </param> /// <param name='offer'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IList<VirtualMachineImageResource>>> ListSkusWithHttpMessagesAsync(string location, string publisherName, string offer, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (publisherName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "publisherName"); } if (offer == null) { throw new ValidationException(ValidationRules.CannotBeNull, "offer"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("publisherName", publisherName); tracingParameters.Add("offer", offer); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListSkus", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus").ToString(); _url = _url.Replace("{location}", Uri.EscapeDataString(location)); _url = _url.Replace("{publisherName}", Uri.EscapeDataString(publisherName)); _url = _url.Replace("{offer}", Uri.EscapeDataString(offer)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)_statusCode != 200) { string _responseContent = null; var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, null); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } throw ex; } // Create Result var _result = new AzureOperationResponse<IList<VirtualMachineImageResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { try { string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); _result.Body = SafeJsonConvert.DeserializeObject<IList<VirtualMachineImageResource>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { throw new RestException("Unable to deserialize the response.", ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using ClosedXML.Excel; using NUnit.Framework; namespace ClosedXML_Tests.Excel.CalcEngine { [TestFixture] public class FunctionsTests { [OneTimeSetUp] public void Init() { // Make sure tests run on a deterministic culture System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); } [Test] public void Asc() { Object actual; actual = XLWorkbook.EvaluateExpr(@"Asc(""Text"")"); Assert.AreEqual("Text", actual); } [Test] public void Clean() { Object actual; actual = XLWorkbook.EvaluateExpr(String.Format(@"Clean(""A{0}B"")", Environment.NewLine)); Assert.AreEqual("AB", actual); } [Test] public void Combin() { object actual1 = XLWorkbook.EvaluateExpr("Combin(200, 2)"); Assert.AreEqual(19900.0, actual1); object actual2 = XLWorkbook.EvaluateExpr("Combin(20.1, 2.9)"); Assert.AreEqual(190.0, actual2); } [Test] public void Degrees() { object actual1 = XLWorkbook.EvaluateExpr("Degrees(180)"); Assert.IsTrue(Math.PI - (double) actual1 < XLHelper.Epsilon); } [Test] public void Dollar() { object actual = XLWorkbook.EvaluateExpr("Dollar(12345.123)"); Assert.AreEqual(TestHelper.CurrencySymbol + "12,345.12", actual); actual = XLWorkbook.EvaluateExpr("Dollar(12345.123, 1)"); Assert.AreEqual(TestHelper.CurrencySymbol + "12,345.1", actual); } [Test] public void Even() { object actual = XLWorkbook.EvaluateExpr("Even(3)"); Assert.AreEqual(4, actual); actual = XLWorkbook.EvaluateExpr("Even(2)"); Assert.AreEqual(2, actual); actual = XLWorkbook.EvaluateExpr("Even(-1)"); Assert.AreEqual(-2, actual); actual = XLWorkbook.EvaluateExpr("Even(-2)"); Assert.AreEqual(-2, actual); actual = XLWorkbook.EvaluateExpr("Even(0)"); Assert.AreEqual(0, actual); actual = XLWorkbook.EvaluateExpr("Even(1.5)"); Assert.AreEqual(2, actual); actual = XLWorkbook.EvaluateExpr("Even(2.01)"); Assert.AreEqual(4, actual); } [Test] public void Exact() { Object actual; actual = XLWorkbook.EvaluateExpr("Exact(\"A\", \"A\")"); Assert.AreEqual(true, actual); actual = XLWorkbook.EvaluateExpr("Exact(\"A\", \"a\")"); Assert.AreEqual(false, actual); } [Test] public void Fact() { object actual = XLWorkbook.EvaluateExpr("Fact(5.9)"); Assert.AreEqual(120.0, actual); } [Test] public void FactDouble() { object actual1 = XLWorkbook.EvaluateExpr("FactDouble(6)"); Assert.AreEqual(48.0, actual1); object actual2 = XLWorkbook.EvaluateExpr("FactDouble(7)"); Assert.AreEqual(105.0, actual2); } [Test] public void Fixed() { Object actual; actual = XLWorkbook.EvaluateExpr("Fixed(12345.123)"); Assert.AreEqual("12,345.12", actual); actual = XLWorkbook.EvaluateExpr("Fixed(12345.123, 1)"); Assert.AreEqual("12,345.1", actual); actual = XLWorkbook.EvaluateExpr("Fixed(12345.123, 1, TRUE)"); Assert.AreEqual("12345.1", actual); } [Test] public void Formula_from_another_sheet() { var wb = new XLWorkbook(); IXLWorksheet ws1 = wb.AddWorksheet("ws1"); ws1.FirstCell().SetValue(1).CellRight().SetFormulaA1("A1 + 1"); IXLWorksheet ws2 = wb.AddWorksheet("ws2"); ws2.FirstCell().SetFormulaA1("ws1!B1 + 1"); object v = ws2.FirstCell().Value; Assert.AreEqual(3.0, v); } [Test] public void Gcd() { object actual = XLWorkbook.EvaluateExpr("Gcd(24, 36)"); Assert.AreEqual(12, actual); object actual1 = XLWorkbook.EvaluateExpr("Gcd(5, 0)"); Assert.AreEqual(5, actual1); object actual2 = XLWorkbook.EvaluateExpr("Gcd(0, 5)"); Assert.AreEqual(5, actual2); object actual3 = XLWorkbook.EvaluateExpr("Gcd(240, 360, 30)"); Assert.AreEqual(30, actual3); } [Test] public void Lcm() { object actual = XLWorkbook.EvaluateExpr("Lcm(24, 36)"); Assert.AreEqual(72, actual); object actual1 = XLWorkbook.EvaluateExpr("Lcm(5, 0)"); Assert.AreEqual(0, actual1); object actual2 = XLWorkbook.EvaluateExpr("Lcm(0, 5)"); Assert.AreEqual(0, actual2); object actual3 = XLWorkbook.EvaluateExpr("Lcm(240, 360, 30)"); Assert.AreEqual(720, actual3); } [Test] public void MDetem() { IXLWorksheet ws = new XLWorkbook().AddWorksheet("Sheet1"); ws.Cell("A1").SetValue(2).CellRight().SetValue(4); ws.Cell("A2").SetValue(3).CellRight().SetValue(5); Object actual; ws.Cell("A5").FormulaA1 = "MDeterm(A1:B2)"; actual = ws.Cell("A5").Value; Assert.IsTrue(XLHelper.AreEqual(-2.0, (double) actual)); ws.Cell("A6").FormulaA1 = "Sum(A5)"; actual = ws.Cell("A6").Value; Assert.IsTrue(XLHelper.AreEqual(-2.0, (double) actual)); ws.Cell("A7").FormulaA1 = "Sum(MDeterm(A1:B2))"; actual = ws.Cell("A7").Value; Assert.IsTrue(XLHelper.AreEqual(-2.0, (double) actual)); } [Test] public void MInverse() { IXLWorksheet ws = new XLWorkbook().AddWorksheet("Sheet1"); ws.Cell("A1").SetValue(1).CellRight().SetValue(2).CellRight().SetValue(1); ws.Cell("A2").SetValue(3).CellRight().SetValue(4).CellRight().SetValue(-1); ws.Cell("A3").SetValue(0).CellRight().SetValue(2).CellRight().SetValue(0); Object actual; ws.Cell("A5").FormulaA1 = "MInverse(A1:C3)"; actual = ws.Cell("A5").Value; Assert.IsTrue(XLHelper.AreEqual(0.25, (double) actual)); ws.Cell("A6").FormulaA1 = "Sum(A5)"; actual = ws.Cell("A6").Value; Assert.IsTrue(XLHelper.AreEqual(0.25, (double) actual)); ws.Cell("A7").FormulaA1 = "Sum(MInverse(A1:C3))"; actual = ws.Cell("A7").Value; Assert.IsTrue(XLHelper.AreEqual(0.5, (double) actual)); } [Test] public void MMult() { IXLWorksheet ws = new XLWorkbook().AddWorksheet("Sheet1"); ws.Cell("A1").SetValue(2).CellRight().SetValue(4); ws.Cell("A2").SetValue(3).CellRight().SetValue(5); ws.Cell("A3").SetValue(2).CellRight().SetValue(4); ws.Cell("A4").SetValue(3).CellRight().SetValue(5); Object actual; ws.Cell("A5").FormulaA1 = "MMult(A1:B2, A3:B4)"; actual = ws.Cell("A5").Value; Assert.AreEqual(16.0, actual); ws.Cell("A6").FormulaA1 = "Sum(A5)"; actual = ws.Cell("A6").Value; Assert.AreEqual(16.0, actual); ws.Cell("A7").FormulaA1 = "Sum(MMult(A1:B2, A3:B4))"; actual = ws.Cell("A7").Value; Assert.AreEqual(102.0, actual); } [Test] public void MRound() { object actual = XLWorkbook.EvaluateExpr("MRound(10, 3)"); Assert.AreEqual(9m, actual); object actual3 = XLWorkbook.EvaluateExpr("MRound(10.5, 3)"); Assert.AreEqual(12m, actual3); object actual4 = XLWorkbook.EvaluateExpr("MRound(10.4, 3)"); Assert.AreEqual(9m, actual4); object actual1 = XLWorkbook.EvaluateExpr("MRound(-10, -3)"); Assert.AreEqual(-9m, actual1); object actual2 = XLWorkbook.EvaluateExpr("MRound(1.3, 0.2)"); Assert.AreEqual(1.4m, actual2); } [Test] public void Mod() { object actual = XLWorkbook.EvaluateExpr("Mod(3, 2)"); Assert.AreEqual(1, actual); object actual1 = XLWorkbook.EvaluateExpr("Mod(-3, 2)"); Assert.AreEqual(1, actual1); object actual2 = XLWorkbook.EvaluateExpr("Mod(3, -2)"); Assert.AreEqual(-1, actual2); object actual3 = XLWorkbook.EvaluateExpr("Mod(-3, -2)"); Assert.AreEqual(-1, actual3); } [Test] public void Multinomial() { object actual = XLWorkbook.EvaluateExpr("Multinomial(2,3,4)"); Assert.AreEqual(1260.0, actual); } [Test] public void Odd() { object actual = XLWorkbook.EvaluateExpr("Odd(1.5)"); Assert.AreEqual(3, actual); object actual1 = XLWorkbook.EvaluateExpr("Odd(3)"); Assert.AreEqual(3, actual1); object actual2 = XLWorkbook.EvaluateExpr("Odd(2)"); Assert.AreEqual(3, actual2); object actual3 = XLWorkbook.EvaluateExpr("Odd(-1)"); Assert.AreEqual(-1, actual3); object actual4 = XLWorkbook.EvaluateExpr("Odd(-2)"); Assert.AreEqual(-3, actual4); actual = XLWorkbook.EvaluateExpr("Odd(0)"); Assert.AreEqual(1, actual); } [Test] public void Product() { object actual = XLWorkbook.EvaluateExpr("Product(2,3,4)"); Assert.AreEqual(24.0, actual); } [Test] public void Quotient() { object actual = XLWorkbook.EvaluateExpr("Quotient(5,2)"); Assert.AreEqual(2, actual); actual = XLWorkbook.EvaluateExpr("Quotient(4.5,3.1)"); Assert.AreEqual(1, actual); actual = XLWorkbook.EvaluateExpr("Quotient(-10,3)"); Assert.AreEqual(-3, actual); } [Test] public void Radians() { object actual = XLWorkbook.EvaluateExpr("Radians(270)"); Assert.IsTrue(Math.Abs(4.71238898038469 - (double) actual) < XLHelper.Epsilon); } [Test] public void Roman() { object actual = XLWorkbook.EvaluateExpr("Roman(3046, 1)"); Assert.AreEqual("MMMXLVI", actual); actual = XLWorkbook.EvaluateExpr("Roman(270)"); Assert.AreEqual("CCLXX", actual); actual = XLWorkbook.EvaluateExpr("Roman(3999, true)"); Assert.AreEqual("MMMCMXCIX", actual); } [Test] public void Round() { object actual = XLWorkbook.EvaluateExpr("Round(2.15, 1)"); Assert.AreEqual(2.2, actual); actual = XLWorkbook.EvaluateExpr("Round(2.149, 1)"); Assert.AreEqual(2.1, actual); actual = XLWorkbook.EvaluateExpr("Round(-1.475, 2)"); Assert.AreEqual(-1.48, actual); actual = XLWorkbook.EvaluateExpr("Round(21.5, -1)"); Assert.AreEqual(20.0, actual); actual = XLWorkbook.EvaluateExpr("Round(626.3, -3)"); Assert.AreEqual(1000.0, actual); actual = XLWorkbook.EvaluateExpr("Round(1.98, -1)"); Assert.AreEqual(0.0, actual); actual = XLWorkbook.EvaluateExpr("Round(-50.55, -2)"); Assert.AreEqual(-100.0, actual); actual = XLWorkbook.EvaluateExpr("ROUND(59 * 0.535, 2)"); // (59 * 0.535) = 31.565 Assert.AreEqual(31.57, actual); actual = XLWorkbook.EvaluateExpr("ROUND(59 * -0.535, 2)"); // (59 * -0.535) = -31.565 Assert.AreEqual(-31.57, actual); } [Test] public void RoundDown() { object actual = XLWorkbook.EvaluateExpr("RoundDown(3.2, 0)"); Assert.AreEqual(3.0, actual); actual = XLWorkbook.EvaluateExpr("RoundDown(76.9, 0)"); Assert.AreEqual(76.0, actual); actual = XLWorkbook.EvaluateExpr("RoundDown(3.14159, 3)"); Assert.AreEqual(3.141, actual); actual = XLWorkbook.EvaluateExpr("RoundDown(-3.14159, 1)"); Assert.AreEqual(-3.1, actual); actual = XLWorkbook.EvaluateExpr("RoundDown(31415.92654, -2)"); Assert.AreEqual(31400.0, actual); actual = XLWorkbook.EvaluateExpr("RoundDown(0, 3)"); Assert.AreEqual(0.0, actual); } [Test] public void RoundUp() { object actual = XLWorkbook.EvaluateExpr("RoundUp(3.2, 0)"); Assert.AreEqual(4.0, actual); actual = XLWorkbook.EvaluateExpr("RoundUp(76.9, 0)"); Assert.AreEqual(77.0, actual); actual = XLWorkbook.EvaluateExpr("RoundUp(3.14159, 3)"); Assert.AreEqual(3.142, actual); actual = XLWorkbook.EvaluateExpr("RoundUp(-3.14159, 1)"); Assert.AreEqual(-3.2, actual); actual = XLWorkbook.EvaluateExpr("RoundUp(31415.92654, -2)"); Assert.AreEqual(31500.0, actual); actual = XLWorkbook.EvaluateExpr("RoundUp(0, 3)"); Assert.AreEqual(0.0, actual); } [Test] public void SeriesSum() { object actual = XLWorkbook.EvaluateExpr("SERIESSUM(2,3,4,5)"); Assert.AreEqual(40.0, actual); var wb = new XLWorkbook(); IXLWorksheet ws = wb.AddWorksheet("Sheet1"); ws.Cell("A2").FormulaA1 = "PI()/4"; ws.Cell("A3").Value = 1; ws.Cell("A4").FormulaA1 = "-1/FACT(2)"; ws.Cell("A5").FormulaA1 = "1/FACT(4)"; ws.Cell("A6").FormulaA1 = "-1/FACT(6)"; actual = ws.Evaluate("SERIESSUM(A2,0,2,A3:A6)"); Assert.IsTrue(Math.Abs(0.70710321482284566 - (double) actual) < XLHelper.Epsilon); } [Test] public void SqrtPi() { object actual = XLWorkbook.EvaluateExpr("SqrtPi(1)"); Assert.IsTrue(Math.Abs(1.7724538509055159 - (double) actual) < XLHelper.Epsilon); actual = XLWorkbook.EvaluateExpr("SqrtPi(2)"); Assert.IsTrue(Math.Abs(2.5066282746310002 - (double) actual) < XLHelper.Epsilon); } [Test] public void SubtotalAverage() { object actual = XLWorkbook.EvaluateExpr("Subtotal(1,2,3)"); Assert.AreEqual(2.5, actual); actual = XLWorkbook.EvaluateExpr(@"Subtotal(1,""A"",3, 2)"); Assert.AreEqual(2.5, actual); } [Test] public void SubtotalCount() { object actual = XLWorkbook.EvaluateExpr("Subtotal(2,2,3)"); Assert.AreEqual(2, actual); actual = XLWorkbook.EvaluateExpr(@"Subtotal(2,""A"",3)"); Assert.AreEqual(1, actual); } [Test] public void SubtotalCountA() { Object actual; actual = XLWorkbook.EvaluateExpr("Subtotal(3,2,3)"); Assert.AreEqual(2.0, actual); actual = XLWorkbook.EvaluateExpr(@"Subtotal(3,"""",3)"); Assert.AreEqual(1.0, actual); } [Test] public void SubtotalMax() { Object actual; actual = XLWorkbook.EvaluateExpr(@"Subtotal(4,2,3,""A"")"); Assert.AreEqual(3.0, actual); } [Test] public void SubtotalMin() { Object actual; actual = XLWorkbook.EvaluateExpr(@"Subtotal(5,2,3,""A"")"); Assert.AreEqual(2.0, actual); } [Test] public void SubtotalProduct() { Object actual; actual = XLWorkbook.EvaluateExpr(@"Subtotal(6,2,3,""A"")"); Assert.AreEqual(6.0, actual); } [Test] public void SubtotalStDev() { Object actual; actual = XLWorkbook.EvaluateExpr(@"Subtotal(7,2,3,""A"")"); Assert.IsTrue(Math.Abs(0.70710678118654757 - (double) actual) < XLHelper.Epsilon); } [Test] public void SubtotalStDevP() { Object actual; actual = XLWorkbook.EvaluateExpr(@"Subtotal(8,2,3,""A"")"); Assert.AreEqual(0.5, actual); } [Test] public void SubtotalSum() { Object actual; actual = XLWorkbook.EvaluateExpr(@"Subtotal(9,2,3,""A"")"); Assert.AreEqual(5.0, actual); } [Test] public void SubtotalVar() { Object actual; actual = XLWorkbook.EvaluateExpr(@"Subtotal(10,2,3,""A"")"); Assert.IsTrue(Math.Abs(0.5 - (double) actual) < XLHelper.Epsilon); } [Test] public void SubtotalVarP() { Object actual; actual = XLWorkbook.EvaluateExpr(@"Subtotal(11,2,3,""A"")"); Assert.AreEqual(0.25, actual); } [Test] public void Sum() { IXLCell cell = new XLWorkbook().AddWorksheet("Sheet1").FirstCell(); IXLCell fCell = cell.SetValue(1).CellBelow().SetValue(2).CellBelow(); fCell.FormulaA1 = "sum(A1:A2)"; Assert.AreEqual(3.0, fCell.Value); } [Test] public void SumSq() { Object actual; actual = XLWorkbook.EvaluateExpr(@"SumSq(3,4)"); Assert.AreEqual(25.0, actual); } [Test] public void TextConcat() { var wb = new XLWorkbook(); IXLWorksheet ws = wb.AddWorksheet("Sheet1"); ws.Cell("A1").Value = 1; ws.Cell("A2").Value = 1; ws.Cell("B1").Value = 1; ws.Cell("B2").Value = 1; ws.Cell("C1").FormulaA1 = "\"The total value is: \" & SUM(A1:B2)"; object r = ws.Cell("C1").Value; Assert.AreEqual("The total value is: 4", r.ToString()); } [Test] public void Trim() { Assert.AreEqual("Test", XLWorkbook.EvaluateExpr("Trim(\"Test \")")); //Should not trim non breaking space //See http://office.microsoft.com/en-us/excel-help/trim-function-HP010062581.aspx Assert.AreEqual("Test\u00A0", XLWorkbook.EvaluateExpr("Trim(\"Test\u00A0 \")")); } [Test] public void TestEmptyTallyOperations() { //In these test no values have been set XLWorkbook wb = new XLWorkbook(); wb.Worksheets.Add("TallyTests"); var cell = wb.Worksheet(1).Cell(1, 1).SetFormulaA1("=MAX(D1,D2)"); Assert.AreEqual(0, cell.Value); cell = wb.Worksheet(1).Cell(2, 1).SetFormulaA1("=MIN(D1,D2)"); Assert.AreEqual(0, cell.Value); cell = wb.Worksheet(1).Cell(3, 1).SetFormulaA1("=SUM(D1,D2)"); Assert.AreEqual(0, cell.Value); Assert.That(() => wb.Worksheet(1).Cell(3, 1).SetFormulaA1("=AVERAGE(D1,D2)").Value, Throws.TypeOf<ApplicationException>()); } [Test] public void TestOmittedParameters() { using (var wb = new XLWorkbook()) { object value; value = wb.Evaluate("=IF(TRUE,1)"); Assert.AreEqual(1, value); value = wb.Evaluate("=IF(TRUE,1,)"); Assert.AreEqual(1, value); value = wb.Evaluate("=IF(FALSE,1,)"); Assert.AreEqual(false, value); value = wb.Evaluate("=IF(FALSE,,2)"); Assert.AreEqual(2, value); } } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.IdentityModel.Tokens { using System.ComponentModel; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Net; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Principal; using System.Security.Authentication.ExtendedProtection; using System.IdentityModel.Diagnostics; public class KerberosRequestorSecurityToken : SecurityToken { string id; byte[] apreq; readonly string servicePrincipalName; SymmetricSecurityKey symmetricSecurityKey; ReadOnlyCollection<SecurityKey> securityKeys; DateTime effectiveTime; DateTime expirationTime; public KerberosRequestorSecurityToken(string servicePrincipalName) : this(servicePrincipalName, TokenImpersonationLevel.Impersonation, null, SecurityUniqueId.Create().Value, null) { } public KerberosRequestorSecurityToken(string servicePrincipalName, TokenImpersonationLevel tokenImpersonationLevel, NetworkCredential networkCredential, string id) : this(servicePrincipalName, tokenImpersonationLevel, networkCredential, id, null, null) { } internal KerberosRequestorSecurityToken(string servicePrincipalName, TokenImpersonationLevel tokenImpersonationLevel, NetworkCredential networkCredential, string id, ChannelBinding channelBinding) : this(servicePrincipalName, tokenImpersonationLevel, networkCredential, id, null, channelBinding) { } internal KerberosRequestorSecurityToken(string servicePrincipalName, TokenImpersonationLevel tokenImpersonationLevel, NetworkCredential networkCredential, string id, SafeFreeCredentials credentialsHandle, ChannelBinding channelBinding) { if (servicePrincipalName == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("servicePrincipalName"); if (tokenImpersonationLevel != TokenImpersonationLevel.Identification && tokenImpersonationLevel != TokenImpersonationLevel.Impersonation) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("tokenImpersonationLevel", SR.GetString(SR.ImpersonationLevelNotSupported, tokenImpersonationLevel))); } if (id == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("id"); this.servicePrincipalName = servicePrincipalName; if (networkCredential != null && networkCredential != CredentialCache.DefaultNetworkCredentials) { if (string.IsNullOrEmpty(networkCredential.UserName)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.ProvidedNetworkCredentialsForKerberosHasInvalidUserName)); } // Note: we don't check the domain, since Lsa accepts // FQ userName. } this.id = id; try { Initialize(tokenImpersonationLevel, networkCredential, credentialsHandle, channelBinding); } catch (Win32Exception e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(SR.GetString(SR.UnableToCreateKerberosCredentials), e)); } catch (SecurityTokenException ste) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(SR.GetString(SR.UnableToCreateKerberosCredentials), ste)); } } public override string Id { get { return this.id; } } public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { if (this.securityKeys == null) { List<SecurityKey> temp = new List<SecurityKey>(1); temp.Add(this.symmetricSecurityKey); this.securityKeys = temp.AsReadOnly(); } return this.securityKeys; } } public override DateTime ValidFrom { get { return this.effectiveTime; } } public override DateTime ValidTo { get { return this.expirationTime; } } public string ServicePrincipalName { get { return this.servicePrincipalName; } } public SymmetricSecurityKey SecurityKey { get { return this.symmetricSecurityKey; } } public byte[] GetRequest() { return SecurityUtils.CloneBuffer(this.apreq); } void Initialize(TokenImpersonationLevel tokenImpersonationLevel, NetworkCredential networkCredential, SafeFreeCredentials credentialsHandle, ChannelBinding channelBinding) { bool ownCredentialsHandle = false; SafeDeleteContext securityContext = null; try { if (credentialsHandle == null) { if (networkCredential == null || networkCredential == CredentialCache.DefaultNetworkCredentials) { credentialsHandle = SspiWrapper.AcquireDefaultCredential("Kerberos", CredentialUse.Outbound); } else { AuthIdentityEx authIdentity = new AuthIdentityEx(networkCredential.UserName, networkCredential.Password, networkCredential.Domain); credentialsHandle = SspiWrapper.AcquireCredentialsHandle("Kerberos", CredentialUse.Outbound, ref authIdentity); } ownCredentialsHandle = true; } SspiContextFlags fContextReq = SspiContextFlags.AllocateMemory | SspiContextFlags.Confidentiality | SspiContextFlags.ReplayDetect | SspiContextFlags.SequenceDetect; // we only accept Identity or Impersonation (Impersonation is default). if (tokenImpersonationLevel == TokenImpersonationLevel.Identification) { fContextReq |= SspiContextFlags.InitIdentify; } SspiContextFlags contextFlags = SspiContextFlags.Zero; SecurityBuffer inSecurityBuffer = null; if (channelBinding != null) { inSecurityBuffer = new SecurityBuffer(channelBinding); } SecurityBuffer outSecurityBuffer = new SecurityBuffer(0, BufferType.Token); int statusCode = SspiWrapper.InitializeSecurityContext( credentialsHandle, ref securityContext, this.servicePrincipalName, fContextReq, Endianness.Native, inSecurityBuffer, outSecurityBuffer, ref contextFlags); if (DiagnosticUtility.ShouldTraceInformation) { SecurityTraceRecordHelper.TraceChannelBindingInformation(null, false, channelBinding); } if (statusCode != (int)SecurityStatus.OK) { if (statusCode == (int)SecurityStatus.ContinueNeeded) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityTokenException(SR.GetString(SR.KerberosMultilegsNotSupported), new Win32Exception(statusCode))); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityTokenException(SR.GetString(SR.FailInitializeSecurityContext), new Win32Exception(statusCode))); } } #if REMOVEGSS // // ... and strip GSS-framing from it // int offset = 0; int len = outSecurityBuffer.token.Length; DEREncoding.VerifyTokenHeader(outSecurityBuffer.token, ref offset, ref len); this.apreq = SecurityUtils.CloneBuffer(outSecurityBuffer.token, offset, len); #else this.apreq = outSecurityBuffer.token; #endif // Expiration LifeSpan lifeSpan = (LifeSpan)SspiWrapper.QueryContextAttributes(securityContext, ContextAttribute.Lifespan); this.effectiveTime = lifeSpan.EffectiveTimeUtc; this.expirationTime = lifeSpan.ExpiryTimeUtc; // SessionKey SecuritySessionKeyClass sessionKey = (SecuritySessionKeyClass)SspiWrapper.QueryContextAttributes(securityContext, ContextAttribute.SessionKey); this.symmetricSecurityKey = new InMemorySymmetricSecurityKey(sessionKey.SessionKey); } finally { if (securityContext != null) securityContext.Close(); if (ownCredentialsHandle && credentialsHandle != null) credentialsHandle.Close(); } } public override bool CanCreateKeyIdentifierClause<T>() { if (typeof(T) == typeof(KerberosTicketHashKeyIdentifierClause)) return true; return base.CanCreateKeyIdentifierClause<T>(); } public override T CreateKeyIdentifierClause<T>() { if (typeof(T) == typeof(KerberosTicketHashKeyIdentifierClause)) return new KerberosTicketHashKeyIdentifierClause(CryptoHelper.ComputeHash(this.apreq), false, null, 0) as T; return base.CreateKeyIdentifierClause<T>(); } public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { KerberosTicketHashKeyIdentifierClause kerbKeyIdentifierClause = keyIdentifierClause as KerberosTicketHashKeyIdentifierClause; if (kerbKeyIdentifierClause != null) return kerbKeyIdentifierClause.Matches(CryptoHelper.ComputeHash(this.apreq)); return base.MatchesKeyIdentifierClause(keyIdentifierClause); } } }
/****************************************************************************** * 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 object entry = ((LdapSearchResult)msg).Entry; entries.Add(entry); i++; entryCount++; } else if (msg is LdapSearchResultReference) { // Search Ref 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 { // 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, (string)null); entries.Add(e); break; } } catch (LdapException e) { // Hand exception off to user entries.Add(e); } } 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 object nameLock; // protect resultsNum private static int resultsNum = 0; // used for debug private 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) ? Int32.MaxValue : batchSize; } /// <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; } } /// <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 ArgumentOutOfRangeException("LdapSearchResults.next() no more results"); } // Check if the enumeration is empty and must be reloaded resetVectors(); 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) { string[] refs = (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 object[] { "next" }, LdapException.LOCAL_ERROR, (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 object(); } } }
//Copyright 2010 Microsoft Corporation // //Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an //"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and limitations under the License. namespace System.Data.Services.Client { #region Namespaces using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Reflection; #endregion internal sealed class BindingObserver { #region Fields private BindingGraph bindingGraph; #endregion #region Constructor internal BindingObserver(DataServiceContext context, Func<EntityChangedParams, bool> entityChanged, Func<EntityCollectionChangedParams, bool> collectionChanged) { Debug.Assert(context != null, "Must have been validated during DataServiceCollection construction."); this.Context = context; this.Context.ChangesSaved += this.OnChangesSaved; this.EntityChanged = entityChanged; this.CollectionChanged = collectionChanged; this.bindingGraph = new BindingGraph(this); } #endregion #region Properties internal DataServiceContext Context { get; private set; } internal bool AttachBehavior { get; set; } internal bool DetachBehavior { get; set; } internal Func<EntityChangedParams, bool> EntityChanged { get; private set; } internal Func<EntityCollectionChangedParams, bool> CollectionChanged { get; private set; } #endregion #region Methods internal void StartTracking<T>(DataServiceCollection<T> collection, string collectionEntitySet) { Debug.Assert(collection != null, "Only constructed collections are tracked."); if (!BindingEntityInfo.IsEntityType(typeof(T))) { throw new ArgumentException(Strings.DataBinding_DataServiceCollectionArgumentMustHaveEntityType(typeof(T))); } try { this.AttachBehavior = true; this.bindingGraph.AddCollection(null, null, collection, collectionEntitySet); } finally { this.AttachBehavior = false; } } internal void StopTracking() { this.bindingGraph.Reset(); this.Context.ChangesSaved -= this.OnChangesSaved; } #if ASTORIA_LIGHT internal bool LookupParent<T>(DataServiceCollection<T> collection, out object parentEntity, out string parentProperty) { string sourceEntitySet; string targetEntitySet; this.bindingGraph.GetEntityCollectionInfo(collection, out parentEntity, out parentProperty, out sourceEntitySet, out targetEntitySet); return parentEntity != null; } #endif [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining | System.Runtime.CompilerServices.MethodImplOptions.NoOptimization)] internal void OnPropertyChanged(object source, PropertyChangedEventArgs eventArgs) { Util.CheckArgumentNull(source, "source"); Util.CheckArgumentNull(eventArgs, "eventArgs"); #if DEBUG Debug.Assert(this.bindingGraph.IsTracking(source), "Entity must be part of the graph if it has the event notification registered."); #endif string sourceProperty = eventArgs.PropertyName; if (String.IsNullOrEmpty(sourceProperty)) { this.HandleUpdateEntity( source, null, null); } else { BindingEntityInfo.BindingPropertyInfo bpi; object sourcePropertyValue = BindingEntityInfo.GetPropertyValue(source, sourceProperty, out bpi); if (bpi != null) { this.bindingGraph.RemoveRelation(source, sourceProperty); switch (bpi.PropertyKind) { case BindingPropertyKind.BindingPropertyKindCollection: if (sourcePropertyValue != null) { try { typeof(BindingUtils) .GetMethod("VerifyObserverNotPresent", BindingFlags.NonPublic | BindingFlags.Static) .MakeGenericMethod(bpi.PropertyInfo.CollectionType) .Invoke(null, new object[] { sourcePropertyValue, sourceProperty, source.GetType() }); } catch (TargetInvocationException tie) { throw tie.InnerException; } try { this.AttachBehavior = true; this.bindingGraph.AddCollection( source, sourceProperty, sourcePropertyValue, null); } finally { this.AttachBehavior = false; } } break; case BindingPropertyKind.BindingPropertyKindEntity: this.bindingGraph.AddEntity( source, sourceProperty, sourcePropertyValue, null, source); break; default: Debug.Assert(bpi.PropertyKind == BindingPropertyKind.BindingPropertyKindComplex, "Must be complex type if PropertyKind is not entity or collection."); if (sourcePropertyValue != null) { this.bindingGraph.AddComplexProperty( source, sourceProperty, sourcePropertyValue); } this.HandleUpdateEntity( source, sourceProperty, sourcePropertyValue); break; } } else { this.HandleUpdateEntity( source, sourceProperty, sourcePropertyValue); } } } internal void OnCollectionChanged(object collection, NotifyCollectionChangedEventArgs eventArgs) { Util.CheckArgumentNull(collection, "collection"); Util.CheckArgumentNull(eventArgs, "eventArgs"); Debug.Assert(BindingEntityInfo.IsDataServiceCollection(collection.GetType()), "We only register this event for DataServiceCollections."); #if DEBUG Debug.Assert(this.bindingGraph.IsTracking(collection), "Collection must be part of the graph if it has the event notification registered."); #endif object source; string sourceProperty; string sourceEntitySet; string targetEntitySet; this.bindingGraph.GetEntityCollectionInfo( collection, out source, out sourceProperty, out sourceEntitySet, out targetEntitySet); switch (eventArgs.Action) { case NotifyCollectionChangedAction.Add: this.OnAddToCollection( eventArgs, source, sourceProperty, targetEntitySet, collection); break; case NotifyCollectionChangedAction.Remove: this.OnDeleteFromCollection( eventArgs, source, sourceProperty, collection); break; case NotifyCollectionChangedAction.Replace: this.OnDeleteFromCollection( eventArgs, source, sourceProperty, collection); this.OnAddToCollection( eventArgs, source, sourceProperty, targetEntitySet, collection); break; case NotifyCollectionChangedAction.Reset: if (this.DetachBehavior) { this.RemoveWithDetachCollection(collection); } else { this.bindingGraph.RemoveCollection(collection); } break; #if !ASTORIA_LIGHT case NotifyCollectionChangedAction.Move: break; #endif default: throw new InvalidOperationException(Strings.DataBinding_CollectionChangedUnknownAction(eventArgs.Action)); } } internal void HandleAddEntity( object source, string sourceProperty, string sourceEntitySet, ICollection collection, object target, string targetEntitySet) { if (this.Context.ApplyingChanges) { return; } Debug.Assert( (source == null && sourceProperty == null) || (source != null && !String.IsNullOrEmpty(sourceProperty)), "source and sourceProperty should either both be present or both be absent."); Debug.Assert(target != null, "target must be provided by the caller."); Debug.Assert(BindingEntityInfo.IsEntityType(target.GetType()), "target must be an entity type."); if (source != null && this.IsDetachedOrDeletedFromContext(source)) { return; } EntityDescriptor targetDescriptor = this.Context.GetEntityDescriptor(target); bool contextOperationRequired = !this.AttachBehavior && (targetDescriptor == null || (source != null && !this.IsContextTrackingLink(source, sourceProperty, target) && targetDescriptor.State != EntityStates.Deleted)); if (contextOperationRequired) { if (this.CollectionChanged != null) { EntityCollectionChangedParams args = new EntityCollectionChangedParams( this.Context, source, sourceProperty, sourceEntitySet, collection, target, targetEntitySet, NotifyCollectionChangedAction.Add); if (this.CollectionChanged(args)) { return; } } } if (source != null && this.IsDetachedOrDeletedFromContext(source)) { throw new InvalidOperationException(Strings.DataBinding_BindingOperation_DetachedSource); } targetDescriptor = this.Context.GetEntityDescriptor(target); if (source != null) { if (this.AttachBehavior) { if (targetDescriptor == null) { BindingUtils.ValidateEntitySetName(targetEntitySet, target); this.Context.AttachTo(targetEntitySet, target); this.Context.AttachLink(source, sourceProperty, target); } else if (targetDescriptor.State != EntityStates.Deleted && !this.IsContextTrackingLink(source, sourceProperty, target)) { this.Context.AttachLink(source, sourceProperty, target); } } else { if (targetDescriptor == null) { this.Context.AddRelatedObject(source, sourceProperty, target); } else if (targetDescriptor.State != EntityStates.Deleted && !this.IsContextTrackingLink(source, sourceProperty, target)) { this.Context.AddLink(source, sourceProperty, target); } } } else if (targetDescriptor == null) { BindingUtils.ValidateEntitySetName(targetEntitySet, target); if (this.AttachBehavior) { this.Context.AttachTo(targetEntitySet, target); } else { this.Context.AddObject(targetEntitySet, target); } } } internal void HandleDeleteEntity( object source, string sourceProperty, string sourceEntitySet, ICollection collection, object target, string targetEntitySet) { if (this.Context.ApplyingChanges) { return; } Debug.Assert( (source == null && sourceProperty == null) || (source != null && !String.IsNullOrEmpty(sourceProperty)), "source and sourceProperty should either both be present or both be absent."); Debug.Assert(target != null, "target must be provided by the caller."); Debug.Assert(BindingEntityInfo.IsEntityType(target.GetType()), "target must be an entity type."); Debug.Assert(!this.AttachBehavior, "AttachBehavior is only allowed during Construction and Load when this method should never be entered."); if (source != null && this.IsDetachedOrDeletedFromContext(source)) { return; } bool contextOperationRequired = this.IsContextTrackingEntity(target) && !this.DetachBehavior; if (contextOperationRequired) { if (this.CollectionChanged != null) { EntityCollectionChangedParams args = new EntityCollectionChangedParams( this.Context, source, sourceProperty, sourceEntitySet, collection, target, targetEntitySet, NotifyCollectionChangedAction.Remove); if (this.CollectionChanged(args)) { return; } } } if (source != null && !this.IsContextTrackingEntity(source)) { throw new InvalidOperationException(Strings.DataBinding_BindingOperation_DetachedSource); } if (this.IsContextTrackingEntity(target)) { if (this.DetachBehavior) { this.Context.Detach(target); } else { this.Context.DeleteObject(target); } } } internal void HandleUpdateEntityReference( object source, string sourceProperty, string sourceEntitySet, object target, string targetEntitySet) { if (this.Context.ApplyingChanges) { return; } Debug.Assert(source != null, "source can not be null for update operations."); Debug.Assert(BindingEntityInfo.IsEntityType(source.GetType()), "source must be an entity with keys."); Debug.Assert(!String.IsNullOrEmpty(sourceProperty), "sourceProperty must be a non-empty string for update operations."); Debug.Assert(!String.IsNullOrEmpty(sourceEntitySet), "sourceEntitySet must be non-empty string for update operation."); if (this.IsDetachedOrDeletedFromContext(source)) { return; } EntityDescriptor targetDescriptor = target != null ? this.Context.GetEntityDescriptor(target) : null; bool contextOperationRequired = !this.AttachBehavior && (targetDescriptor == null || !this.IsContextTrackingLink(source, sourceProperty, target)); if (contextOperationRequired) { if (this.EntityChanged != null) { EntityChangedParams args = new EntityChangedParams( this.Context, source, sourceProperty, target, sourceEntitySet, targetEntitySet); if (this.EntityChanged(args)) { return; } } } if (this.IsDetachedOrDeletedFromContext(source)) { throw new InvalidOperationException(Strings.DataBinding_BindingOperation_DetachedSource); } targetDescriptor = target != null ? this.Context.GetEntityDescriptor(target) : null; if (target != null) { if (targetDescriptor == null) { BindingUtils.ValidateEntitySetName(targetEntitySet, target); if (this.AttachBehavior) { this.Context.AttachTo(targetEntitySet, target); } else { this.Context.AddObject(targetEntitySet, target); } targetDescriptor = this.Context.GetEntityDescriptor(target); } if (!this.IsContextTrackingLink(source, sourceProperty, target)) { if (this.AttachBehavior) { if (targetDescriptor.State != EntityStates.Deleted) { this.Context.AttachLink(source, sourceProperty, target); } } else { this.Context.SetLink(source, sourceProperty, target); } } } else { Debug.Assert(!this.AttachBehavior, "During attach operations we must never perform operations for null values."); this.Context.SetLink(source, sourceProperty, null); } } internal bool IsContextTrackingEntity(object entity) { Debug.Assert(entity != null, "entity must be provided when checking for context tracking."); return this.Context.GetEntityDescriptor(entity) != default(EntityDescriptor); } private void HandleUpdateEntity(object entity, string propertyName, object propertyValue) { Debug.Assert(!this.AttachBehavior || this.Context.ApplyingChanges, "Entity updates must not happen during Attach or construction phases, deserialization case is the exception."); if (this.Context.ApplyingChanges) { return; } if (!BindingEntityInfo.IsEntityType(entity.GetType())) { this.bindingGraph.GetAncestorEntityForComplexProperty(ref entity, ref propertyName, ref propertyValue); } Debug.Assert(entity != null, "entity must be provided for update operations."); Debug.Assert(BindingEntityInfo.IsEntityType(entity.GetType()), "entity must be an entity with keys."); Debug.Assert(!String.IsNullOrEmpty(propertyName) || propertyValue == null, "When propertyName is null no propertyValue should be provided."); if (this.IsDetachedOrDeletedFromContext(entity)) { return; } if (this.EntityChanged != null) { EntityChangedParams args = new EntityChangedParams( this.Context, entity, propertyName, propertyValue, null, null); if (this.EntityChanged(args)) { return; } } if (this.IsContextTrackingEntity(entity)) { this.Context.UpdateObject(entity); } } private void OnAddToCollection( NotifyCollectionChangedEventArgs eventArgs, object source, String sourceProperty, String targetEntitySet, object collection) { Debug.Assert(collection != null, "Must have a valid collection to which entities are added."); if (eventArgs.NewItems != null) { foreach (object target in eventArgs.NewItems) { if (target == null) { throw new InvalidOperationException(Strings.DataBinding_BindingOperation_ArrayItemNull("Add")); } if (!BindingEntityInfo.IsEntityType(target.GetType())) { throw new InvalidOperationException(Strings.DataBinding_BindingOperation_ArrayItemNotEntity("Add")); } this.bindingGraph.AddEntity( source, sourceProperty, target, targetEntitySet, collection); } } } private void OnDeleteFromCollection( NotifyCollectionChangedEventArgs eventArgs, object source, String sourceProperty, object collection) { Debug.Assert(collection != null, "Must have a valid collection from which entities are removed."); Debug.Assert( (source == null && sourceProperty == null) || (source != null && !String.IsNullOrEmpty(sourceProperty)), "source and sourceProperty must both be null or both be non-null."); if (eventArgs.OldItems != null) { this.DeepRemoveCollection( eventArgs.OldItems, source ?? collection, sourceProperty, this.ValidateCollectionItem); } } private void RemoveWithDetachCollection(object collection) { Debug.Assert(this.DetachBehavior, "Must be detaching each item in collection."); object source = null; string sourceProperty = null; string sourceEntitySet = null; string targetEntitySet = null; this.bindingGraph.GetEntityCollectionInfo( collection, out source, out sourceProperty, out sourceEntitySet, out targetEntitySet); this.DeepRemoveCollection( this.bindingGraph.GetCollectionItems(collection), source ?? collection, sourceProperty, null); } private void DeepRemoveCollection(IEnumerable collection, object source, string sourceProperty, Action<object> itemValidator) { foreach (object target in collection) { if (itemValidator != null) { itemValidator(target); } List<UnTrackingInfo> untrackingInfo = new List<UnTrackingInfo>(); this.CollectUnTrackingInfo( target, source, sourceProperty, untrackingInfo); foreach (UnTrackingInfo info in untrackingInfo) { this.bindingGraph.Remove( info.Entity, info.Parent, info.ParentProperty); } } this.bindingGraph.RemoveUnreachableVertices(); } private void OnChangesSaved(object sender, SaveChangesEventArgs eventArgs) { this.bindingGraph.RemoveNonTrackedEntities(); } private void CollectUnTrackingInfo( object currentEntity, object parentEntity, string parentProperty, IList<UnTrackingInfo> entitiesToUnTrack) { foreach (var ed in this.Context .Entities .Where(x => x.ParentEntity == currentEntity && x.State == EntityStates.Added)) { this.CollectUnTrackingInfo( ed.Entity, ed.ParentEntity, ed.ParentPropertyForInsert, entitiesToUnTrack); } entitiesToUnTrack.Add(new UnTrackingInfo { Entity = currentEntity, Parent = parentEntity, ParentProperty = parentProperty }); } private bool IsContextTrackingLink(object source, string sourceProperty, object target) { Debug.Assert(source != null, "source entity must be provided."); Debug.Assert(BindingEntityInfo.IsEntityType(source.GetType()), "source must be an entity with keys."); Debug.Assert(!String.IsNullOrEmpty(sourceProperty), "sourceProperty must be provided."); Debug.Assert(target != null, "target entity must be provided."); Debug.Assert(BindingEntityInfo.IsEntityType(target.GetType()), "target must be an entity with keys."); return this.Context.GetLinkDescriptor(source, sourceProperty, target) != default(LinkDescriptor); } private bool IsDetachedOrDeletedFromContext(object entity) { Debug.Assert(entity != null, "entity must be provided."); Debug.Assert(BindingEntityInfo.IsEntityType(entity.GetType()), "entity must be an entity with keys."); EntityDescriptor descriptor = this.Context.GetEntityDescriptor(entity); return descriptor == null || descriptor.State == EntityStates.Deleted; } private void ValidateCollectionItem(object target) { if (target == null) { throw new InvalidOperationException(Strings.DataBinding_BindingOperation_ArrayItemNull("Remove")); } if (!BindingEntityInfo.IsEntityType(target.GetType())) { throw new InvalidOperationException(Strings.DataBinding_BindingOperation_ArrayItemNotEntity("Remove")); } } #endregion private class UnTrackingInfo { public object Entity { get; set; } public object Parent { get; set; } public string ParentProperty { get; set; } } } }
using System; using System.Linq; using Baseline; using LamarCodeGeneration; using LamarCodeGeneration.Frames; using Marten.Internal.Storage; using Marten.Linq; using Marten.Linq.SqlGeneration; using Marten.Schema; using Marten.Services; using Marten.Storage; namespace Marten.Internal.CodeGeneration { internal class DocumentStorageBuilder { private readonly Func<DocumentOperations, GeneratedType> _selectorTypeSource; private readonly Type _baseType; private readonly string _typeName; private readonly DocumentMapping _mapping; public static string DeriveTypeName(DocumentMapping mapping, StorageStyle style) { return $"{style}{mapping.DocumentType.Name.Sanitize()}DocumentStorage"; } public DocumentStorageBuilder(DocumentMapping mapping, StorageStyle style, Func<DocumentOperations, GeneratedType> selectorTypeSource) { _mapping = mapping; _selectorTypeSource = selectorTypeSource; _typeName = DeriveTypeName(mapping, style); _baseType = determineOpenDocumentStorageType(style).MakeGenericType(mapping.DocumentType, mapping.IdType); } private Type determineOpenDocumentStorageType(StorageStyle style) { switch (style) { case StorageStyle.Lightweight: return typeof(LightweightDocumentStorage<,>); case StorageStyle.QueryOnly: return typeof(QueryOnlyDocumentStorage<,>); case StorageStyle.IdentityMap: return typeof(IdentityMapDocumentStorage<,>); case StorageStyle.DirtyTracking: return typeof(DirtyCheckedDocumentStorage<,>); } throw new NotSupportedException(); } public GeneratedType Build(GeneratedAssembly assembly, DocumentOperations operations) { var selectorType = _selectorTypeSource(operations); return buildDocumentStorageType(assembly, operations, _typeName, _baseType, selectorType); } private GeneratedType buildDocumentStorageType(GeneratedAssembly assembly, DocumentOperations operations, string typeName, Type baseType, GeneratedType selectorType) { var type = assembly.AddType(typeName, baseType); writeIdentityMethod(type); buildStorageOperationMethods(operations, type); type.MethodFor(nameof(ISelectClause.BuildSelector)) .Frames.Code($"return new Marten.Generated.{selectorType.TypeName}({{0}}, {{1}});", Use.Type<IMartenSession>(), Use.Type<DocumentMapping>()); buildLoaderCommands(type); writeNotImplementedStubs(type); return type; } private void writeIdentityMethod(GeneratedType type) { var identity = type.MethodFor("Identity"); identity.Frames.Code($"return {{0}}.{_mapping.IdMember.Name};", identity.Arguments[0]); var assign = type.MethodFor("AssignIdentity"); _mapping.IdStrategy.GenerateCode(assign, _mapping); } private static void writeNotImplementedStubs(GeneratedType type) { var missing = type.Methods.Where(x => !x.Frames.Any()).Select(x => x.MethodName); if (missing.Any()) { throw new Exception("Missing methods: " + missing.Join(", ")); } foreach (var method in type.Methods) { if (!method.Frames.Any()) { method.Frames.ThrowNotImplementedException(); } } } private void buildLoaderCommands(GeneratedType type) { var load = type.MethodFor("BuildLoadCommand"); var loadByArray = type.MethodFor("BuildLoadManyCommand"); if (_mapping.TenancyStyle == TenancyStyle.Conjoined) { load.Frames.Code( "return new NpgsqlCommand(_loaderSql).With(\"id\", id).With(TenantIdArgument.ArgName, tenant.TenantId);"); loadByArray.Frames.Code( "return new NpgsqlCommand(_loadArraySql).With(\"ids\", ids).With(TenantIdArgument.ArgName, tenant.TenantId);"); } else { load.Frames.Code("return new NpgsqlCommand(_loaderSql).With(\"id\", id);"); loadByArray.Frames.Code("return new NpgsqlCommand(_loadArraySql).With(\"ids\", ids);"); } } private void buildStorageOperationMethods(DocumentOperations operations, GeneratedType type) { if (_mapping.UseOptimisticConcurrency) { buildConditionalOperationBasedOnConcurrencyChecks(type, operations, "Upsert"); buildOperationMethod(type, operations, "Insert"); buildOperationMethod(type, operations, "Overwrite"); buildConditionalOperationBasedOnConcurrencyChecks(type, operations, "Update"); } else { buildOperationMethod(type, operations, "Upsert"); buildOperationMethod(type, operations, "Insert"); buildOperationMethod(type, operations, "Update"); } if (_mapping.UseOptimisticConcurrency) { buildOperationMethod(type, operations, "Overwrite"); } else { type.MethodFor("Overwrite").Frames.ThrowNotSupportedException(); } } private void buildConditionalOperationBasedOnConcurrencyChecks(GeneratedType type, DocumentOperations operations, string methodName) { var operationType = (GeneratedType)typeof(DocumentOperations).GetProperty(methodName).GetValue(operations); var overwriteType = operations.Overwrite; var method = type.MethodFor(methodName); method.Frames.Code($"BLOCK:if (session.{nameof(IDocumentSession.Concurrency)} == {{0}})", ConcurrencyChecks.Disabled); writeReturnOfOperation(method, overwriteType); method.Frames.Code("END"); method.Frames.Code("BLOCK:else"); writeReturnOfOperation(method, operationType); method.Frames.Code("END"); } private void buildOperationMethod(GeneratedType type, DocumentOperations operations, string methodName) { var operationType = (GeneratedType)typeof(DocumentOperations).GetProperty(methodName).GetValue(operations); var method = type.MethodFor(methodName); writeReturnOfOperation(method, operationType); } private void writeReturnOfOperation(GeneratedMethod method, GeneratedType operationType) { var tenantDeclaration = ""; if (_mapping.TenancyStyle == TenancyStyle.Conjoined) { tenantDeclaration = ", tenant"; } if (_mapping.IsHierarchy()) { method.Frames .Code($@" return new Marten.Generated.{operationType.TypeName} ( {{0}}, Identity({{0}}), {{1}}.Versions.ForType<{_mapping.DocumentType.FullNameInCode()}, {_mapping.IdType.FullNameInCode()}>(), {{2}} {tenantDeclaration} );" , new Use(_mapping.DocumentType), Use.Type<IMartenSession>(), Use.Type<DocumentMapping>()); } else { method.Frames .Code($@" return new Marten.Generated.{operationType.TypeName} ( {{0}}, Identity({{0}}), {{1}}.Versions.ForType<{_mapping.DocumentType.FullNameInCode()}, {_mapping.IdType.FullNameInCode()}>(), {{2}} {tenantDeclaration} );" , new Use(_mapping.DocumentType), Use.Type<IMartenSession>(), Use.Type<DocumentMapping>()); } } } }
// 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.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Input.Events; using osu.Framework.Threading; using osu.Game.Beatmaps; using osu.Game.Graphics.UserInterface; using osu.Game.Tournament.Components; using osu.Game.Tournament.IPC; using osu.Game.Tournament.Models; using osu.Game.Tournament.Screens.Gameplay; using osu.Game.Tournament.Screens.Gameplay.Components; using osuTK; using osuTK.Graphics; using osuTK.Input; namespace osu.Game.Tournament.Screens.MapPool { public class MapPoolScreen : TournamentMatchScreen { private readonly FillFlowContainer<FillFlowContainer<TournamentBeatmapPanel>> mapFlows; [Resolved(canBeNull: true)] private TournamentSceneManager sceneManager { get; set; } private TeamColour pickColour; private ChoiceType pickType; private readonly OsuButton buttonRedBan; private readonly OsuButton buttonBlueBan; private readonly OsuButton buttonRedPick; private readonly OsuButton buttonBluePick; public MapPoolScreen() { InternalChildren = new Drawable[] { new TourneyVideo("mappool") { Loop = true, RelativeSizeAxes = Axes.Both, }, new MatchHeader(), mapFlows = new FillFlowContainer<FillFlowContainer<TournamentBeatmapPanel>> { Y = 160, Spacing = new Vector2(10, 10), Direction = FillDirection.Vertical, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, }, new ControlPanel { Children = new Drawable[] { new TournamentSpriteText { Text = "Current Mode" }, buttonRedBan = new TourneyButton { RelativeSizeAxes = Axes.X, Text = "Red Ban", Action = () => setMode(TeamColour.Red, ChoiceType.Ban) }, buttonBlueBan = new TourneyButton { RelativeSizeAxes = Axes.X, Text = "Blue Ban", Action = () => setMode(TeamColour.Blue, ChoiceType.Ban) }, buttonRedPick = new TourneyButton { RelativeSizeAxes = Axes.X, Text = "Red Pick", Action = () => setMode(TeamColour.Red, ChoiceType.Pick) }, buttonBluePick = new TourneyButton { RelativeSizeAxes = Axes.X, Text = "Blue Pick", Action = () => setMode(TeamColour.Blue, ChoiceType.Pick) }, new ControlPanel.Spacer(), new TourneyButton { RelativeSizeAxes = Axes.X, Text = "Reset", Action = reset }, new ControlPanel.Spacer(), }, } }; } [BackgroundDependencyLoader] private void load(MatchIPCInfo ipc) { ipc.Beatmap.BindValueChanged(beatmapChanged); } private void beatmapChanged(ValueChangedEvent<BeatmapInfo> beatmap) { if (CurrentMatch.Value == null || CurrentMatch.Value.PicksBans.Count(p => p.Type == ChoiceType.Ban) < 2) return; // if bans have already been placed, beatmap changes result in a selection being made autoamtically if (beatmap.NewValue.OnlineBeatmapID != null) addForBeatmap(beatmap.NewValue.OnlineBeatmapID.Value); } private void setMode(TeamColour colour, ChoiceType choiceType) { pickColour = colour; pickType = choiceType; static Color4 setColour(bool active) => active ? Color4.White : Color4.Gray; buttonRedBan.Colour = setColour(pickColour == TeamColour.Red && pickType == ChoiceType.Ban); buttonBlueBan.Colour = setColour(pickColour == TeamColour.Blue && pickType == ChoiceType.Ban); buttonRedPick.Colour = setColour(pickColour == TeamColour.Red && pickType == ChoiceType.Pick); buttonBluePick.Colour = setColour(pickColour == TeamColour.Blue && pickType == ChoiceType.Pick); } private void setNextMode() { const TeamColour roll_winner = TeamColour.Red; //todo: draw from match var nextColour = (CurrentMatch.Value.PicksBans.LastOrDefault()?.Team ?? roll_winner) == TeamColour.Red ? TeamColour.Blue : TeamColour.Red; if (pickType == ChoiceType.Ban && CurrentMatch.Value.PicksBans.Count(p => p.Type == ChoiceType.Ban) >= 2) setMode(pickColour, ChoiceType.Pick); else setMode(nextColour, CurrentMatch.Value.PicksBans.Count(p => p.Type == ChoiceType.Ban) >= 2 ? ChoiceType.Pick : ChoiceType.Ban); } protected override bool OnMouseDown(MouseDownEvent e) { var maps = mapFlows.Select(f => f.FirstOrDefault(m => m.ReceivePositionalInputAt(e.ScreenSpaceMousePosition))); var map = maps.FirstOrDefault(m => m != null); if (map != null) { if (e.Button == MouseButton.Left && map.BeatmapInfo.OnlineID > 0) addForBeatmap(map.BeatmapInfo.OnlineID); else { var existing = CurrentMatch.Value.PicksBans.FirstOrDefault(p => p.BeatmapID == map.BeatmapInfo.OnlineID); if (existing != null) { CurrentMatch.Value.PicksBans.Remove(existing); setNextMode(); } } return true; } return base.OnMouseDown(e); } private void reset() { CurrentMatch.Value.PicksBans.Clear(); setNextMode(); } private ScheduledDelegate scheduledChange; private void addForBeatmap(int beatmapId) { if (CurrentMatch.Value == null) return; if (CurrentMatch.Value.Round.Value.Beatmaps.All(b => b.BeatmapInfo.OnlineBeatmapID != beatmapId)) // don't attempt to add if the beatmap isn't in our pool return; if (CurrentMatch.Value.PicksBans.Any(p => p.BeatmapID == beatmapId)) // don't attempt to add if already exists. return; CurrentMatch.Value.PicksBans.Add(new BeatmapChoice { Team = pickColour, Type = pickType, BeatmapID = beatmapId }); setNextMode(); if (pickType == ChoiceType.Pick && CurrentMatch.Value.PicksBans.Any(i => i.Type == ChoiceType.Pick)) { scheduledChange?.Cancel(); scheduledChange = Scheduler.AddDelayed(() => { sceneManager?.SetScreen(typeof(GameplayScreen)); }, 10000); } } protected override void CurrentMatchChanged(ValueChangedEvent<TournamentMatch> match) { base.CurrentMatchChanged(match); mapFlows.Clear(); if (match.NewValue == null) return; int totalRows = 0; if (match.NewValue.Round.Value != null) { FillFlowContainer<TournamentBeatmapPanel> currentFlow = null; string currentMod = null; int flowCount = 0; foreach (var b in match.NewValue.Round.Value.Beatmaps) { if (currentFlow == null || currentMod != b.Mods) { mapFlows.Add(currentFlow = new FillFlowContainer<TournamentBeatmapPanel> { Spacing = new Vector2(10, 5), Direction = FillDirection.Full, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y }); currentMod = b.Mods; totalRows++; flowCount = 0; } if (++flowCount > 2) { totalRows++; flowCount = 1; } currentFlow.Add(new TournamentBeatmapPanel(b.BeatmapInfo, b.Mods) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Height = 42, }); } } mapFlows.Padding = new MarginPadding(5) { // remove horizontal padding to increase flow width to 3 panels Horizontal = totalRows > 9 ? 0 : 100 }; } } }
using System; using System.Collections.Concurrent; using System.Linq; using ReactiveDomain.Logging; using ReactiveDomain.Util; namespace ReactiveDomain.Transport { public class TcpConnectionMonitor { public static readonly TcpConnectionMonitor Default = new TcpConnectionMonitor(); private static readonly ILogger Log = LogManager.GetLogger("ReactiveDomain"); private readonly object _statsLock = new object(); private readonly ConcurrentDictionary<IMonitoredTcpConnection, ConnectionData> _connections = new ConcurrentDictionary<IMonitoredTcpConnection, ConnectionData>(); private long _sentTotal; private long _receivedTotal; private long _sentSinceLastRun; private long _receivedSinceLastRun; private long _pendingSendOnLastRun; private long _inSendOnLastRun; private long _pendingReceivedOnLastRun; private bool _anySendBlockedOnLastRun; private DateTime _lastUpdateTime; private TcpConnectionMonitor() { } public void Register(IMonitoredTcpConnection connection) { _connections.TryAdd(connection, new ConnectionData(connection)); } public void Unregister(IMonitoredTcpConnection connection) { _connections.TryRemove(connection, out ConnectionData _); } public TcpStats GetTcpStats() { ConnectionData[] connections = _connections.Values.ToArray(); lock (_statsLock) { var stats = AnalyzeConnections(connections, DateTime.UtcNow - _lastUpdateTime); _lastUpdateTime = DateTime.UtcNow; return stats; } } private TcpStats AnalyzeConnections(ConnectionData[] connections, TimeSpan measurePeriod) { _receivedSinceLastRun = 0; _sentSinceLastRun = 0; _pendingSendOnLastRun = 0; _inSendOnLastRun = 0; _pendingReceivedOnLastRun = 0; _anySendBlockedOnLastRun = false; foreach (var connection in connections) { AnalyzeConnection(connection); } var stats = new TcpStats(connections.Length, _sentTotal, _receivedTotal, _sentSinceLastRun, _receivedSinceLastRun, _pendingSendOnLastRun, _inSendOnLastRun, _pendingReceivedOnLastRun, measurePeriod); if (Application.IsDefined(Application.DumpStatistics)) { Log.Info("\n# Total connections: {0,3}. Out: {1:0.00}b/s In: {2:0.00}b/s Pending Send: {3} " + "In Send: {4} Pending Received: {5} Measure Time: {6}", stats.Connections, stats.SendingSpeed, stats.ReceivingSpeed, stats.PendingSend, stats.InSend, stats.PendingSend, stats.MeasureTime); } return stats; } private void AnalyzeConnection(ConnectionData connectionData) { var connection = connectionData.Connection; if (!connection.IsInitialized) return; if (connection.IsFaulted) { Log.Info("# {0} is faulted", connection); return; } UpdateStatistics(connectionData); CheckPendingReceived(connection); CheckPendingSend(connection); CheckMissingSendCallback(connectionData, connection); CheckMissingReceiveCallback(connectionData, connection); } private void UpdateStatistics(ConnectionData connectionData) { var connection = connectionData.Connection; long totalBytesSent = connection.TotalBytesSent; long totalBytesReceived = connection.TotalBytesReceived; long pendingSend = connection.PendingSendBytes; long inSend = connection.InSendBytes; long pendingReceived = connection.PendingReceivedBytes; _sentSinceLastRun += totalBytesSent - connectionData.LastTotalBytesSent; _receivedSinceLastRun += totalBytesReceived - connectionData.LastTotalBytesReceived; _sentTotal += _sentSinceLastRun; _receivedTotal += _sentSinceLastRun; _pendingSendOnLastRun += pendingSend; _inSendOnLastRun += inSend; _pendingReceivedOnLastRun = pendingReceived; connectionData.LastTotalBytesSent = totalBytesSent; connectionData.LastTotalBytesReceived = totalBytesReceived; } private static void CheckMissingReceiveCallback(ConnectionData connectionData, IMonitoredTcpConnection connection) { bool inReceive = connection.InReceive; bool isReadyForReceive = connection.IsReadyForReceive; DateTime? lastReceiveStarted = connection.LastReceiveStarted; int sinceLastReceive = (int)(DateTime.UtcNow - lastReceiveStarted.GetValueOrDefault()).TotalMilliseconds; bool missingReceiveCallback = inReceive && isReadyForReceive && sinceLastReceive > 500; if (missingReceiveCallback && connectionData.LastMissingReceiveCallBack) { Log.Error("# {0} {1}ms since last Receive started. No completion callback received, but socket status is READY_FOR_RECEIVE", connection, sinceLastReceive); } connectionData.LastMissingReceiveCallBack = missingReceiveCallback; } private void CheckMissingSendCallback(ConnectionData connectionData, IMonitoredTcpConnection connection) { // snapshot all data? bool inSend = connection.InSend; bool isReadyForSend = connection.IsReadyForSend; DateTime? lastSendStarted = connection.LastSendStarted; int inSendBytes = connection.InSendBytes; int sinceLastSend = (int)(DateTime.UtcNow - lastSendStarted.GetValueOrDefault()).TotalMilliseconds; bool missingSendCallback = inSend && isReadyForSend && sinceLastSend > 500; if (missingSendCallback && connectionData.LastMissingSendCallBack) { // _anySendBlockedOnLastRun = true; Log.Error( "# {0} {1}ms since last send started. No completion callback received, but socket status is READY_FOR_SEND. In send: {2}", connection, sinceLastSend, inSendBytes); } connectionData.LastMissingSendCallBack = missingSendCallback; } private static void CheckPendingSend(IMonitoredTcpConnection connection) { int pendingSendBytes = connection.PendingSendBytes; if (pendingSendBytes > 128 * 1024) { Log.Info("# {0} {1}kb pending send", connection, pendingSendBytes / 1024); } } private static void CheckPendingReceived(IMonitoredTcpConnection connection) { int pendingReceivedBytes = connection.PendingReceivedBytes; if (pendingReceivedBytes > 128 * 1024) { Log.Info("# {0} {1}kb are not dispatched", connection, pendingReceivedBytes / 1024); } } public bool IsSendBlocked() { return _anySendBlockedOnLastRun; } private class ConnectionData { public readonly IMonitoredTcpConnection Connection; public bool LastMissingSendCallBack; public bool LastMissingReceiveCallBack; public long LastTotalBytesSent; public long LastTotalBytesReceived; public ConnectionData(IMonitoredTcpConnection connection) { Connection = connection; } } } }
// 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.Contracts; using System.Collections; using System.Globalization; using System.Threading; namespace System.Text { // This class overrides Encoding with the things we need for our NLS Encodings // // All of the GetBytes/Chars GetByte/CharCount methods are just wrappers for the pointer // plus decoder/encoder method that is our real workhorse. Note that this is an internal // class, so our public classes cannot derive from this class. Because of this, all of the // GetBytes/Chars GetByte/CharCount wrapper methods are duplicated in all of our public // encodings, which currently include: // // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, & UnicodeEncoding // // So if you change the wrappers in this class, you must change the wrappers in the other classes // as well because they should have the same behavior. // [System.Runtime.InteropServices.ComVisible(true)] internal abstract class EncodingNLS : Encoding { protected EncodingNLS(int codePage) : base(codePage) { } // Returns the number of bytes required to encode a range of characters in // a character array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetByteCount(char[] chars, int index, int count) { // Validate input parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // If no input, return 0, avoid fixed empty array problem if (chars.Length == 0) return 0; // Just call the pointer version fixed (char* pChars = chars) return GetByteCount(pChars + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetByteCount(String s) { // Validate input if (s == null) throw new ArgumentNullException("s"); Contract.EndContractBlock(); fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecurityCritical] // auto-generated public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Call it with empty encoder return GetByteCount(chars, count, null); } // Parent method is safe. // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) throw new ArgumentNullException((s == null ? "s" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (s.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("s", SR.ArgumentOutOfRange_IndexCount); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = s) fixed (byte* pBytes = bytes) return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); // If nothing to encode return 0, avoid fixed problem if (chars.Length == 0) return 0; // Just call pointer version int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = chars) fixed (byte* pBytes = bytes) // Remember that byteCount is # to decode, not size of array. return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecurityCritical] // auto-generated public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); return GetBytes(chars, charCount, bytes, byteCount, null); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetCharCount(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // If no input just return 0, fixed doesn't like 0 length arrays if (bytes.Length == 0) return 0; // Just call pointer version fixed (byte* pBytes = bytes) return GetCharCount(pBytes + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecurityCritical] // auto-generated public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); return GetCharCount(bytes, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); // If no input, return 0 & avoid fixed problem if (bytes.Length == 0) return 0; // Just call pointer version int charCount = chars.Length - charIndex; // Fixed doesn't like empty arrays if (chars.Length == 0) chars = new char[1]; fixed (byte* pBytes = bytes) fixed (char* pChars = chars) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecurityCritical] // auto-generated public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); return GetChars(bytes, byteCount, chars, charCount, null); } // Returns a string containing the decoded representation of a range of // bytes in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe String GetString(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // Avoid problems with empty input buffer if (bytes.Length == 0) return String.Empty; fixed (byte* pBytes = bytes) return String.CreateStringFromEncoding( pBytes + index, count, this); } public override Decoder GetDecoder() { return new DecoderNLS(this); } public override Encoder GetEncoder() { return new EncoderNLS(this); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.GrainDirectory; using Orleans.SystemTargetInterfaces; using OutcomeState = Orleans.Runtime.GrainDirectory.GlobalSingleInstanceResponseOutcome.OutcomeState; using Orleans.Runtime.MultiClusterNetwork; namespace Orleans.Runtime.GrainDirectory { /// <summary> /// A grain registrar that coordinates the directory entries for a grain between /// all the clusters in the current multi-cluster configuration. /// It uses the global-single-instance protocol to ensure that there is eventually /// only a single owner for each grain. When a new grain is registered, all other clusters are /// contacted to see if an activation already exists. If so, a pointer to that activation is /// stored in the directory and returned. Otherwise, the new activation is registered. /// The protocol uses special states to track the status of directory entries, as listed in /// <see cref="GrainDirectoryEntryStatus"/>. /// </summary> internal class GlobalSingleInstanceRegistrar : IGrainRegistrar<GlobalSingleInstanceRegistration> { private readonly int numRetries; private readonly IInternalGrainFactory grainFactory; private readonly ILogger logger; private readonly GrainDirectoryPartition directoryPartition; private readonly GlobalSingleInstanceActivationMaintainer gsiActivationMaintainer; private readonly IMultiClusterOracle multiClusterOracle; private readonly bool hasMultiClusterNetwork; private readonly string clusterId; public GlobalSingleInstanceRegistrar( LocalGrainDirectory localDirectory, ILogger<GlobalSingleInstanceRegistrar> logger, GlobalSingleInstanceActivationMaintainer gsiActivationMaintainer, IInternalGrainFactory grainFactory, IMultiClusterOracle multiClusterOracle, ILocalSiloDetails siloDetails, IOptions<MultiClusterOptions> multiClusterOptions) { this.directoryPartition = localDirectory.DirectoryPartition; this.logger = logger; this.gsiActivationMaintainer = gsiActivationMaintainer; this.numRetries = multiClusterOptions.Value.GlobalSingleInstanceNumberRetries; this.grainFactory = grainFactory; this.multiClusterOracle = multiClusterOracle; this.hasMultiClusterNetwork = multiClusterOptions.Value.HasMultiClusterNetwork; this.clusterId = siloDetails.ClusterId; } public bool IsSynchronous { get { return false; } } public AddressAndTag Register(ActivationAddress address, bool singleActivation) { throw new InvalidOperationException(); } public void Unregister(ActivationAddress address, UnregistrationCause cause) { throw new InvalidOperationException(); } public void Delete(GrainId gid) { throw new InvalidOperationException(); } public async Task<AddressAndTag> RegisterAsync(ActivationAddress address, bool singleActivation) { if (!singleActivation) throw new OrleansException("global single instance protocol is incompatible with using multiple activations"); if (!this.hasMultiClusterNetwork) { // no multicluster network. Go to owned state directly. return directoryPartition.AddSingleActivation(address.Grain, address.Activation, address.Silo, GrainDirectoryEntryStatus.Owned); } // examine the multicluster configuration var config = this.multiClusterOracle.GetMultiClusterConfiguration(); if (config == null || !config.Clusters.Contains(this.clusterId)) { // we are not joined to the cluster yet/anymore. Go to doubtful state directly. gsiActivationMaintainer.TrackDoubtfulGrain(address.Grain); return directoryPartition.AddSingleActivation(address.Grain, address.Activation, address.Silo, GrainDirectoryEntryStatus.Doubtful); } var remoteClusters = config.Clusters.Where(id => id != this.clusterId).ToList(); // Try to go into REQUESTED_OWNERSHIP state var myActivation = directoryPartition.AddSingleActivation(address.Grain, address.Activation, address.Silo, GrainDirectoryEntryStatus.RequestedOwnership); if (!myActivation.Address.Equals(address)) { //This implies that the registration already existed in some state? return the existing activation. return myActivation; } // Do request rounds until successful or we run out of retries int retries = numRetries; while (retries-- > 0) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("GSIP:Req {0} Round={1} Act={2}", address.Grain.ToString(), numRetries - retries, myActivation.Address.ToString()); var outcome = await SendRequestRound(address, remoteClusters); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("GSIP:End {0} Round={1} Outcome={2}", address.Grain.ToString(), numRetries - retries, outcome); switch (outcome.State) { case OutcomeState.RemoteOwner: case OutcomeState.RemoteOwnerLikely: { directoryPartition.CacheOrUpdateRemoteClusterRegistration(address.Grain, address.Activation, outcome.RemoteOwnerAddress.Address); return outcome.RemoteOwnerAddress; } case OutcomeState.Succeed: { if (directoryPartition.UpdateClusterRegistrationStatus(address.Grain, address.Activation, GrainDirectoryEntryStatus.Owned, GrainDirectoryEntryStatus.RequestedOwnership)) return myActivation; else break; // concurrently moved to RACE_LOSER } case OutcomeState.Inconclusive: { break; } } // we were not successful, reread state to determine what is going on int version; var mcstatus = directoryPartition.TryGetActivation(address.Grain, out address, out version); if (mcstatus == GrainDirectoryEntryStatus.RequestedOwnership) { // we failed because of inconclusive answers. Stay in this state for retry. } else if (mcstatus == GrainDirectoryEntryStatus.RaceLoser) { // we failed because an external request moved us to RACE_LOSER. Go back to REQUESTED_OWNERSHIP for retry var success = directoryPartition.UpdateClusterRegistrationStatus(address.Grain, address.Activation, GrainDirectoryEntryStatus.RequestedOwnership, GrainDirectoryEntryStatus.RaceLoser); if (!success) ProtocolError(address, "unable to transition from RACE_LOSER to REQUESTED_OWNERSHIP"); // do not wait before retrying because there is a dominant remote request active so we can probably complete quickly } else { ProtocolError(address, "unhandled protocol state"); } } // we are done with the quick retries. Now we go into doubtful state, which means slower retries. var ok = directoryPartition.UpdateClusterRegistrationStatus(address.Grain, address.Activation, GrainDirectoryEntryStatus.Doubtful, GrainDirectoryEntryStatus.RequestedOwnership); if (!ok) ProtocolError(address, "unable to transition into doubtful"); this.gsiActivationMaintainer.TrackDoubtfulGrain(address.Grain); return myActivation; } private void ProtocolError(ActivationAddress address, string msg) { logger.Error((int)ErrorCode.GlobalSingleInstance_ProtocolError, string.Format("GSIP:Req {0} PROTOCOL ERROR {1}", address.Grain.ToString(), msg)); } public Task UnregisterAsync(List<ActivationAddress> addresses, UnregistrationCause cause) { List<ActivationAddress> formerActivationsInThisCluster = null; foreach (var address in addresses) { IActivationInfo existingAct; bool wasRemoved; directoryPartition.RemoveActivation(address.Grain, address.Activation, cause, out existingAct, out wasRemoved); if (existingAct == null) { logger.Trace("GSIP:Unr {0} {1} ignored", cause, address); } else if (!wasRemoved) { logger.Trace("GSIP:Unr {0} {1} too fresh", cause, address); } else if (existingAct.RegistrationStatus == GrainDirectoryEntryStatus.Owned || existingAct.RegistrationStatus == GrainDirectoryEntryStatus.Doubtful) { logger.Trace("GSIP:Unr {0} {1} broadcast ({2})", cause, address, existingAct.RegistrationStatus); if (formerActivationsInThisCluster == null) formerActivationsInThisCluster = new List<ActivationAddress>(); formerActivationsInThisCluster.Add(address); } else { logger.Trace("GSIP:Unr {0} {1} removed ({2})", cause, address, existingAct.RegistrationStatus); } } if (formerActivationsInThisCluster == null) return Task.CompletedTask; if (!this.hasMultiClusterNetwork) return Task.CompletedTask; // single cluster - no broadcast required // we must also remove cached references to former activations in this cluster // from remote clusters; thus, we broadcast the unregistration var myClusterId = this.clusterId; // target clusters in current configuration, other than this one var remoteClusters = this.multiClusterOracle.GetMultiClusterConfiguration().Clusters .Where(id => id != myClusterId).ToList(); var tasks = new List<Task>(); foreach (var remoteCluster in remoteClusters) { // find gateway var gossipOracle = this.multiClusterOracle; var clusterGatewayAddress = gossipOracle.GetRandomClusterGateway(remoteCluster); if (clusterGatewayAddress != null) { var clusterGrainDir = this.grainFactory.GetSystemTarget<IClusterGrainDirectory>(Constants.ClusterDirectoryServiceId, clusterGatewayAddress); // try to send request tasks.Add(clusterGrainDir.ProcessDeactivations(formerActivationsInThisCluster)); } } return Task.WhenAll(tasks); } public void InvalidateCache(ActivationAddress address) { IActivationInfo existingAct; bool wasRemoved; directoryPartition.RemoveActivation(address.Grain, address.Activation, UnregistrationCause.CacheInvalidation, out existingAct, out wasRemoved); if (!wasRemoved) { logger.Trace("GSIP:Inv {0} ignored", address); } else { logger.Trace("GSIP:Inv {0} removed ({1})", address, existingAct.RegistrationStatus); } } public Task DeleteAsync(GrainId gid) { directoryPartition.RemoveGrain(gid); if (!this.hasMultiClusterNetwork) return Task.CompletedTask; // single cluster - no broadcast required // broadcast deletion to all other clusters var myClusterId = this.clusterId; // target ALL clusters, not just clusters in current configuration var remoteClusters = this.multiClusterOracle.GetActiveClusters() .Where(id => id != myClusterId).ToList(); var tasks = new List<Task>(); foreach (var remoteCluster in remoteClusters) { // find gateway var gossipOracle = this.multiClusterOracle; var clusterGatewayAddress = gossipOracle.GetRandomClusterGateway(remoteCluster); if (clusterGatewayAddress != null) { var clusterGrainDir = this.grainFactory.GetSystemTarget<IClusterGrainDirectory>(Constants.ClusterDirectoryServiceId, clusterGatewayAddress); // try to send request tasks.Add(clusterGrainDir.ProcessDeletion(gid)); } } return Task.WhenAll(tasks); } public Task<GlobalSingleInstanceResponseOutcome> SendRequestRound(ActivationAddress address, List<string> remoteClusters) { // array that holds the responses var responses = new Task<RemoteClusterActivationResponse>[remoteClusters.Count]; // send all requests for (int i = 0; i < responses.Length; i++) responses[i] = SendRequest(address.Grain, remoteClusters[i]); // response processor return GlobalSingleInstanceResponseTracker.GetOutcomeAsync(responses, address.Grain, logger); } /// <summary> /// Send GSI protocol request to the given remote cluster /// </summary> /// <param name="grain">The grainId of the grain being activated</param> /// <param name="remotecluster">The remote cluster name to send the request to.</param> public async Task<RemoteClusterActivationResponse> SendRequest(GrainId grain, string remotecluster) { try { // find gateway var gossiporacle = this.multiClusterOracle; var clusterGatewayAddress = gossiporacle.GetRandomClusterGateway(remotecluster); var clusterGrainDir = this.grainFactory.GetSystemTarget<IClusterGrainDirectory>(Constants.ClusterDirectoryServiceId, clusterGatewayAddress); // try to send request return await clusterGrainDir.ProcessActivationRequest(grain, this.clusterId, 0); } catch (Exception ex) { return new RemoteClusterActivationResponse(ActivationResponseStatus.Faulted) { ResponseException = ex }; } } } }
using Android.Content; using Android.Hardware; using Android.Runtime; using Android.Util; using Android.Views; using System; using System.Collections.Generic; #pragma warning disable 618 namespace BuildIt.AR.Android.Controls { [Preserve(AllMembers = true)] public class CameraPreview : ViewGroup, ISurfaceHolderCallback { string TAG = "CameraPreview"; SurfaceView mSurfaceView; ISurfaceHolder mHolder; IList<Camera.Size> mSupportedPreviewSizes; Camera camera; public Camera PreviewCamera { get => camera; set { camera = value; if (camera == null) { return; } mSupportedPreviewSizes = PreviewCamera.GetParameters().SupportedPreviewSizes; RequestLayout(); } } public CameraPreview(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { } public CameraPreview(Context context) : base(context) { } public CameraPreview(Context context, IAttributeSet attrs) : base(context, attrs) { } public CameraPreview(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr) { } public CameraPreview(Context context, IAttributeSet attrs, int defStyleAttr, int defStyleRes) : base(context, attrs, defStyleAttr, defStyleRes) { } public void SurfaceCreated(ISurfaceHolder holder) { // The Surface has been created, acquire the camera and tell it where // to draw. try { PreviewCamera?.SetPreviewDisplay(holder); } catch (Java.IO.IOException exception) { Log.Error(TAG, "IOException caused by setPreviewDisplay()", exception); } } public void SetPreviewDisplay() { if (mHolder != null) { PreviewCamera?.SetPreviewDisplay(mHolder); } } public void SurfaceDestroyed(ISurfaceHolder holder) { // Surface will be destroyed when we return, so stop the preview. PreviewCamera?.StopPreview(); } protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec) { try { // We purposely disregard child measurements because act as a // wrapper to a SurfaceView that centers the camera preview instead // of stretching it. int width = ResolveSize(SuggestedMinimumWidth, widthMeasureSpec); int height = ResolveSize(SuggestedMinimumHeight, heightMeasureSpec); SetMeasuredDimension(width, height); if (mSupportedPreviewSizes != null) { GetOptimalPreviewSize(mSupportedPreviewSizes, width, height); } } catch (Exception ex) { ex.LogError(); } } protected override void OnLayout(bool changed, int l, int t, int r, int b) { try { if (changed && ChildCount > 0) { View child = GetChildAt(0); int width = r - l; int height = b - t; child.Layout(0, 0, width, height); } } catch (Exception ex) { ex.LogError(); } } private Camera.Size GetOptimalPreviewSize(IList<Camera.Size> sizes, int w, int h) { try { const double ASPECT_TOLERANCE = 0.1; double targetRatio = (double)w / h; if (sizes == null) { return null; } Camera.Size optimalSize = null; double minDiff = Double.MaxValue; int targetHeight = h; // Try to find an size match aspect ratio and size foreach (Camera.Size size in sizes) { double ratio = (double)size.Width / size.Height; if (Math.Abs(ratio - targetRatio) > ASPECT_TOLERANCE) { continue; } if (Math.Abs(size.Height - targetHeight) < minDiff) { optimalSize = size; minDiff = Math.Abs(size.Height - targetHeight); } } // Cannot find the one match the aspect ratio, ignore the requirement if (optimalSize == null) { minDiff = Double.MaxValue; foreach (Camera.Size size in sizes) { if (Math.Abs(size.Height - targetHeight) < minDiff) { optimalSize = size; minDiff = Math.Abs(size.Height - targetHeight); } } } return optimalSize; } catch (Exception ex) { ex.LogError(); } return null; } public void SurfaceChanged(ISurfaceHolder holder, global::Android.Graphics.Format format, int w, int h) { try { // Now that the size is known, set up the camera parameters and begin // the preview. // Camera.Parameters parameters = PreviewCamera.GetParameters(); // parameters.SetPreviewSize(mPreviewSize.Width, mPreviewSize.Height); RequestLayout(); // PreviewCamera.SetParameters(parameters); PreviewCamera.StartPreview(); } catch (Exception ex) { ex.LogError(); } } public void InitPreview(Context context) { try { mSurfaceView = new SurfaceView(context); AddView(mSurfaceView); // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = mSurfaceView.Holder; mHolder.AddCallback(this); mHolder.SetType(SurfaceType.PushBuffers); } catch (Exception ex) { ex.LogError(); } } } }
namespace java.nio.channels { [global::MonoJavaBridge.JavaClass(typeof(global::java.nio.channels.SocketChannel_))] public abstract partial class SocketChannel : java.nio.channels.spi.AbstractSelectableChannel, ByteChannel, ScatteringByteChannel, GatheringByteChannel { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static SocketChannel() { InitJNI(); } protected SocketChannel(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _write14582; public virtual long write(java.nio.ByteBuffer[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::java.nio.channels.SocketChannel._write14582, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.nio.channels.SocketChannel.staticClass, global::java.nio.channels.SocketChannel._write14582, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _write14583; public abstract int write(java.nio.ByteBuffer arg0); internal static global::MonoJavaBridge.MethodId _write14584; public abstract long write(java.nio.ByteBuffer[] arg0, int arg1, int arg2); internal static global::MonoJavaBridge.MethodId _read14585; public abstract long read(java.nio.ByteBuffer[] arg0, int arg1, int arg2); internal static global::MonoJavaBridge.MethodId _read14586; public virtual long read(java.nio.ByteBuffer[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::java.nio.channels.SocketChannel._read14586, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.nio.channels.SocketChannel.staticClass, global::java.nio.channels.SocketChannel._read14586, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _read14587; public abstract int read(java.nio.ByteBuffer arg0); internal static global::MonoJavaBridge.MethodId _open14588; public static global::java.nio.channels.SocketChannel open(java.net.SocketAddress arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.nio.channels.SocketChannel.staticClass, global::java.nio.channels.SocketChannel._open14588, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.channels.SocketChannel; } internal static global::MonoJavaBridge.MethodId _open14589; public static global::java.nio.channels.SocketChannel open() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.nio.channels.SocketChannel.staticClass, global::java.nio.channels.SocketChannel._open14589)) as java.nio.channels.SocketChannel; } internal static global::MonoJavaBridge.MethodId _connect14590; public abstract bool connect(java.net.SocketAddress arg0); internal static global::MonoJavaBridge.MethodId _socket14591; public abstract global::java.net.Socket socket(); internal static global::MonoJavaBridge.MethodId _isConnected14592; public abstract bool isConnected(); internal static global::MonoJavaBridge.MethodId _validOps14593; public sealed override int validOps() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.nio.channels.SocketChannel._validOps14593); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.channels.SocketChannel.staticClass, global::java.nio.channels.SocketChannel._validOps14593); } internal static global::MonoJavaBridge.MethodId _isConnectionPending14594; public abstract bool isConnectionPending(); internal static global::MonoJavaBridge.MethodId _finishConnect14595; public abstract bool finishConnect(); internal static global::MonoJavaBridge.MethodId _SocketChannel14596; protected SocketChannel(java.nio.channels.spi.SelectorProvider arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.nio.channels.SocketChannel.staticClass, global::java.nio.channels.SocketChannel._SocketChannel14596, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.nio.channels.SocketChannel.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/channels/SocketChannel")); global::java.nio.channels.SocketChannel._write14582 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel.staticClass, "write", "([Ljava/nio/ByteBuffer;)J"); global::java.nio.channels.SocketChannel._write14583 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel.staticClass, "write", "(Ljava/nio/ByteBuffer;)I"); global::java.nio.channels.SocketChannel._write14584 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel.staticClass, "write", "([Ljava/nio/ByteBuffer;II)J"); global::java.nio.channels.SocketChannel._read14585 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel.staticClass, "read", "([Ljava/nio/ByteBuffer;II)J"); global::java.nio.channels.SocketChannel._read14586 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel.staticClass, "read", "([Ljava/nio/ByteBuffer;)J"); global::java.nio.channels.SocketChannel._read14587 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel.staticClass, "read", "(Ljava/nio/ByteBuffer;)I"); global::java.nio.channels.SocketChannel._open14588 = @__env.GetStaticMethodIDNoThrow(global::java.nio.channels.SocketChannel.staticClass, "open", "(Ljava/net/SocketAddress;)Ljava/nio/channels/SocketChannel;"); global::java.nio.channels.SocketChannel._open14589 = @__env.GetStaticMethodIDNoThrow(global::java.nio.channels.SocketChannel.staticClass, "open", "()Ljava/nio/channels/SocketChannel;"); global::java.nio.channels.SocketChannel._connect14590 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel.staticClass, "connect", "(Ljava/net/SocketAddress;)Z"); global::java.nio.channels.SocketChannel._socket14591 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel.staticClass, "socket", "()Ljava/net/Socket;"); global::java.nio.channels.SocketChannel._isConnected14592 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel.staticClass, "isConnected", "()Z"); global::java.nio.channels.SocketChannel._validOps14593 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel.staticClass, "validOps", "()I"); global::java.nio.channels.SocketChannel._isConnectionPending14594 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel.staticClass, "isConnectionPending", "()Z"); global::java.nio.channels.SocketChannel._finishConnect14595 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel.staticClass, "finishConnect", "()Z"); global::java.nio.channels.SocketChannel._SocketChannel14596 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel.staticClass, "<init>", "(Ljava/nio/channels/spi/SelectorProvider;)V"); } } [global::MonoJavaBridge.JavaProxy(typeof(global::java.nio.channels.SocketChannel))] public sealed partial class SocketChannel_ : java.nio.channels.SocketChannel { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static SocketChannel_() { InitJNI(); } internal SocketChannel_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _write14597; public override int write(java.nio.ByteBuffer arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.nio.channels.SocketChannel_._write14597, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.channels.SocketChannel_.staticClass, global::java.nio.channels.SocketChannel_._write14597, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _write14598; public override long write(java.nio.ByteBuffer[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::java.nio.channels.SocketChannel_._write14598, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.nio.channels.SocketChannel_.staticClass, global::java.nio.channels.SocketChannel_._write14598, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _read14599; public override long read(java.nio.ByteBuffer[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::java.nio.channels.SocketChannel_._read14599, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.nio.channels.SocketChannel_.staticClass, global::java.nio.channels.SocketChannel_._read14599, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _read14600; public override int read(java.nio.ByteBuffer arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.nio.channels.SocketChannel_._read14600, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.channels.SocketChannel_.staticClass, global::java.nio.channels.SocketChannel_._read14600, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _connect14601; public override bool connect(java.net.SocketAddress arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.nio.channels.SocketChannel_._connect14601, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.nio.channels.SocketChannel_.staticClass, global::java.nio.channels.SocketChannel_._connect14601, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _socket14602; public override global::java.net.Socket socket() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.channels.SocketChannel_._socket14602)) as java.net.Socket; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.channels.SocketChannel_.staticClass, global::java.nio.channels.SocketChannel_._socket14602)) as java.net.Socket; } internal static global::MonoJavaBridge.MethodId _isConnected14603; public override bool isConnected() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.nio.channels.SocketChannel_._isConnected14603); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.nio.channels.SocketChannel_.staticClass, global::java.nio.channels.SocketChannel_._isConnected14603); } internal static global::MonoJavaBridge.MethodId _isConnectionPending14604; public override bool isConnectionPending() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.nio.channels.SocketChannel_._isConnectionPending14604); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.nio.channels.SocketChannel_.staticClass, global::java.nio.channels.SocketChannel_._isConnectionPending14604); } internal static global::MonoJavaBridge.MethodId _finishConnect14605; public override bool finishConnect() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.nio.channels.SocketChannel_._finishConnect14605); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.nio.channels.SocketChannel_.staticClass, global::java.nio.channels.SocketChannel_._finishConnect14605); } internal static global::MonoJavaBridge.MethodId _implCloseSelectableChannel14606; protected override void implCloseSelectableChannel() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.nio.channels.SocketChannel_._implCloseSelectableChannel14606); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.nio.channels.SocketChannel_.staticClass, global::java.nio.channels.SocketChannel_._implCloseSelectableChannel14606); } internal static global::MonoJavaBridge.MethodId _implConfigureBlocking14607; protected override void implConfigureBlocking(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.nio.channels.SocketChannel_._implConfigureBlocking14607, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.nio.channels.SocketChannel_.staticClass, global::java.nio.channels.SocketChannel_._implConfigureBlocking14607, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.nio.channels.SocketChannel_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/channels/SocketChannel")); global::java.nio.channels.SocketChannel_._write14597 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel_.staticClass, "write", "(Ljava/nio/ByteBuffer;)I"); global::java.nio.channels.SocketChannel_._write14598 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel_.staticClass, "write", "([Ljava/nio/ByteBuffer;II)J"); global::java.nio.channels.SocketChannel_._read14599 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel_.staticClass, "read", "([Ljava/nio/ByteBuffer;II)J"); global::java.nio.channels.SocketChannel_._read14600 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel_.staticClass, "read", "(Ljava/nio/ByteBuffer;)I"); global::java.nio.channels.SocketChannel_._connect14601 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel_.staticClass, "connect", "(Ljava/net/SocketAddress;)Z"); global::java.nio.channels.SocketChannel_._socket14602 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel_.staticClass, "socket", "()Ljava/net/Socket;"); global::java.nio.channels.SocketChannel_._isConnected14603 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel_.staticClass, "isConnected", "()Z"); global::java.nio.channels.SocketChannel_._isConnectionPending14604 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel_.staticClass, "isConnectionPending", "()Z"); global::java.nio.channels.SocketChannel_._finishConnect14605 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel_.staticClass, "finishConnect", "()Z"); global::java.nio.channels.SocketChannel_._implCloseSelectableChannel14606 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel_.staticClass, "implCloseSelectableChannel", "()V"); global::java.nio.channels.SocketChannel_._implConfigureBlocking14607 = @__env.GetMethodIDNoThrow(global::java.nio.channels.SocketChannel_.staticClass, "implConfigureBlocking", "(Z)V"); } } }
#region copyright // VZF // Copyright (C) 2014-2016 Vladimir Zakharov // // http://www.code.coolhobby.ru/ // File profileprovider.cs created on 2.6.2015 in 6:31 AM. // Last changed on 5.21.2016 in 1:13 PM. // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // #endregion namespace YAF.Providers.Profile { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Web.Profile; using VZF.Data.Common; using VZF.Data.Postgre.Mappers; using VZF.Data.Utils; using YAF.Core; using YAF.Providers.Utils; using YAF.Types.Interfaces; /// <summary> /// YAF Custom Profile Provider /// </summary> public partial class PgProfileProvider : ProfileProvider { #region Constants and Fields /// <summary> /// The conn str app key name. /// </summary> private static string _connStrAppKeyName = "YafProfileConnectionString"; /// <summary> /// The _connection string. /// </summary> private static string _connectionString; /// <summary> /// The _conn str name. /// </summary> private string _connStrName; /// <summary> /// The _properties setup. /// </summary> private bool _propertiesSetup = false; /// <summary> /// The _property lock. /// </summary> private object _propertyLock = new object(); /// <summary> /// The _settings columns list. /// </summary> private List<SettingsPropertyColumn> _settingsColumnsList = new List<SettingsPropertyColumn>(); #endregion #region Override Public Properties /// <summary> /// Gets the Connection String App Key Name. /// </summary> public static string ConnStrAppKeyName { get { return _connStrAppKeyName; } } /// <summary> /// Gets the Connection String App Key Name. /// </summary> public static string ConnectionString { get { return _connectionString; } set { _connectionString = value; } } /// <summary> /// Gets the Connection String App Key Name. /// </summary> public static string ConnectionStringName { get; set; } #endregion #region Common Properties /// <summary> /// Gets UserProfileCache. /// </summary> private ConcurrentDictionary<string, SettingsPropertyValueCollection> _userProfileCache = null; /// <summary> /// Gets UserProfileCache. /// </summary> private ConcurrentDictionary<string, SettingsPropertyValueCollection> UserProfileCache { get { string key = this.GenerateCacheKey("UserProfileDictionary"); return this._userProfileCache ?? (this._userProfileCache = YafContext.Current.Get<IObjectStore>().GetOrSet( key, () => new ConcurrentDictionary<string, SettingsPropertyValueCollection>())); } } #endregion /// <summary> /// The delete from profile cache if exists. /// </summary> /// <param name="key"> /// The key to remove. /// </param> private void DeleteFromProfileCacheIfExists(string key) { SettingsPropertyValueCollection collection; this.UserProfileCache.TryRemove(key, out collection); } /// <summary> /// The clear user profile cache. /// </summary> private void ClearUserProfileCache() { YafContext.Current.Get<IObjectStore>().Remove(this.GenerateCacheKey("UserProfileDictionary")); } /// <summary> /// The generate cache key. /// </summary> /// <param name="name"> /// The name. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> private string GenerateCacheKey(string name) { return string.Format("PgProfileProvider-{0}-{1}", name, this.ApplicationName); } #region Overriden Public Methods /// <summary> /// The load from property collection. /// </summary> /// <param name="collection"> /// The collection. /// </param> protected void LoadFromPropertyCollection(SettingsPropertyCollection collection) { if (this._propertiesSetup) { return; } lock (this._propertyLock) { // clear it out just in case something is still in there... this._settingsColumnsList.Clear(); } // validiate all the properties and populate the internal settings collection foreach (SettingsProperty property in collection) { DbType dbType; int size; // parse custom provider data... this.GetDbTypeAndSizeFromString(property.Attributes["CustomProviderData"].ToString(), out dbType, out size); // default the size to 256 if no size is specified // default the size to 256 if no size is specified if (dbType == DbType.String && size == -1) { size = 256; } this._settingsColumnsList.Add(new SettingsPropertyColumn(property, dbType, size)); } // sync profile table structure with the db... DataTable structure = Db.__GetProfileStructure(ConnectionStringName); // verify all the columns are there... foreach (SettingsPropertyColumn column in this._settingsColumnsList) { // see if this column exists if (!structure.Columns.Contains(column.Settings.Name)) { // if not, create it... Db.__AddProfileColumn(ConnectionStringName, column.Settings.Name, column.DataType.ToString(), column.Size); } } // it's setup now... this._propertiesSetup = true; } /// <summary> /// The load from property value collection. /// </summary> /// <param name="collection"> /// The collection. /// </param> protected void LoadFromPropertyValueCollection(SettingsPropertyValueCollection collection) { if (_propertiesSetup) { return; } // clear it out just in case something is still in there... this._settingsColumnsList.Clear(); // validiate all the properties and populate the internal settings collection foreach (SettingsPropertyValue value in collection) { DbType dbType; int size; // parse custom provider data... this.GetDbTypeAndSizeFromString(value.Property.Attributes ["CustomProviderData"].ToString(), out dbType, out size ); if (dbType == DbType.String && size == -1) { size = 256; } this._settingsColumnsList.Add( new SettingsPropertyColumn(value.Property, dbType, size)); } // sync profile table structure with the db... DataTable structure = Db.__GetProfileStructure(ConnectionStringName); // verify all the columns are there... foreach (SettingsPropertyColumn column in this._settingsColumnsList) { // see if this column exists if (!structure.Columns.Contains(column.Settings.Name)) { // if not, create it... Db.__AddProfileColumn( ConnectionStringName, column.Settings.Name, column.DataType.ToString(), column.Size); } } // it's setup now... this._propertiesSetup = true; } /// <summary> /// The get db type and size from string. /// </summary> /// <param name="providerData"> /// The provider data. /// </param> /// <param name="dbType"> /// The db type. /// </param> /// <param name="size"> /// The size. /// </param> /// <returns> /// The <see cref="bool"/>. /// </returns> /// <exception cref="ArgumentException"> /// </exception> private bool GetDbTypeAndSizeFromString( string providerData, out DbType dbType, out int size ) { size = -1; dbType = DbType.String; if (string.IsNullOrEmpty(providerData)) { return false; } // split the data string[] chunk = providerData.Split(new[] { ';' }); // first item is the column name... string paramName = DataTypeMappers.FromDbValueMap(chunk[1]); // get the datatype and ignore case... dbType = (DbType)Enum.Parse(typeof(DbType), paramName, true); if (chunk.Length > 2) { // handle size... if (!int.TryParse(chunk[2], out size)) { throw new ArgumentException("Unable to parse as integer: " + chunk[2]); } } return true; } /// <summary> /// The get profile as collection. /// </summary> /// <param name="authenticationOption"> /// The authentication option. /// </param> /// <param name="pageIndex"> /// The page index. /// </param> /// <param name="pageSize"> /// The page size. /// </param> /// <param name="userNameToMatch"> /// The user name to match. /// </param> /// <param name="inactiveSinceDate"> /// The inactive since date. /// </param> /// <param name="totalRecords"> /// The total records. /// </param> /// <returns> /// The <see cref="ProfileInfoCollection"/>. /// </returns> private ProfileInfoCollection GetProfileAsCollection( ProfileAuthenticationOption authenticationOption, int pageIndex, int pageSize, object userNameToMatch, object inactiveSinceDate, out int totalRecords ) { if (authenticationOption == ProfileAuthenticationOption.Anonymous) { ExceptionReporter.ThrowArgument("PROFILE", "NOANONYMOUS"); } if (pageIndex < 0) { ExceptionReporter.ThrowArgument( "PROFILE", "PAGEINDEXTOOSMALL"); } if (pageSize < 1) { ExceptionReporter.ThrowArgument("PROFILE", "PAGESIZETOOSMALL"); } // get all the profiles... // DataSet allProfilesDS = Db.GetProfiles( this.ApplicationName, pageIndex, pageSize, userNameToMatch, inactiveSinceDate ); // create an instance for the profiles... var profiles = new ProfileInfoCollection(); DataTable allProfilesDt = Db.__GetProfiles(ConnectionStringName, this.ApplicationName, pageIndex, pageSize, userNameToMatch, inactiveSinceDate); // DataTable allProfilesDT = allProfilesDS.Tables [0]; // DataTable profilesCountDT = allProfilesDS.Tables [1]; foreach (DataRow profileRow in allProfilesDt.Rows) { string username = profileRow["Username"].ToString(); var lastActivity = DateTime.SpecifyKind(Convert.ToDateTime(profileRow["LastActivity"]), DateTimeKind.Utc); var lastUpdated = DateTime.SpecifyKind(Convert.ToDateTime(profileRow["LastUpdated"]), DateTimeKind.Utc); profiles.Add(new ProfileInfo(username, false, lastActivity, lastUpdated, 0)); } // get the first record which is the count... totalRecords = Convert.ToInt32(allProfilesDt.Rows[0]["TotalCount"]); return profiles; } #endregion } }
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> /// User Program Codes Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class KUPCDataSet : EduHubDataSet<KUPC> { /// <inheritdoc /> public override string Name { get { return "KUPC"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal KUPCDataSet(EduHubContext Context) : base(Context) { Index_GL_CODE = new Lazy<NullDictionary<string, IReadOnlyList<KUPC>>>(() => this.ToGroupedNullDictionary(i => i.GL_CODE)); Index_GLPROGRAM01 = new Lazy<NullDictionary<string, IReadOnlyList<KUPC>>>(() => this.ToGroupedNullDictionary(i => i.GLPROGRAM01)); Index_GLPROGRAM02 = new Lazy<NullDictionary<string, IReadOnlyList<KUPC>>>(() => this.ToGroupedNullDictionary(i => i.GLPROGRAM02)); Index_KUPCKEY = new Lazy<Dictionary<string, KUPC>>(() => this.ToDictionary(i => i.KUPCKEY)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="KUPC" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="KUPC" /> fields for each CSV column header</returns> internal override Action<KUPC, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<KUPC, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "KUPCKEY": mapper[i] = (e, v) => e.KUPCKEY = v; break; case "GLPROGRAM01": mapper[i] = (e, v) => e.GLPROGRAM01 = v; break; case "GLPROGRAM02": mapper[i] = (e, v) => e.GLPROGRAM02 = v; break; case "GL_CODE": mapper[i] = (e, v) => e.GL_CODE = 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="KUPC" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="KUPC" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="KUPC" /> entities</param> /// <returns>A merged <see cref="IEnumerable{KUPC}"/> of entities</returns> internal override IEnumerable<KUPC> ApplyDeltaEntities(IEnumerable<KUPC> Entities, List<KUPC> DeltaEntities) { HashSet<string> Index_KUPCKEY = new HashSet<string>(DeltaEntities.Select(i => i.KUPCKEY)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.KUPCKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_KUPCKEY.Remove(entity.KUPCKEY); if (entity.KUPCKEY.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<KUPC>>> Index_GL_CODE; private Lazy<NullDictionary<string, IReadOnlyList<KUPC>>> Index_GLPROGRAM01; private Lazy<NullDictionary<string, IReadOnlyList<KUPC>>> Index_GLPROGRAM02; private Lazy<Dictionary<string, KUPC>> Index_KUPCKEY; #endregion #region Index Methods /// <summary> /// Find KUPC by GL_CODE field /// </summary> /// <param name="GL_CODE">GL_CODE value used to find KUPC</param> /// <returns>List of related KUPC entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KUPC> FindByGL_CODE(string GL_CODE) { return Index_GL_CODE.Value[GL_CODE]; } /// <summary> /// Attempt to find KUPC by GL_CODE field /// </summary> /// <param name="GL_CODE">GL_CODE value used to find KUPC</param> /// <param name="Value">List of related KUPC entities</param> /// <returns>True if the list of related KUPC entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByGL_CODE(string GL_CODE, out IReadOnlyList<KUPC> Value) { return Index_GL_CODE.Value.TryGetValue(GL_CODE, out Value); } /// <summary> /// Attempt to find KUPC by GL_CODE field /// </summary> /// <param name="GL_CODE">GL_CODE value used to find KUPC</param> /// <returns>List of related KUPC entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KUPC> TryFindByGL_CODE(string GL_CODE) { IReadOnlyList<KUPC> value; if (Index_GL_CODE.Value.TryGetValue(GL_CODE, out value)) { return value; } else { return null; } } /// <summary> /// Find KUPC by GLPROGRAM01 field /// </summary> /// <param name="GLPROGRAM01">GLPROGRAM01 value used to find KUPC</param> /// <returns>List of related KUPC entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KUPC> FindByGLPROGRAM01(string GLPROGRAM01) { return Index_GLPROGRAM01.Value[GLPROGRAM01]; } /// <summary> /// Attempt to find KUPC by GLPROGRAM01 field /// </summary> /// <param name="GLPROGRAM01">GLPROGRAM01 value used to find KUPC</param> /// <param name="Value">List of related KUPC entities</param> /// <returns>True if the list of related KUPC entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByGLPROGRAM01(string GLPROGRAM01, out IReadOnlyList<KUPC> Value) { return Index_GLPROGRAM01.Value.TryGetValue(GLPROGRAM01, out Value); } /// <summary> /// Attempt to find KUPC by GLPROGRAM01 field /// </summary> /// <param name="GLPROGRAM01">GLPROGRAM01 value used to find KUPC</param> /// <returns>List of related KUPC entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KUPC> TryFindByGLPROGRAM01(string GLPROGRAM01) { IReadOnlyList<KUPC> value; if (Index_GLPROGRAM01.Value.TryGetValue(GLPROGRAM01, out value)) { return value; } else { return null; } } /// <summary> /// Find KUPC by GLPROGRAM02 field /// </summary> /// <param name="GLPROGRAM02">GLPROGRAM02 value used to find KUPC</param> /// <returns>List of related KUPC entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KUPC> FindByGLPROGRAM02(string GLPROGRAM02) { return Index_GLPROGRAM02.Value[GLPROGRAM02]; } /// <summary> /// Attempt to find KUPC by GLPROGRAM02 field /// </summary> /// <param name="GLPROGRAM02">GLPROGRAM02 value used to find KUPC</param> /// <param name="Value">List of related KUPC entities</param> /// <returns>True if the list of related KUPC entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByGLPROGRAM02(string GLPROGRAM02, out IReadOnlyList<KUPC> Value) { return Index_GLPROGRAM02.Value.TryGetValue(GLPROGRAM02, out Value); } /// <summary> /// Attempt to find KUPC by GLPROGRAM02 field /// </summary> /// <param name="GLPROGRAM02">GLPROGRAM02 value used to find KUPC</param> /// <returns>List of related KUPC entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KUPC> TryFindByGLPROGRAM02(string GLPROGRAM02) { IReadOnlyList<KUPC> value; if (Index_GLPROGRAM02.Value.TryGetValue(GLPROGRAM02, out value)) { return value; } else { return null; } } /// <summary> /// Find KUPC by KUPCKEY field /// </summary> /// <param name="KUPCKEY">KUPCKEY value used to find KUPC</param> /// <returns>Related KUPC entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KUPC FindByKUPCKEY(string KUPCKEY) { return Index_KUPCKEY.Value[KUPCKEY]; } /// <summary> /// Attempt to find KUPC by KUPCKEY field /// </summary> /// <param name="KUPCKEY">KUPCKEY value used to find KUPC</param> /// <param name="Value">Related KUPC entity</param> /// <returns>True if the related KUPC entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByKUPCKEY(string KUPCKEY, out KUPC Value) { return Index_KUPCKEY.Value.TryGetValue(KUPCKEY, out Value); } /// <summary> /// Attempt to find KUPC by KUPCKEY field /// </summary> /// <param name="KUPCKEY">KUPCKEY value used to find KUPC</param> /// <returns>Related KUPC entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KUPC TryFindByKUPCKEY(string KUPCKEY) { KUPC value; if (Index_KUPCKEY.Value.TryGetValue(KUPCKEY, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a KUPC 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].[KUPC]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[KUPC]( [KUPCKEY] varchar(10) NOT NULL, [GLPROGRAM01] varchar(3) NULL, [GLPROGRAM02] varchar(3) NULL, [GL_CODE] varchar(10) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [KUPC_Index_KUPCKEY] PRIMARY KEY CLUSTERED ( [KUPCKEY] ASC ) ); CREATE NONCLUSTERED INDEX [KUPC_Index_GL_CODE] ON [dbo].[KUPC] ( [GL_CODE] ASC ); CREATE NONCLUSTERED INDEX [KUPC_Index_GLPROGRAM01] ON [dbo].[KUPC] ( [GLPROGRAM01] ASC ); CREATE NONCLUSTERED INDEX [KUPC_Index_GLPROGRAM02] ON [dbo].[KUPC] ( [GLPROGRAM02] 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].[KUPC]') AND name = N'KUPC_Index_GL_CODE') ALTER INDEX [KUPC_Index_GL_CODE] ON [dbo].[KUPC] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KUPC]') AND name = N'KUPC_Index_GLPROGRAM01') ALTER INDEX [KUPC_Index_GLPROGRAM01] ON [dbo].[KUPC] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KUPC]') AND name = N'KUPC_Index_GLPROGRAM02') ALTER INDEX [KUPC_Index_GLPROGRAM02] ON [dbo].[KUPC] 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].[KUPC]') AND name = N'KUPC_Index_GL_CODE') ALTER INDEX [KUPC_Index_GL_CODE] ON [dbo].[KUPC] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KUPC]') AND name = N'KUPC_Index_GLPROGRAM01') ALTER INDEX [KUPC_Index_GLPROGRAM01] ON [dbo].[KUPC] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KUPC]') AND name = N'KUPC_Index_GLPROGRAM02') ALTER INDEX [KUPC_Index_GLPROGRAM02] ON [dbo].[KUPC] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KUPC"/> 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="KUPC"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KUPC> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<string> Index_KUPCKEY = new List<string>(); foreach (var entity in Entities) { Index_KUPCKEY.Add(entity.KUPCKEY); } builder.AppendLine("DELETE [dbo].[KUPC] WHERE"); // Index_KUPCKEY builder.Append("[KUPCKEY] IN ("); for (int index = 0; index < Index_KUPCKEY.Count; index++) { if (index != 0) builder.Append(", "); // KUPCKEY var parameterKUPCKEY = $"@p{parameterIndex++}"; builder.Append(parameterKUPCKEY); command.Parameters.Add(parameterKUPCKEY, SqlDbType.VarChar, 10).Value = Index_KUPCKEY[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the KUPC data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KUPC data set</returns> public override EduHubDataSetDataReader<KUPC> GetDataSetDataReader() { return new KUPCDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the KUPC data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KUPC data set</returns> public override EduHubDataSetDataReader<KUPC> GetDataSetDataReader(List<KUPC> Entities) { return new KUPCDataReader(new EduHubDataSetLoadedReader<KUPC>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class KUPCDataReader : EduHubDataSetDataReader<KUPC> { public KUPCDataReader(IEduHubDataSetReader<KUPC> Reader) : base (Reader) { } public override int FieldCount { get { return 7; } } public override object GetValue(int i) { switch (i) { case 0: // KUPCKEY return Current.KUPCKEY; case 1: // GLPROGRAM01 return Current.GLPROGRAM01; case 2: // GLPROGRAM02 return Current.GLPROGRAM02; case 3: // GL_CODE return Current.GL_CODE; case 4: // LW_DATE return Current.LW_DATE; case 5: // LW_TIME return Current.LW_TIME; case 6: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // GLPROGRAM01 return Current.GLPROGRAM01 == null; case 2: // GLPROGRAM02 return Current.GLPROGRAM02 == null; case 3: // GL_CODE return Current.GL_CODE == null; case 4: // LW_DATE return Current.LW_DATE == null; case 5: // LW_TIME return Current.LW_TIME == null; case 6: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // KUPCKEY return "KUPCKEY"; case 1: // GLPROGRAM01 return "GLPROGRAM01"; case 2: // GLPROGRAM02 return "GLPROGRAM02"; case 3: // GL_CODE return "GL_CODE"; case 4: // LW_DATE return "LW_DATE"; case 5: // LW_TIME return "LW_TIME"; case 6: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "KUPCKEY": return 0; case "GLPROGRAM01": return 1; case "GLPROGRAM02": return 2; case "GL_CODE": return 3; case "LW_DATE": return 4; case "LW_TIME": return 5; case "LW_USER": return 6; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
namespace Microsoft.Protocols.TestSuites.MS_FSSHTTP_FSSHTTPB { using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestSuites.SharedAdapter; using Microsoft.Protocols.TestSuites.SharedTestSuite; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// A class which contains test cases used to capture the requirements related with CellSubRequest operation. /// </summary> [TestClass] public sealed class MS_FSSHTTP_FSSHTTPB_S01_Cell : S01_Cell { #region Test Suite Initialization and clean up /// <summary> /// Class initialization /// </summary> /// <param name="testContext">The context of the test suite.</param> [ClassInitialize] public static new void ClassInitialize(TestContext testContext) { S01_Cell.ClassInitialize(testContext); } /// <summary> /// Class clean up /// </summary> [ClassCleanup] public static new void ClassCleanup() { S01_Cell.ClassCleanup(); } #endregion /// <summary> /// A method used to verify the related requirements when the URL attribute of the corresponding Request element is an empty string. /// </summary> [TestCategory("MSFSSHTTP_FSSHTTPB"), TestMethod()] public void MSFSSHTTP_FSSHTTPB_S01_TC01_DownloadContents_EmptyUrl() { if ((!Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3008, this.Site)) && (!Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3009, this.Site))) { Site.Assume.Inconclusive("Implementation does not have same behaviors as Microsoft products."); } // Initialize the context using user01 and defaultFileUrl. this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); CellStorageResponse response = new CellStorageResponse(); bool isR3008Verified = false; try { // Query the updated file content. CellSubRequestType queryChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedQueryChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID()); response = Adapter.CellStorageRequest(string.Empty, new SubRequestType[] { queryChange }); } catch (System.Xml.XmlException exception) { string message = exception.Message; isR3008Verified = message.Contains("Duplicate attribute"); isR3008Verified &= message.Contains("ErrorCode"); } if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R3008 if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3008, this.Site)) { Site.Log.Add( LogEntryKind.Debug, "SharePoint server 2010 and SharePoint Foundation responses two ErrorCode attributes when the URL is empty."); Site.CaptureRequirementIfIsTrue( isR3008Verified, "MS-FSSHTTP", 3008, @"[In Appendix B: Product Behavior] If the Url attribute of the corresponding Request element is an empty string, the implementation does return two ErrorCode attributes in Response element. <11> Section 2.2.3.5: SharePoint Server 2010 will return 2 ErrorCode attributes in Response element."); } // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R3009 if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3009, this.Site)) { Site.CaptureRequirementIfIsNull( response.ResponseCollection, "MS-FSSHTTP", 3009, @"[In Appendix B: Product Behavior] If the Url attribute of the corresponding Request element is an empty string, the implementation does not return Response element. <11> Section 2.2.3.5: SharePoint Server 2013 will not return Response element."); } } else { if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3008, this.Site)) { Site.Log.Add( LogEntryKind.Debug, "SharePoint server 2010 and SharePoint Foundation responses two ErrorCode attributes when the URL is non exists."); Site.Assert.IsTrue( isR3008Verified, "SharePoint server 2010 and SharePoint Foundation responses two ErrorCode attributes when the URL is non exists."); } if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3009, this.Site)) { Site.Assert.IsNull( response.ResponseCollection, @"[In Appendix B: Product Behavior] If the Url attribute of the corresponding Request element is an empty string, the implementation does not return Response element. <8> Section 2.2.3.5: SharePoint Server 2013 will not return Response element."); } } } /// <summary> /// A method used to verify the related requirements when the URL attribute of the corresponding Request element does not exist. /// </summary> [TestCategory("MSFSSHTTP_FSSHTTPB"), TestMethod()] public void MSFSSHTTP_FSSHTTPB_S01_TC02_DownloadContents_NotSpecifiedURL() { // Initialize the context using user01 and defaultFileUrl. this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); CellStorageResponse response = new CellStorageResponse(); bool isR3006Verified = false; try { // Query the updated file content. CellSubRequestType queryChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedQueryChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID()); response = Adapter.CellStorageRequest(string.Empty, new SubRequestType[] { queryChange }); } catch (System.Xml.XmlException exception) { string message = exception.Message; isR3006Verified = message.Contains("Duplicate attribute"); isR3006Verified &= message.Contains("ErrorCode"); } if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R3006 if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3006, this.Site)) { Site.Log.Add( LogEntryKind.Debug, "SharePoint server 2010 and SharePoint Foundation responses two ErrorCode attributes when the URL is non exists."); Site.CaptureRequirementIfIsTrue( isR3006Verified, "MS-FSSHTTP", 3006, @"[In Appendix B: Product Behavior] If the Url attribute of the corresponding Request element doesn't exist, the implementation does return two ErrorCode attributes in Response element. <11> Section 2.2.3.5: SharePoint Server 2010 will return 2 ErrorCode attributes in Response element."); } // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R3007 if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3007, this.Site)) { Site.CaptureRequirementIfIsNull( response.ResponseCollection, "MS-FSSHTTP", 3007, @"[In Appendix B: Product Behavior] If the Url attribute of the corresponding Request element doesn't exist, the implementation does not return Response element. <8> Section 2.2.3.5: SharePoint Server 2013 will not return Response element."); } } else { if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3006, this.Site)) { Site.Log.Add( LogEntryKind.Debug, "SharePoint server 2010 and SharePoint Foundation responses two ErrorCode attributes when the URL is non exists."); Site.Assert.IsTrue( isR3006Verified, "SharePoint server 2010 and SharePoint Foundation responses two ErrorCode attributes when the URL is non exists."); } if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3007, this.Site)) { Site.Assert.IsNull( response.ResponseCollection, @"[In Appendix B: Product Behavior] If the URL attribute of the corresponding Request element doesn't exist, the implementation does not return Response element. <8> Section 2.2.3.5: SharePoint Server 2013 will not return Response element."); } } } /// <summary> /// A method used to verify CellRequestFail will be returned if server was unable to find the URL for the file specified in the Url attribute. /// </summary> [TestCategory("MSFSSHTTP_FSSHTTPB"), TestMethod()] public void MSFSSHTTP_FSSHTTPB_S01_TC03_DownloadContents_InvalidUrl() { // Query the updated file content using the invalid url. string invalidUrl = this.DefaultFileUrl + "Invalid"; // Initialize the context using user01 and invalid url. this.InitializeContext(invalidUrl, this.UserName01, this.Password01, this.Domain); CellSubRequestType queryChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedQueryChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID()); CellStorageResponse response = Adapter.CellStorageRequest(invalidUrl, new SubRequestType[] { queryChange }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse<CellSubResponseType>(response, 0, 0, this.Site); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R1875 Site.CaptureRequirementIfAreEqual<ErrorCodeType>( ErrorCodeType.CellRequestFail, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "MS-FSSHTTP", 1875, @"[In Cell Subrequest][The protocol server returns results based on the following conditions:] If the protocol server was unable to find the URL for the file specified in the Url attribute, the protocol server reports a failure by returning an error code value set to ""CellRequestFail"" in the ErrorCode attribute sent back in the SubResponse element. [and the binary data in the returned SubRequestData element indicates an HRESULT Error as described in [MS-FSSHTTPB] section 2.2.3.2.4.]"); // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R11230 Site.CaptureRequirementIfAreEqual<ErrorCodeType>( ErrorCodeType.CellRequestFail, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "MS-FSSHTTP", 11230, @"[In Cell Subrequest][The protocol server returns results based on the following conditions:] [If the protocol server was unable to find the URL for the file specified in the Url attribute, the protocol server reports a failure by returning an error code value set to ""CellRequestFail"" in the ErrorCode attribute sent back in the SubResponse element, and] the binary data in the returned SubRequestData element indicates an HRESULT Error as described in [MS-FSSHTTPB] section 2.2.3.2.4."); } else { Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.CellRequestFail, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), @"[In Cell Subrequest][The protocol server returns results based on the following conditions:] If the protocol server was unable to find the URL for the file specified in the Url attribute, the protocol server reports a failure by returning an error code value set to ""CellRequestFail"" in the ErrorCode attribute sent back in the SubResponse element. [and the binary data in the returned SubRequestData element indicates an HRESULT Error as described in [MS-FSSHTTPB] section 2.2.3.2.4.]"); Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.CellRequestFail, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), @"[In Cell Subrequest][The protocol server returns results based on the following conditions:] [If the protocol server was unable to find the URL for the file specified in the Url attribute, the protocol server reports a failure by returning an error code value set to ""CellRequestFail"" in the ErrorCode attribute sent back in the SubResponse element, and] the binary data in the returned SubRequestData element indicates an HRESULT Error as described in [MS-FSSHTTPB] section 2.2.3.2.4."); } } /// <summary> /// Initialize the shared context based on the specified request file URL, user name, password and domain for the MS-FSSHTTP test purpose. /// </summary> /// <param name="requestFileUrl">Specify the request file URL.</param> /// <param name="userName">Specify the user name.</param> /// <param name="password">Specify the password.</param> /// <param name="domain">Specify the domain.</param> protected override void InitializeContext(string requestFileUrl, string userName, string password, string domain) { SharedContextUtils.InitializeSharedContextForFSSHTTP(userName, password, domain, this.Site); } /// <summary> /// Merge the common configuration and should/may configuration file. /// </summary> /// <param name="site">An instance of interface ITestSite which provides logging, assertions, /// and adapters for test code onto its execution context.</param> protected override void MergeConfigurationFile(TestTools.ITestSite site) { ConfigurationFileHelper.MergeConfigurationFile(site); } } }
// 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 USE_ETW using Microsoft.Diagnostics.Tracing; using Microsoft.Diagnostics.Tracing.Session; #endif using System; using System.Collections.Generic; using System.Diagnostics; #if USE_MDT_EVENTSOURCE using Microsoft.Diagnostics.Tracing; #else using System.Diagnostics.Tracing; #endif using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace BasicEventSourceTests { /// <summary> /// A listener can represent an out of process ETW listener (real time or not) or an EventListener /// </summary> public abstract class Listener : IDisposable { public Action<Event> OnEvent; // Called when you get events. public abstract void Dispose(); /// <summary> /// Send a command to an eventSource. Be careful this is async. You may wish to do a WaitForEnable /// </summary> public abstract void EventSourceCommand(string eventSourceName, EventCommand command, FilteringOptions options = null); public void EventSourceSynchronousEnable(EventSource eventSource, FilteringOptions options = null) { EventSourceCommand(eventSource.Name, EventCommand.Enable, options); WaitForEnable(eventSource); } public void WaitForEnable(EventSource logger) { if (!SpinWait.SpinUntil(() => logger.IsEnabled(), TimeSpan.FromSeconds(10))) { throw new InvalidOperationException("EventSource not enabled after 5 seconds"); } } internal void EnableTimer(EventSource eventSource, double pollingTime) { FilteringOptions options = new FilteringOptions(); options.Args = new Dictionary<string, string>(); options.Args.Add("EventCounterIntervalSec", pollingTime.ToString()); EventSourceCommand(eventSource.Name, EventCommand.Enable, options); } } /// <summary> /// Used to control what options the harness sends to the EventSource when turning it on. If not given /// it turns on all keywords, Verbose level, and no args. /// </summary> public class FilteringOptions { public FilteringOptions() { Keywords = EventKeywords.All; Level = EventLevel.Verbose; } public EventKeywords Keywords; public EventLevel Level; public IDictionary<string, string> Args; public override string ToString() { return string.Format("<Options Keywords='{0}' Level'{1}' ArgsCount='{2}'", ((ulong)Keywords).ToString("x"), Level, Args.Count); } } /// <summary> /// Because events can be written to a EventListener as well as to ETW, we abstract what the result /// of an event coming out of the pipe. Basically there are properties that fetch the name /// and the payload values, and we subclass this for the ETW case and for the EventListener case. /// </summary> public abstract class Event { public virtual bool IsEtw { get { return false; } } public virtual bool IsEventListener { get { return false; } } public abstract string ProviderName { get; } public abstract string EventName { get; } public abstract object PayloadValue(int propertyIndex, string propertyName); public abstract int PayloadCount { get; } public virtual string PayloadString(int propertyIndex, string propertyName) { var obj = PayloadValue(propertyIndex, propertyName); var asDict = obj as IDictionary<string, object>; if (asDict != null) { StringBuilder sb = new StringBuilder(); sb.Append("{"); bool first = true; foreach (var key in asDict.Keys) { if (!first) sb.Append(","); first = false; var value = asDict[key]; sb.Append(key).Append(":").Append(value != null ? value.ToString() : "NULL"); } sb.Append("}"); return sb.ToString(); } if (obj != null) return obj.ToString(); return ""; } public abstract IList<string> PayloadNames { get; } #if DEBUG /// <summary> /// This is a convenience function for the debugger. It is not used typically /// </summary> public List<object> PayloadValues { get { var ret = new List<object>(); for (int i = 0; i < PayloadCount; i++) ret.Add(PayloadValue(i, null)); return ret; } } #endif public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append(ProviderName).Append('/').Append(EventName).Append('('); for (int i = 0; i < PayloadCount; i++) { if (i != 0) sb.Append(','); sb.Append(PayloadString(i, PayloadNames[i])); } sb.Append(')'); return sb.ToString(); } } #if USE_ETW /**************************************************************************/ /* Concrete implementation of the Listener abstraction */ /// <summary> /// Implementation of the Listener abstraction for ETW. /// </summary> public class EtwListener : Listener { internal static void EnsureStopped() { using (var session = new TraceEventSession("EventSourceTestSession", "EventSourceTestData.etl")) session.Stop(); } public EtwListener(string dataFileName = "EventSourceTestData.etl", string sessionName = "EventSourceTestSession") { _dataFileName = dataFileName; // Today you have to be Admin to turn on ETW events (anyone can write ETW events). if (TraceEventSession.IsElevated() != true) { throw new Exception("Need to be elevated to run. "); } if (dataFileName == null) { Debug.WriteLine("Creating a real time session " + sessionName); Task.Factory.StartNew(delegate () { var session = new TraceEventSession(sessionName, dataFileName); session.Source.AllEvents += OnEventHelper; Debug.WriteLine("Listening for real time events"); _session = session; // Indicate that we are alive. _session.Source.Process(); Debug.WriteLine("Real time listening stopping."); }); SpinWait.SpinUntil(() => _session != null); // Wait for real time thread to wake up. } else { // Normalize to a full path name. dataFileName = Path.GetFullPath(dataFileName); Debug.WriteLine("Creating ETW data file " + Path.GetFullPath(dataFileName)); _session = new TraceEventSession(sessionName, dataFileName); } } public override void EventSourceCommand(string eventSourceName, EventCommand command, FilteringOptions options = null) { if (command == EventCommand.Enable) { if (options == null) options = new FilteringOptions(); _session.EnableProvider(eventSourceName, (TraceEventLevel)options.Level, (ulong)options.Keywords, new TraceEventProviderOptions() { Arguments = options.Args }); } else if (command == EventCommand.Disable) { _session.DisableProvider(TraceEventProviders.GetEventSourceGuidFromName(eventSourceName)); } else throw new NotImplementedException(); Thread.Sleep(200); // Calls are async, give them time to work. } public override void Dispose() { if(_disposed) { return; } _disposed = true; _session.Flush(); Thread.Sleep(1010); // Let it drain. _session.Dispose(); // This also will kill the real time thread if (_dataFileName != null) { using (var traceEventSource = new ETWTraceEventSource(_dataFileName)) { Debug.WriteLine("Processing data file " + Path.GetFullPath(_dataFileName)); // Parse all the events as best we can, and also send unhandled events there as well. traceEventSource.Dynamic.All += OnEventHelper; traceEventSource.UnhandledEvents += OnEventHelper; // Process all the events in the file. traceEventSource.Process(); Debug.WriteLine("Done processing data file " + Path.GetFullPath(_dataFileName)); } } } #region private private void OnEventHelper(TraceEvent data) { // Ignore EventTrace events. if (data.ProviderGuid == EventTraceProviderID) return; // Ignore kernel events. if (data.ProviderGuid == KernelProviderID) return; // Ignore manifest events. if ((int)data.ID == 0xFFFE) return; this.OnEvent(new EtwEvent(data)); } private static readonly Guid EventTraceProviderID = new Guid("9e814aad-3204-11d2-9a82-006008a86939"); private static readonly Guid KernelProviderID = new Guid("9e814aad-3204-11d2-9a82-006008a86939"); /// <summary> /// EtwEvent implements the 'Event' abstraction for ETW events (it has a TraceEvent in it) /// </summary> internal class EtwEvent : Event { public override bool IsEtw { get { return true; } } public override string ProviderName { get { return _data.ProviderName; } } public override string EventName { get { return _data.EventName; } } public override object PayloadValue(int propertyIndex, string propertyName) { if (propertyName != null) Assert.Equal(propertyName, _data.PayloadNames[propertyIndex]); return _data.PayloadValue(propertyIndex); } public override string PayloadString(int propertyIndex, string propertyName) { Assert.Equal(propertyName, _data.PayloadNames[propertyIndex]); return _data.PayloadString(propertyIndex); } public override int PayloadCount { get { return _data.PayloadNames.Length; } } public override IList<string> PayloadNames { get { return _data.PayloadNames; } } #region private internal EtwEvent(TraceEvent data) { _data = data.Clone(); } private TraceEvent _data; #endregion } private bool _disposed; private string _dataFileName; private volatile TraceEventSession _session; #endregion } #endif //USE_ETW public class EventListenerListener : Listener { private EventListener _listener; private Action<EventSource> _onEventSourceCreated; #if FEATURE_ETLEVENTS public event EventHandler<EventSourceCreatedEventArgs> EventSourceCreated { add { if (this._listener != null) this._listener.EventSourceCreated += value; } remove { if (this._listener != null) this._listener.EventSourceCreated -= value; } } public event EventHandler<EventWrittenEventArgs> EventWritten { add { if (this._listener != null) this._listener.EventWritten += value; } remove { if (this._listener != null) this._listener.EventWritten -= value; } } #endif public EventListenerListener(bool useEventsToListen = false) { #if FEATURE_ETLEVENTS if (useEventsToListen) { _listener = new HelperEventListener(null); _listener.EventSourceCreated += (sender, eventSourceCreatedEventArgs) => _onEventSourceCreated?.Invoke(eventSourceCreatedEventArgs.EventSource); _listener.EventWritten += mListenerEventWritten; } else #endif { _listener = new HelperEventListener(this); } } public override void Dispose() { if (_disposed) { return; } _disposed = true; EventTestHarness.LogWriteLine("Disposing Listener"); _listener.Dispose(); } private void DoCommand(EventSource source, EventCommand command, FilteringOptions options) { if (command == EventCommand.Enable) _listener.EnableEvents(source, options.Level, options.Keywords, options.Args); else if (command == EventCommand.Disable) _listener.DisableEvents(source); else throw new NotImplementedException(); } public override void EventSourceCommand(string eventSourceName, EventCommand command, FilteringOptions options = null) { EventTestHarness.LogWriteLine("Sending command {0} to EventSource {1} Options {2}", eventSourceName, command, options); if (options == null) options = new FilteringOptions(); foreach (EventSource source in EventSource.GetSources()) { if (source.Name == eventSourceName) { DoCommand(source, command, options); return; } } _onEventSourceCreated += delegate (EventSource sourceBeingCreated) { if (eventSourceName != null && eventSourceName == sourceBeingCreated.Name) { DoCommand(sourceBeingCreated, command, options); eventSourceName = null; // so we only do it once. } }; } private void mListenerEventWritten(object sender, EventWrittenEventArgs eventData) { OnEvent(new EventListenerEvent(eventData)); } private class HelperEventListener : EventListener { private readonly EventListenerListener _forwardTo; public HelperEventListener(EventListenerListener forwardTo) { _forwardTo = forwardTo; } protected override void OnEventSourceCreated(EventSource eventSource) { base.OnEventSourceCreated(eventSource); _forwardTo?._onEventSourceCreated?.Invoke(eventSource); } protected override void OnEventWritten(EventWrittenEventArgs eventData) { #if FEATURE_ETLEVENTS // OnEventWritten is abstract in netfx <= 461 base.OnEventWritten(eventData); #endif _forwardTo?.OnEvent?.Invoke(new EventListenerEvent(eventData)); } } /// <summary> /// EtwEvent implements the 'Event' abstraction for TraceListene events (it has a EventWrittenEventArgs in it) /// </summary> internal class EventListenerEvent : Event { private readonly EventWrittenEventArgs _data; public override bool IsEventListener { get { return true; } } public override string ProviderName { get { return _data.EventSource.Name; } } public override string EventName { get { return _data.EventName; } } public override IList<string> PayloadNames { get { return _data.PayloadNames; } } public override int PayloadCount { get { return _data.Payload?.Count ?? 0; } } internal EventListenerEvent(EventWrittenEventArgs data) { _data = data; } public override object PayloadValue(int propertyIndex, string propertyName) { if (propertyName != null) Assert.Equal(propertyName, _data.PayloadNames[propertyIndex]); return _data.Payload[propertyIndex]; } } private bool _disposed; } }
// 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.Globalization; using Xunit; public static class CharTests { [Fact] public static void TestCompareTo() { // Int32 Char.CompareTo(Char) char h = 'h'; Assert.True(h.CompareTo('h') == 0); Assert.True(h.CompareTo('a') > 0); Assert.True(h.CompareTo('z') < 0); } [Fact] public static void TestSystemIComparableCompareTo() { // Int32 Char.System.IComparable.CompareTo(Object) IComparable h = 'h'; Assert.True(h.CompareTo('h') == 0); Assert.True(h.CompareTo('a') > 0); Assert.True(h.CompareTo('z') < 0); Assert.True(h.CompareTo(null) > 0); Assert.Throws<ArgumentException>(() => h.CompareTo("H")); } private static void ValidateConvertFromUtf32(int i, string expected) { try { string s = char.ConvertFromUtf32(i); Assert.Equal(expected, s); } catch (ArgumentOutOfRangeException) { Assert.True(expected == null, "Expected an ArgumentOutOfRangeException"); } } [Fact] public static void TestConvertFromUtf32() { // String Char.ConvertFromUtf32(Int32) ValidateConvertFromUtf32(0x10000, "\uD800\uDC00"); ValidateConvertFromUtf32(0x103FF, "\uD800\uDFFF"); ValidateConvertFromUtf32(0xFFFFF, "\uDBBF\uDFFF"); ValidateConvertFromUtf32(0x10FC00, "\uDBFF\uDC00"); ValidateConvertFromUtf32(0x10FFFF, "\uDBFF\uDFFF"); ValidateConvertFromUtf32(0, "\0"); ValidateConvertFromUtf32(0x3FF, "\u03FF"); ValidateConvertFromUtf32(0xE000, "\uE000"); ValidateConvertFromUtf32(0xFFFF, "\uFFFF"); ValidateConvertFromUtf32(0xD800, null); ValidateConvertFromUtf32(0xDC00, null); ValidateConvertFromUtf32(0xDFFF, null); ValidateConvertFromUtf32(0x110000, null); ValidateConvertFromUtf32(-1, null); ValidateConvertFromUtf32(Int32.MaxValue, null); ValidateConvertFromUtf32(Int32.MinValue, null); } private static void ValidateconverToUtf32<T>(string s, int i, int expected) where T : Exception { try { int result = char.ConvertToUtf32(s, i); Assert.Equal(result, expected); } catch (T) { Assert.True(expected == Int32.MinValue, "Expected an exception to be thrown"); } } [Fact] public static void TestConvertToUtf32StrInt() { // Int32 Char.ConvertToUtf32(String, Int32) ValidateconverToUtf32<Exception>("\uD800\uDC00", 0, 0x10000); ValidateconverToUtf32<Exception>("\uD800\uD800\uDFFF", 1, 0x103FF); ValidateconverToUtf32<Exception>("\uDBBF\uDFFF", 0, 0xFFFFF); ValidateconverToUtf32<Exception>("\uDBFF\uDC00", 0, 0x10FC00); ValidateconverToUtf32<Exception>("\uDBFF\uDFFF", 0, 0x10FFFF); // Not surrogate pairs ValidateconverToUtf32<Exception>("\u0000\u0001", 0, 0); ValidateconverToUtf32<Exception>("\u0000\u0001", 1, 1); ValidateconverToUtf32<Exception>("\u0000", 0, 0); ValidateconverToUtf32<Exception>("\u0020\uD7FF", 0, 32); ValidateconverToUtf32<Exception>("\u0020\uD7FF", 1, 0xD7FF); ValidateconverToUtf32<Exception>("abcde", 4, (int)'e'); ValidateconverToUtf32<Exception>("\uD800\uD7FF", 1, 0xD7FF); // high, non-surrogate ValidateconverToUtf32<Exception>("\uD800\u0000", 1, 0); // high, non-surrogate ValidateconverToUtf32<Exception>("\uDF01\u0000", 1, 0); // low, non-surrogate // Invalid inputs ValidateconverToUtf32<ArgumentException>("\uD800\uD800", 0, Int32.MinValue); // high, high ValidateconverToUtf32<ArgumentException>("\uD800\uD7FF", 0, Int32.MinValue); // high, non-surrogate ValidateconverToUtf32<ArgumentException>("\uD800\u0000", 0, Int32.MinValue); // high, non-surrogate ValidateconverToUtf32<ArgumentException>("\uDC01\uD940", 0, Int32.MinValue); // low, high ValidateconverToUtf32<ArgumentException>("\uDD00\uDE00", 0, Int32.MinValue); // low, low ValidateconverToUtf32<ArgumentException>("\uDF01\u0000", 0, Int32.MinValue); // low, non-surrogate ValidateconverToUtf32<ArgumentException>("\uD800\uD800", 1, Int32.MinValue); // high, high ValidateconverToUtf32<ArgumentException>("\uDC01\uD940", 1, Int32.MinValue); // low, high ValidateconverToUtf32<ArgumentException>("\uDD00\uDE00", 1, Int32.MinValue); // low, low ValidateconverToUtf32<ArgumentNullException>(null, 0, Int32.MinValue); // null string ValidateconverToUtf32<ArgumentOutOfRangeException>("", 0, Int32.MinValue); // index out of range ValidateconverToUtf32<ArgumentOutOfRangeException>("", -1, Int32.MinValue); // index out of range ValidateconverToUtf32<ArgumentOutOfRangeException>("abcde", -1, Int32.MinValue); // index out of range ValidateconverToUtf32<ArgumentOutOfRangeException>("abcde", 5, Int32.MinValue); // index out of range } private static void ValidateconverToUtf32<T>(char c1, char c2, int expected) where T : Exception { try { int result = char.ConvertToUtf32(c1, c2); Assert.Equal(result, expected); } catch (T) { Assert.True(expected == Int32.MinValue, "Expected an exception to be thrown"); } } [Fact] public static void TestConvertToUtf32() { // Int32 Char.ConvertToUtf32(Char, Char) ValidateconverToUtf32<Exception>('\uD800', '\uDC00', 0x10000); ValidateconverToUtf32<Exception>('\uD800', '\uDFFF', 0x103FF); ValidateconverToUtf32<Exception>('\uDBBF', '\uDFFF', 0xFFFFF); ValidateconverToUtf32<Exception>('\uDBFF', '\uDC00', 0x10FC00); ValidateconverToUtf32<Exception>('\uDBFF', '\uDFFF', 0x10FFFF); ValidateconverToUtf32<ArgumentOutOfRangeException>('\uD800', '\uD800', Int32.MinValue); // high, high ValidateconverToUtf32<ArgumentOutOfRangeException>('\uD800', '\uD7FF', Int32.MinValue); // high, non-surrogate ValidateconverToUtf32<ArgumentOutOfRangeException>('\uD800', '\u0000', Int32.MinValue); // high, non-surrogate ValidateconverToUtf32<ArgumentOutOfRangeException>('\uDC01', '\uD940', Int32.MinValue); // low, high ValidateconverToUtf32<ArgumentOutOfRangeException>('\uDD00', '\uDE00', Int32.MinValue); // low, low ValidateconverToUtf32<ArgumentOutOfRangeException>('\uDF01', '\u0000', Int32.MinValue); // low, non-surrogate ValidateconverToUtf32<ArgumentOutOfRangeException>('\u0032', '\uD7FF', Int32.MinValue); // both non-surrogate ValidateconverToUtf32<ArgumentOutOfRangeException>('\u0000', '\u0000', Int32.MinValue); // both non-surrogate } [Fact] public static void TestEquals() { // Boolean Char.Equals(Char) char a = 'a'; Assert.True(a.Equals('a')); Assert.False(a.Equals('b')); Assert.False(a.Equals('A')); } [Fact] public static void TestEqualsObj() { // Boolean Char.Equals(Object) char a = 'a'; Assert.True(a.Equals((object)'a')); Assert.False(a.Equals((object)'b')); Assert.False(a.Equals((object)'A')); Assert.False(a.Equals(null)); int i = (int)'a'; Assert.False(a.Equals(i)); Assert.False(a.Equals("a")); } [Fact] public static void TestGetHashCode() { // Int32 Char.GetHashCode() char a = 'a'; char b = 'b'; Assert.NotEqual(a.GetHashCode(), b.GetHashCode()); } [Fact] public static void TestGetNumericValueStrInt() { Assert.Equal(Char.GetNumericValue("\uD800\uDD07", 0), 1); Assert.Equal(Char.GetNumericValue("9", 0), 9); Assert.Equal(Char.GetNumericValue("Test 7", 5), 7); Assert.Equal(Char.GetNumericValue("T", 0), -1); } [Fact] public static void TestGetNumericValue() { Assert.Equal(Char.GetNumericValue('9'), 9); Assert.Equal(Char.GetNumericValue('z'), -1); } [Fact] public static void TestIsControl() { // Boolean Char.IsControl(Char) foreach (var c in GetTestChars(UnicodeCategory.Control)) Assert.True(char.IsControl(c)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.Control)) Assert.False(char.IsControl(c)); } [Fact] public static void TestIsControlStrInt() { // Boolean Char.IsControl(String, Int32) foreach (var c in GetTestChars(UnicodeCategory.Control)) Assert.True(char.IsControl(c.ToString(), 0)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.Control)) Assert.False(char.IsControl(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsControl(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsControl("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsControl("abc", 4)); } [Fact] public static void TestIsDigit() { // Boolean Char.IsDigit(Char) foreach (var c in GetTestChars(UnicodeCategory.DecimalDigitNumber)) Assert.True(char.IsDigit(c)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber)) Assert.False(char.IsDigit(c)); } [Fact] public static void TestIsDigitStrInt() { // Boolean Char.IsDigit(String, Int32) foreach (var c in GetTestChars(UnicodeCategory.DecimalDigitNumber)) Assert.True(char.IsDigit(c.ToString(), 0)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber)) Assert.False(char.IsDigit(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsDigit(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsDigit("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsDigit("abc", 4)); } [Fact] public static void TestIsLetter() { // Boolean Char.IsLetter(Char) foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter)) Assert.True(char.IsLetter(c)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter)) Assert.False(char.IsLetter(c)); } [Fact] public static void TestIsLetterStrInt() { // Boolean Char.IsLetter(String, Int32) foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter)) Assert.True(char.IsLetter(c.ToString(), 0)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter)) Assert.False(char.IsLetter(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsLetter(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLetter("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLetter("abc", 4)); } [Fact] public static void TestIsLetterOrDigit() { // Boolean Char.IsLetterOrDigit(Char) foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter, UnicodeCategory.DecimalDigitNumber)) Assert.True(char.IsLetterOrDigit(c)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter, UnicodeCategory.DecimalDigitNumber)) Assert.False(char.IsLetterOrDigit(c)); } [Fact] public static void TestIsLetterOrDigitStrInt() { // Boolean Char.IsLetterOrDigit(String, Int32) foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter, UnicodeCategory.DecimalDigitNumber)) Assert.True(char.IsLetterOrDigit(c.ToString(), 0)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter, UnicodeCategory.DecimalDigitNumber)) Assert.False(char.IsLetterOrDigit(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsLetterOrDigit(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLetterOrDigit("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLetterOrDigit("abc", 4)); } [Fact] public static void TestIsLower() { // Boolean Char.IsLower(Char) foreach (var c in GetTestChars(UnicodeCategory.LowercaseLetter)) Assert.True(char.IsLower(c)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter)) Assert.False(char.IsLower(c)); } [Fact] public static void TestIsLowerStrInt() { // Boolean Char.IsLower(String, Int32) foreach (var c in GetTestChars(UnicodeCategory.LowercaseLetter)) Assert.True(char.IsLower(c.ToString(), 0)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter)) Assert.False(char.IsLower(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsLower(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLower("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLower("abc", 4)); } [Fact] public static void TestIsNumber() { // Boolean Char.IsNumber(Char) foreach (var c in GetTestChars(UnicodeCategory.DecimalDigitNumber, UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber)) Assert.True(char.IsNumber(c)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber, UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber)) Assert.False(char.IsNumber(c)); } [Fact] public static void TestIsNumberStrInt() { // Boolean Char.IsNumber(String, Int32) foreach (var c in GetTestChars(UnicodeCategory.DecimalDigitNumber, UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber)) Assert.True(char.IsNumber(c.ToString(), 0)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber, UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber)) Assert.False(char.IsNumber(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsNumber(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsNumber("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsNumber("abc", 4)); } [Fact] public static void TestIsPunctuation() { // Boolean Char.IsPunctuation(Char) foreach (var c in GetTestChars(UnicodeCategory.ConnectorPunctuation, UnicodeCategory.DashPunctuation, UnicodeCategory.OpenPunctuation, UnicodeCategory.ClosePunctuation, UnicodeCategory.InitialQuotePunctuation, UnicodeCategory.FinalQuotePunctuation, UnicodeCategory.OtherPunctuation)) Assert.True(char.IsPunctuation(c)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.ConnectorPunctuation, UnicodeCategory.DashPunctuation, UnicodeCategory.OpenPunctuation, UnicodeCategory.ClosePunctuation, UnicodeCategory.InitialQuotePunctuation, UnicodeCategory.FinalQuotePunctuation, UnicodeCategory.OtherPunctuation)) Assert.False(char.IsPunctuation(c)); } [Fact] public static void TestIsPunctuationStrInt() { // Boolean Char.IsPunctuation(String, Int32) foreach (var c in GetTestChars(UnicodeCategory.ConnectorPunctuation, UnicodeCategory.DashPunctuation, UnicodeCategory.OpenPunctuation, UnicodeCategory.ClosePunctuation, UnicodeCategory.InitialQuotePunctuation, UnicodeCategory.FinalQuotePunctuation, UnicodeCategory.OtherPunctuation)) Assert.True(char.IsPunctuation(c.ToString(), 0)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.ConnectorPunctuation, UnicodeCategory.DashPunctuation, UnicodeCategory.OpenPunctuation, UnicodeCategory.ClosePunctuation, UnicodeCategory.InitialQuotePunctuation, UnicodeCategory.FinalQuotePunctuation, UnicodeCategory.OtherPunctuation)) Assert.False(char.IsPunctuation(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsPunctuation(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsPunctuation("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsPunctuation("abc", 4)); } [Fact] public static void TestIsSeparator() { // Boolean Char.IsSeparator(Char) foreach (var c in GetTestChars(UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator)) Assert.True(char.IsSeparator(c)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator)) Assert.False(char.IsSeparator(c)); } [Fact] public static void TestIsSeparatorStrInt() { // Boolean Char.IsSeparator(String, Int32) foreach (var c in GetTestChars(UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator)) Assert.True(char.IsSeparator(c.ToString(), 0)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator)) Assert.False(char.IsSeparator(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsSeparator(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSeparator("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSeparator("abc", 4)); } [Fact] public static void TestIsLowSurrogate() { // Boolean Char.IsLowSurrogate(Char) foreach (char c in s_lowSurrogates) Assert.True(char.IsLowSurrogate(c)); foreach (char c in s_highSurrogates) Assert.False(char.IsLowSurrogate(c)); foreach (char c in s_nonSurrogates) Assert.False(char.IsLowSurrogate(c)); } [Fact] public static void TestIsLowSurrogateStrInt() { // Boolean Char.IsLowSurrogate(String, Int32) foreach (char c in s_lowSurrogates) Assert.True(char.IsLowSurrogate(c.ToString(), 0)); foreach (char c in s_highSurrogates) Assert.False(char.IsLowSurrogate(c.ToString(), 0)); foreach (char c in s_nonSurrogates) Assert.False(char.IsLowSurrogate(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsLowSurrogate(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLowSurrogate("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLowSurrogate("abc", 4)); } [Fact] public static void TestIsHighSurrogate() { // Boolean Char.IsHighSurrogate(Char) foreach (char c in s_highSurrogates) Assert.True(char.IsHighSurrogate(c)); foreach (char c in s_lowSurrogates) Assert.False(char.IsHighSurrogate(c)); foreach (char c in s_nonSurrogates) Assert.False(char.IsHighSurrogate(c)); } [Fact] public static void TestIsHighSurrogateStrInt() { // Boolean Char.IsHighSurrogate(String, Int32) foreach (char c in s_highSurrogates) Assert.True(char.IsHighSurrogate(c.ToString(), 0)); foreach (char c in s_lowSurrogates) Assert.False(char.IsHighSurrogate(c.ToString(), 0)); foreach (char c in s_nonSurrogates) Assert.False(char.IsHighSurrogate(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsHighSurrogate(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsHighSurrogate("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsHighSurrogate("abc", 4)); } [Fact] public static void TestIsSurrogate() { // Boolean Char.IsSurrogate(Char) foreach (char c in s_highSurrogates) Assert.True(char.IsSurrogate(c)); foreach (char c in s_lowSurrogates) Assert.True(char.IsSurrogate(c)); foreach (char c in s_nonSurrogates) Assert.False(char.IsSurrogate(c)); } [Fact] public static void TestIsSurrogateStrInt() { // Boolean Char.IsSurrogate(String, Int32) foreach (char c in s_highSurrogates) Assert.True(char.IsSurrogate(c.ToString(), 0)); foreach (char c in s_lowSurrogates) Assert.True(char.IsSurrogate(c.ToString(), 0)); foreach (char c in s_nonSurrogates) Assert.False(char.IsSurrogate(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsSurrogate(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSurrogate("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSurrogate("abc", 4)); } [Fact] public static void TestIsSurrogatePair() { // Boolean Char.IsSurrogatePair(Char, Char) foreach (char hs in s_highSurrogates) foreach (char ls in s_lowSurrogates) Assert.True(Char.IsSurrogatePair(hs, ls)); foreach (char hs in s_nonSurrogates) foreach (char ls in s_lowSurrogates) Assert.False(Char.IsSurrogatePair(hs, ls)); foreach (char hs in s_highSurrogates) foreach (char ls in s_nonSurrogates) Assert.False(Char.IsSurrogatePair(hs, ls)); } [Fact] public static void TestIsSurrogatePairStrInt() { // Boolean Char.IsSurrogatePair(String, Int32) foreach (char hs in s_highSurrogates) foreach (char ls in s_lowSurrogates) Assert.True(Char.IsSurrogatePair(hs.ToString() + ls, 0)); foreach (char hs in s_nonSurrogates) foreach (char ls in s_lowSurrogates) Assert.False(Char.IsSurrogatePair(hs.ToString() + ls, 0)); foreach (char hs in s_highSurrogates) foreach (char ls in s_nonSurrogates) Assert.False(Char.IsSurrogatePair(hs.ToString() + ls, 0)); } [Fact] public static void TestIsSymbol() { // Boolean Char.IsSymbol(Char) foreach (var c in GetTestChars(UnicodeCategory.MathSymbol, UnicodeCategory.ModifierSymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.OtherSymbol)) Assert.True(char.IsSymbol(c)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.MathSymbol, UnicodeCategory.ModifierSymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.OtherSymbol)) Assert.False(char.IsSymbol(c)); } [Fact] public static void TestIsSymbolStrInt() { // Boolean Char.IsSymbol(String, Int32) foreach (var c in GetTestChars(UnicodeCategory.MathSymbol, UnicodeCategory.ModifierSymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.OtherSymbol)) Assert.True(char.IsSymbol(c.ToString(), 0)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.MathSymbol, UnicodeCategory.ModifierSymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.OtherSymbol)) Assert.False(char.IsSymbol(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsSymbol(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSymbol("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSymbol("abc", 4)); } [Fact] public static void TestIsUpper() { // Boolean Char.IsUpper(Char) foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter)) Assert.True(char.IsUpper(c)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter)) Assert.False(char.IsUpper(c)); } [Fact] public static void TestIsUpperStrInt() { // Boolean Char.IsUpper(String, Int32) foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter)) Assert.True(char.IsUpper(c.ToString(), 0)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter)) Assert.False(char.IsUpper(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsUpper(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsUpper("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsUpper("abc", 4)); } [Fact] public static void TestIsWhiteSpace() { // Boolean Char.IsWhiteSpace(Char) foreach (var c in GetTestChars(UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator)) Assert.True(char.IsWhiteSpace(c)); // Some control chars are also considered whitespace for legacy reasons. //if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') Assert.True(char.IsWhiteSpace('\u000b')); Assert.True(char.IsWhiteSpace('\u0085')); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator)) { // Need to special case some control chars that are treated as whitespace if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') continue; Assert.False(char.IsWhiteSpace(c)); } } [Fact] public static void TestIsWhiteSpaceStrInt() { // Boolean Char.IsWhiteSpace(String, Int32) foreach (var c in GetTestChars(UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator)) Assert.True(char.IsWhiteSpace(c.ToString(), 0)); // Some control chars are also considered whitespace for legacy reasons. //if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') Assert.True(char.IsWhiteSpace('\u000b'.ToString(), 0)); Assert.True(char.IsWhiteSpace('\u0085'.ToString(), 0)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator)) { // Need to special case some control chars that are treated as whitespace if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') continue; Assert.False(char.IsWhiteSpace(c.ToString(), 0)); } Assert.Throws<ArgumentNullException>(() => char.IsWhiteSpace(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsWhiteSpace("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsWhiteSpace("abc", 4)); } [Fact] public static void TestMaxValue() { // Char Char.MaxValue Assert.Equal(0xffff, char.MaxValue); } [Fact] public static void TestMinValue() { // Char Char.MinValue Assert.Equal(0, char.MinValue); } [Fact] [ActiveIssue(846, PlatformID.AnyUnix)] public static void TestToLower() { // Char Char.ToLower(Char) Assert.Equal('a', char.ToLower('A')); Assert.Equal('a', char.ToLower('a')); foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter)) { char lc = char.ToLower(c); Assert.NotEqual(c, lc); Assert.True(char.IsLower(lc)); } // TitlecaseLetter can have a lower case form (e.g. \u01C8 'Lj' letter which will be 'lj') // LetterNumber can have a lower case form (e.g. \u2162 'III' letter which will be 'iii') foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber)) { char lc = char.ToLower(c); Assert.Equal(c, lc); } } [Fact] [ActiveIssue(846, PlatformID.AnyUnix)] public static void TestToLowerInvariant() { // Char Char.ToLowerInvariant(Char) Assert.Equal('a', char.ToLowerInvariant('A')); Assert.Equal('a', char.ToLowerInvariant('a')); foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter)) { char lc = char.ToLowerInvariant(c); Assert.NotEqual(c, lc); Assert.True(char.IsLower(lc)); } // TitlecaseLetter can have a lower case form (e.g. \u01C8 'Lj' letter which will be 'lj') // LetterNumber can have a lower case form (e.g. \u2162 'III' letter which will be 'iii') foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber)) { char lc = char.ToLowerInvariant(c); Assert.Equal(c, lc); } } [Fact] public static void TestToString() { // String Char.ToString() Assert.Equal(new string('a', 1), 'a'.ToString()); Assert.Equal(new string('\uabcd', 1), '\uabcd'.ToString()); } [Fact] public static void TestToStringChar() { // String Char.ToString(Char) Assert.Equal(new string('a', 1), char.ToString('a')); Assert.Equal(new string('\uabcd', 1), char.ToString('\uabcd')); } [Fact] [ActiveIssue(846, PlatformID.AnyUnix)] public static void TestToUpper() { // Char Char.ToUpper(Char) Assert.Equal('A', char.ToUpper('A')); Assert.Equal('A', char.ToUpper('a')); foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter)) { char lc = char.ToUpper(c); Assert.NotEqual(c, lc); Assert.True(char.IsUpper(lc)); } // TitlecaseLetter can have a uppercase form (e.g. \u01C8 'Lj' letter which will be 'LJ') // LetterNumber can have a uppercase form (e.g. \u2172 'iii' letter which will be 'III') foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber)) { char lc = char.ToUpper(c); Assert.Equal(c, lc); } } [Fact] [ActiveIssue(846, PlatformID.AnyUnix)] public static void TestToUpperInvariant() { // Char Char.ToUpperInvariant(Char) Assert.Equal('A', char.ToUpperInvariant('A')); Assert.Equal('A', char.ToUpperInvariant('a')); foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter)) { char lc = char.ToUpperInvariant(c); Assert.NotEqual(c, lc); Assert.True(char.IsUpper(lc)); } // TitlecaseLetter can have a uppercase form (e.g. \u01C8 'Lj' letter which will be 'LJ') // LetterNumber can have a uppercase form (e.g. \u2172 'iii' letter which will be 'III') foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber)) { char lc = char.ToUpperInvariant(c); Assert.Equal(c, lc); } } private static void ValidateTryParse(string s, char expected, bool shouldSucceed) { char result; Assert.Equal(shouldSucceed, char.TryParse(s, out result)); if (shouldSucceed) Assert.Equal(expected, result); } [Fact] public static void TestTryParse() { // Boolean Char.TryParse(String, Char) ValidateTryParse("a", 'a', true); ValidateTryParse("4", '4', true); ValidateTryParse(" ", ' ', true); ValidateTryParse("\n", '\n', true); ValidateTryParse("\0", '\0', true); ValidateTryParse("\u0135", '\u0135', true); ValidateTryParse("\u05d9", '\u05d9', true); ValidateTryParse("\ud801", '\ud801', true); // high surrogate ValidateTryParse("\udc01", '\udc01', true); // low surrogate ValidateTryParse("\ue001", '\ue001', true); // private use codepoint // Fail cases ValidateTryParse(null, '\0', false); ValidateTryParse("", '\0', false); ValidateTryParse("\n\r", '\0', false); ValidateTryParse("kj", '\0', false); ValidateTryParse(" a", '\0', false); ValidateTryParse("a ", '\0', false); ValidateTryParse("\\u0135", '\0', false); ValidateTryParse("\u01356", '\0', false); ValidateTryParse("\ud801\udc01", '\0', false); // surrogate pair } private static IEnumerable<char> GetTestCharsNotInCategory(params UnicodeCategory[] categories) { Assert.Equal(s_latinTestSet.Length, s_unicodeTestSet.Length); for (int i = 0; i < s_latinTestSet.Length; i++) { if (Array.Exists(categories, uc => uc == (UnicodeCategory)i)) continue; char[] latinSet = s_latinTestSet[i]; for (int j = 0; j < latinSet.Length; j++) yield return latinSet[j]; char[] unicodeSet = s_unicodeTestSet[i]; for (int k = 0; k < unicodeSet.Length; k++) yield return unicodeSet[k]; } } private static IEnumerable<char> GetTestChars(params UnicodeCategory[] categories) { for (int i = 0; i < categories.Length; i++) { char[] latinSet = s_latinTestSet[(int)categories[i]]; for (int j = 0; j < latinSet.Length; j++) yield return latinSet[j]; char[] unicodeSet = s_unicodeTestSet[(int)categories[i]]; for (int k = 0; k < unicodeSet.Length; k++) yield return unicodeSet[k]; } } private static char[][] s_latinTestSet = new char[][] { new char[] {'\u0047','\u004c','\u0051','\u0056','\u00c0','\u00c5','\u00ca','\u00cf','\u00d4','\u00da'}, // UnicodeCategory.UppercaseLetter new char[] {'\u0062','\u0068','\u006e','\u0074','\u007a','\u00e1','\u00e7','\u00ed','\u00f3','\u00fa'}, // UnicodeCategory.LowercaseLetter new char[] {}, // UnicodeCategory.TitlecaseLetter new char[] {}, // UnicodeCategory.ModifierLetter new char[] {}, // UnicodeCategory.OtherLetter new char[] {}, // UnicodeCategory.NonSpacingMark new char[] {}, // UnicodeCategory.SpacingCombiningMark new char[] {}, // UnicodeCategory.EnclosingMark new char[] {'\u0030','\u0031','\u0032','\u0033','\u0034','\u0035','\u0036','\u0037','\u0038','\u0039'}, // UnicodeCategory.DecimalDigitNumber new char[] {}, // UnicodeCategory.LetterNumber new char[] {'\u00b2','\u00b3','\u00b9','\u00bc','\u00bd','\u00be'}, // UnicodeCategory.OtherNumber new char[] {'\u0020','\u00a0'}, // UnicodeCategory.SpaceSeparator new char[] {}, // UnicodeCategory.LineSeparator new char[] {}, // UnicodeCategory.ParagraphSeparator new char[] {'\u0005','\u000b','\u0011','\u0017','\u001d','\u0082','\u0085','\u008e','\u0094','\u009a'}, // UnicodeCategory.Control new char[] {}, // UnicodeCategory.Format new char[] {}, // UnicodeCategory.Surrogate new char[] {}, // UnicodeCategory.PrivateUse new char[] {'\u005f'}, // UnicodeCategory.ConnectorPunctuation new char[] {'\u002d','\u00ad'}, // UnicodeCategory.DashPunctuation new char[] {'\u0028','\u005b','\u007b'}, // UnicodeCategory.OpenPunctuation new char[] {'\u0029','\u005d','\u007d'}, // UnicodeCategory.ClosePunctuation new char[] {'\u00ab'}, // UnicodeCategory.InitialQuotePunctuation new char[] {'\u00bb'}, // UnicodeCategory.FinalQuotePunctuation new char[] {'\u002e','\u002f','\u003a','\u003b','\u003f','\u0040','\u005c','\u00a1','\u00b7','\u00bf'}, // UnicodeCategory.OtherPunctuation new char[] {'\u002b','\u003c','\u003d','\u003e','\u007c','\u007e','\u00ac','\u00b1','\u00d7','\u00f7'}, // UnicodeCategory.MathSymbol new char[] {'\u0024','\u00a2','\u00a3','\u00a4','\u00a5'}, // UnicodeCategory.CurrencySymbol new char[] {'\u005e','\u0060','\u00a8','\u00af','\u00b4','\u00b8'}, // UnicodeCategory.ModifierSymbol new char[] {'\u00a6','\u00a7','\u00a9','\u00ae','\u00b0','\u00b6'}, // UnicodeCategory.OtherSymbol new char[] {}, // UnicodeCategory.OtherNotAssigned }; private static char[][] s_unicodeTestSet = new char[][] { new char[] {'\u0102','\u01ac','\u0392','\u0428','\u0508','\u10c4','\u1eb4','\u1fba','\u2c28','\ua668'}, // UnicodeCategory.UppercaseLetter new char[] { '\u0107', '\u012D', '\u0140', '\u0151', '\u013A', '\u01A1', '\u01F9', '\u022D', '\u1E09','\uFF45' }, // UnicodeCategory.LowercaseLetter new char[] {'\u01c8','\u1f88','\u1f8b','\u1f8e','\u1f99','\u1f9c','\u1f9f','\u1faa','\u1fad','\u1fbc'}, // UnicodeCategory.TitlecaseLetter new char[] {'\u02b7','\u02cd','\u07f4','\u1d2f','\u1d41','\u1d53','\u1d9d','\u1daf','\u2091','\u30fe'}, // UnicodeCategory.ModifierLetter new char[] {'\u01c0','\u37be','\u4970','\u5b6c','\u6d1e','\u7ed0','\u9082','\ua271','\ub985','\ucb37'}, // UnicodeCategory.OtherLetter new char[] {'\u0303','\u034e','\u05b5','\u0738','\u0a4d','\u0e49','\u0fad','\u180b','\u1dd5','\u2dfd'}, // UnicodeCategory.NonSpacingMark new char[] {'\u0982','\u0b03','\u0c41','\u0d40','\u0df3','\u1083','\u1925','\u19b9','\u1b44','\ua8b5'}, // UnicodeCategory.SpacingCombiningMark new char[] {'\u20dd','\u20de','\u20df','\u20e0','\u20e2','\u20e3','\u20e4','\ua670','\ua671','\ua672'}, // UnicodeCategory.EnclosingMark new char[] {'\u0660','\u0966','\u0ae6','\u0c66','\u0e50','\u1040','\u1810','\u1b50','\u1c50','\ua900'}, // UnicodeCategory.DecimalDigitNumber new char[] {'\u2162','\u2167','\u216c','\u2171','\u2176','\u217b','\u2180','\u2187','\u3023','\u3028'}, // UnicodeCategory.LetterNumber new char[] {'\u0c78','\u136b','\u17f7','\u2158','\u2471','\u248a','\u24f1','\u2780','\u3220','\u3280'}, // UnicodeCategory.OtherNumber new char[] {'\u2004','\u2005','\u2006','\u2007','\u2008','\u2009','\u200a','\u202f','\u205f','\u3000'}, // UnicodeCategory.SpaceSeparator new char[] {'\u2028'}, // UnicodeCategory.LineSeparator new char[] {'\u2029'}, // UnicodeCategory.ParagraphSeparator new char[] {}, // UnicodeCategory.Control new char[] {'\u0603','\u17b4','\u200c','\u200f','\u202c','\u2060','\u2063','\u206b','\u206e','\ufff9'}, // UnicodeCategory.Format new char[] {'\ud808','\ud8d4','\ud9a0','\uda6c','\udb38','\udc04','\udcd0','\udd9c','\ude68','\udf34'}, // UnicodeCategory.Surrogate new char[] {'\ue000','\ue280','\ue500','\ue780','\uea00','\uec80','\uef00','\uf180','\uf400','\uf680'}, // UnicodeCategory.PrivateUse new char[] {'\u203f','\u2040','\u2054','\ufe33','\ufe34','\ufe4d','\ufe4e','\ufe4f','\uff3f'}, // UnicodeCategory.ConnectorPunctuation new char[] {'\u2e17','\u2e1a','\u301c','\u3030','\u30a0','\ufe31','\ufe32','\ufe58','\ufe63','\uff0d'}, // UnicodeCategory.DashPunctuation new char[] {'\u2768','\u2774','\u27ee','\u298d','\u29d8','\u2e28','\u3014','\ufe17','\ufe3f','\ufe5d'}, // UnicodeCategory.OpenPunctuation new char[] {'\u276b','\u27c6','\u2984','\u2990','\u29db','\u3009','\u3017','\ufe18','\ufe40','\ufe5e'}, // UnicodeCategory.ClosePunctuation new char[] {'\u201b','\u201c','\u201f','\u2039','\u2e02','\u2e04','\u2e09','\u2e0c','\u2e1c','\u2e20'}, // UnicodeCategory.InitialQuotePunctuation new char[] {'\u2019','\u201d','\u203a','\u2e03','\u2e05','\u2e0a','\u2e0d','\u2e1d','\u2e21'}, // UnicodeCategory.FinalQuotePunctuation new char[] {'\u0589','\u0709','\u0f10','\u16ec','\u1b5b','\u2034','\u2058','\u2e16','\ua8cf','\ufe55'}, // UnicodeCategory.OtherPunctuation new char[] {'\u2052','\u2234','\u2290','\u22ec','\u27dd','\u2943','\u29b5','\u2a17','\u2a73','\u2acf'}, // UnicodeCategory.MathSymbol new char[] {'\u17db','\u20a2','\u20a5','\u20a8','\u20ab','\u20ae','\u20b1','\u20b4','\ufe69','\uffe1'}, // UnicodeCategory.CurrencySymbol new char[] {'\u02c5','\u02da','\u02e8','\u02f3','\u02fc','\u1fc0','\u1fee','\ua703','\ua70c','\ua715'}, // UnicodeCategory.ModifierSymbol new char[] {'\u0bf3','\u2316','\u24ac','\u25b2','\u26af','\u285c','\u2e8f','\u2f8c','\u3292','\u3392'}, // UnicodeCategory.OtherSymbol new char[] {'\u037f','\u09c6','\u0dfa','\u2e5c','\ua9f9','\uabbd'}, // UnicodeCategory.OtherNotAssigned }; private static char[] s_highSurrogates = new char[] { '\ud800', '\udaaa', '\udbff' }; // range from '\ud800' to '\udbff' private static char[] s_lowSurrogates = new char[] { '\udc00', '\udeee', '\udfff' }; // range from '\udc00' to '\udfff' private static char[] s_nonSurrogates = new char[] { '\u0000', '\ud7ff', '\ue000', '\uffff' }; }
using Newtonsoft.Json; using Signum.Engine.Authorization; using Signum.Engine.Basics; using Signum.Engine.Chart; using Signum.Engine.Dashboard; using Signum.Engine.DynamicQuery; using Signum.Engine.Maps; using Signum.Engine.Operations; using Signum.Engine.UserAssets; using Signum.Engine.UserQueries; using Signum.Entities; using Signum.Entities.Authorization; using Signum.Entities.Basics; using Signum.Entities.Chart; using Signum.Entities.Dashboard; using Signum.Entities.Toolbar; using Signum.Entities.UserQueries; using Signum.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Signum.Engine.Toolbar { public static class ToolbarLogic { public static ResetLazy<Dictionary<Lite<ToolbarEntity>, ToolbarEntity>> Toolbars = null!; public static ResetLazy<Dictionary<Lite<ToolbarMenuEntity>, ToolbarMenuEntity>> ToolbarMenus = null!; public static void Start(SchemaBuilder sb) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { sb.Include<ToolbarEntity>() .WithSave(ToolbarOperation.Save) .WithDelete(ToolbarOperation.Delete) .WithQuery(() => e => new { Entity = e, e.Id, e.Name, e.Owner, e.Priority }); sb.Include<ToolbarMenuEntity>() .WithSave(ToolbarMenuOperation.Save) .WithDelete(ToolbarMenuOperation.Delete) .WithQuery(() => e => new { Entity = e, e.Id, e.Name }); UserAssetsImporter.RegisterName<ToolbarEntity>("Toolbar"); UserAssetsImporter.RegisterName<ToolbarMenuEntity>("ToolbarMenu"); RegisterDelete<UserQueryEntity>(sb); RegisterDelete<UserChartEntity>(sb); RegisterDelete<QueryEntity>(sb); RegisterDelete<DashboardEntity>(sb); RegisterDelete<ToolbarMenuEntity>(sb); Toolbars = sb.GlobalLazy(() => Database.Query<ToolbarEntity>().ToDictionary(a => a.ToLite()), new InvalidateWith(typeof(ToolbarEntity))); ToolbarMenus = sb.GlobalLazy(() => Database.Query<ToolbarMenuEntity>().ToDictionary(a => a.ToLite()), new InvalidateWith(typeof(ToolbarMenuEntity))); } } public static void RegisterUserTypeCondition(SchemaBuilder sb, TypeConditionSymbol typeCondition) { sb.Schema.Settings.AssertImplementedBy((ToolbarEntity t) => t.Owner, typeof(UserEntity)); TypeConditionLogic.RegisterCompile<ToolbarEntity>(typeCondition, t => t.Owner.Is(UserEntity.Current)); sb.Schema.Settings.AssertImplementedBy((ToolbarMenuEntity t) => t.Owner, typeof(UserEntity)); TypeConditionLogic.RegisterCompile<ToolbarMenuEntity>(typeCondition, t => t.Owner.Is(UserEntity.Current)); } public static void RegisterRoleTypeCondition(SchemaBuilder sb, TypeConditionSymbol typeCondition) { sb.Schema.Settings.AssertImplementedBy((ToolbarEntity t) => t.Owner, typeof(RoleEntity)); TypeConditionLogic.RegisterCompile<ToolbarEntity>(typeCondition, t => AuthLogic.CurrentRoles().Contains(t.Owner) || t.Owner == null); sb.Schema.Settings.AssertImplementedBy((ToolbarMenuEntity t) => t.Owner, typeof(RoleEntity)); TypeConditionLogic.RegisterCompile<ToolbarMenuEntity>(typeCondition, t => AuthLogic.CurrentRoles().Contains(t.Owner) || t.Owner == null); } public static void RegisterDelete<T>(SchemaBuilder sb) where T : Entity { if (sb.Settings.ImplementedBy((ToolbarEntity tb) => tb.Elements.First().Content, typeof(T))) { sb.Schema.EntityEvents<T>().PreUnsafeDelete += query => { Database.MListQuery((ToolbarEntity tb) => tb.Elements).Where(mle => query.Contains((T)mle.Element.Content!.Entity)).UnsafeDeleteMList(); return null; }; sb.Schema.Table<T>().PreDeleteSqlSync += arg => { var entity = (T)arg; var parts = Administrator.UnsafeDeletePreCommandMList((ToolbarEntity tb) => tb.Elements, Database.MListQuery((ToolbarEntity tb) => tb.Elements) .Where(mle => mle.Element.Content!.Entity == entity)); return parts; }; } if (sb.Settings.ImplementedBy((ToolbarMenuEntity tb) => tb.Elements.First().Content, typeof(T))) { sb.Schema.EntityEvents<T>().PreUnsafeDelete += query => { Database.MListQuery((ToolbarMenuEntity tb) => tb.Elements).Where(mle => query.Contains((T)mle.Element.Content!.Entity)).UnsafeDeleteMList(); return null; }; sb.Schema.Table<T>().PreDeleteSqlSync += arg => { var entity = (T)arg; var parts = Administrator.UnsafeDeletePreCommandMList((ToolbarMenuEntity tb) => tb.Elements, Database.MListQuery((ToolbarMenuEntity tb) => tb.Elements) .Where(mle => mle.Element.Content!.Entity == entity)); return parts; }; } } public static ToolbarEntity GetCurrent(ToolbarLocation location) { var isAllowed = Schema.Current.GetInMemoryFilter<ToolbarEntity>(userInterface: false); var result = Toolbars.Value.Values .Where(t => isAllowed(t) && t.Location == location) .OrderByDescending(a => a.Priority) .FirstOrDefault(); return result; } public static ToolbarResponse? GetCurrentToolbarResponse(ToolbarLocation location) { var curr = GetCurrent(location); if (curr == null) return null; var responses = ToResponseList(curr.Elements); if (responses.Count == 0) return null; return new ToolbarResponse { type = ToolbarElementType.Header, content = curr.ToLite(), label = curr.Name, elements = responses, }; } private static List<ToolbarResponse> ToResponseList(MList<ToolbarElementEmbedded> elements) { var result = elements.Select(a => ToResponse(a)).NotNull().ToList(); retry: var extraDividers = result.Where((a, i) => a.type == ToolbarElementType.Divider && ( i == 0 || result[i - 1].type == ToolbarElementType.Divider || i == result.Count )).ToList(); result.RemoveAll(extraDividers.Contains); var extraHeaders = result.Where((a, i) => IsPureHeader(a) && ( i == result.Count - 1 || IsPureHeader(result[i + 1]) || result[i + 1].type == ToolbarElementType.Divider || result[i + 1].type == ToolbarElementType.Header && result[i + 1].content is Lite<ToolbarMenuEntity> )).ToList(); result.RemoveAll(extraHeaders.Contains); if (extraDividers.Any() || extraHeaders.Any()) goto retry; return result; } private static bool IsPureHeader(ToolbarResponse tr) { return tr.type == ToolbarElementType.Header && tr.content == null && string.IsNullOrEmpty(tr.url); } private static ToolbarResponse? ToResponse(ToolbarElementEmbedded element) { if (element.Content != null && !(element.Content is Lite<ToolbarMenuEntity>)) { if (!IsAuthorized(element.Content)) return null; } var result = new ToolbarResponse { type = element.Type, content = element.Content, url = element.Url, label = element.Label, iconName = element.IconName, iconColor = element.IconColor, autoRefreshPeriod = element.AutoRefreshPeriod, openInPopup = element.OpenInPopup, }; if (element.Content is Lite<ToolbarMenuEntity>) { var tme = ToolbarMenus.Value.GetOrThrow((Lite<ToolbarMenuEntity>)element.Content); result.elements = ToResponseList(tme.Elements); if (result.elements.Count == 0) return null; } return result; } public static void RegisterIsAuthorized<T>(Func<Lite<Entity>, bool> isAuthorized) where T : Entity { IsAuthorizedDictionary.Add(typeof(T), isAuthorized); } static Dictionary<Type, Func<Lite<Entity>, bool>> IsAuthorizedDictionary = new Dictionary<Type, Func<Lite<Entity>, bool>> { { typeof(QueryEntity), a => IsQueryAllowed((Lite<QueryEntity>)a) }, { typeof(PermissionSymbol), a => PermissionAuthLogic.IsAuthorized((PermissionSymbol)a.RetrieveAndRemember()) }, { typeof(UserQueryEntity), a => { var uq = UserQueryLogic.UserQueries.Value.GetOrCreate((Lite<UserQueryEntity>)a); return InMemoryFilter(uq) && QueryLogic.Queries.QueryAllowed(uq.Query.ToQueryName(), true); } }, { typeof(UserChartEntity), a => { var uc = UserChartLogic.UserCharts.Value.GetOrCreate((Lite<UserChartEntity>)a); return InMemoryFilter(uc) && QueryLogic.Queries.QueryAllowed(uc.Query.ToQueryName(), true); } }, { typeof(DashboardEntity), a => InMemoryFilter(DashboardLogic.Dashboards.Value.GetOrCreate((Lite<DashboardEntity>)a)) }, }; static bool IsQueryAllowed(Lite<QueryEntity> query) { try { return QueryLogic.Queries.QueryAllowed(QueryLogic.QueryNames.GetOrThrow(query.ToString()!), true); } catch (Exception e) when (StartParameters.IgnoredDatabaseMismatches != null) { //Could happen when not 100% synchronized StartParameters.IgnoredDatabaseMismatches.Add(e); return false; } } static bool InMemoryFilter<T>(T entity) where T : Entity { if (Schema.Current.IsAllowed(typeof(T), inUserInterface: false) != null) return false; var isAllowed = Schema.Current.GetInMemoryFilter<T>(userInterface: false); return isAllowed(entity); } public static bool IsAuthorized(Lite<Entity> lite) { return IsAuthorizedDictionary.GetOrThrow(lite.EntityType)(lite); } } public class ToolbarResponse { public ToolbarElementType type; public string? label; public Lite<Entity>? content; public string? url; public List<ToolbarResponse>? elements; public string? iconName; public string? iconColor; [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public int? autoRefreshPeriod; [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool openInPopup; public override string ToString() => $"{type} {label} {content} {url}"; } }
//------------------------------------------------------------------------------ // <copyright file="Cursor.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* */ namespace System.Windows.Forms { using System.Runtime.InteropServices; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System; using System.Drawing; using System.Drawing.Design; using CodeAccessPermission = System.Security.CodeAccessPermission; using System.Security.Permissions; using System.ComponentModel; using System.IO; using Microsoft.Win32; using System.Runtime.Serialization; using System.Globalization; using System.Security; /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor"]/*' /> /// <devdoc> /// <para> /// Represents the image used to paint the mouse pointer. /// Different cursor shapes are used to inform the user what operation the mouse will /// have. /// </para> /// </devdoc> // [ TypeConverterAttribute(typeof(CursorConverter)), Serializable, Editor("System.Drawing.Design.CursorEditor, " + AssemblyRef.SystemDrawingDesign, typeof(UITypeEditor)) ] public sealed class Cursor : IDisposable, ISerializable { private static Size cursorSize = System.Drawing.Size.Empty; private byte[] cursorData; private IntPtr handle = IntPtr.Zero; // handle to loaded image private bool ownHandle = true; private int resourceId = 0; private object userData; /** * Constructor used in deserialization */ internal Cursor(SerializationInfo info, StreamingContext context) { SerializationInfoEnumerator sie = info.GetEnumerator(); if (sie == null) { return; } for (; sie.MoveNext();) { // Dont catch any exceptions while Deserialising objects from stream. if (String.Equals(sie.Name, "CursorData", StringComparison.OrdinalIgnoreCase) ){ cursorData = (byte[])sie.Value; if (cursorData != null) { LoadPicture(new UnsafeNativeMethods.ComStreamFromDataStream(new MemoryStream(cursorData))); } } else if (String.Compare(sie.Name, "CursorResourceId", true, CultureInfo.InvariantCulture) == 0) { LoadFromResourceId((int)sie.Value); } } } /// <devdoc> /// Private constructor. If you want a standard system cursor, use one of the /// definitions in the Cursors class. /// </devdoc> // internal Cursor(int nResourceId, int dummy) { LoadFromResourceId(nResourceId); } // Private constructor. We have a private constructor here for // static cursors that are loaded through resources. The only reason // to use the private constructor is so that we can assert, rather // than throw, if the cursor couldn't be loaded. Why? Because // throwing in <clinit/> is really rude and will prevent any of windows forms // from initializing. This seems extreme just because we fail to // load a cursor. internal Cursor(string resource, int dummy) { Stream stream = typeof(Cursor).Module.Assembly.GetManifestResourceStream(typeof(Cursor), resource); Debug.Assert(stream != null, "couldn't get stream for resource " + resource); cursorData = new byte[stream.Length]; stream.Read(cursorData, 0, Convert.ToInt32(stream.Length)); // we assume that a cursor is less than 4gig big LoadPicture(new UnsafeNativeMethods.ComStreamFromDataStream(new MemoryStream(cursorData))); } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.Cursor1"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Windows.Forms.Cursor'/> class with the specified handle. /// </para> /// </devdoc> public Cursor(IntPtr handle) { IntSecurity.UnmanagedCode.Demand(); if (handle == IntPtr.Zero) { throw new ArgumentException(SR.GetString(SR.InvalidGDIHandle, (typeof(Cursor)).Name)); } this.handle = handle; this.ownHandle = false; } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.Cursor2"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Windows.Forms.Cursor'/> /// class with /// the specified filename. /// </para> /// </devdoc> public Cursor(string fileName) { //Filestream demands the correct FILEIO access here // FileStream f = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); try { cursorData = new byte[f.Length]; f.Read(cursorData, 0, Convert.ToInt32(f.Length)); // assume that a cursor is less than 4gig... } finally { f.Close(); } LoadPicture(new UnsafeNativeMethods.ComStreamFromDataStream(new MemoryStream(cursorData))); } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.Cursor3"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Windows.Forms.Cursor'/> class from the specified resource. /// </para> /// </devdoc> public Cursor(Type type, string resource) : this(type.Module.Assembly.GetManifestResourceStream(type,resource)) { } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.Cursor4"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Windows.Forms.Cursor'/> class from the /// specified data stream. /// </para> /// </devdoc> public Cursor(Stream stream) { cursorData = new byte[stream.Length]; stream.Read(cursorData, 0, Convert.ToInt32(stream.Length));// assume that a cursor is less than 4gig... LoadPicture(new UnsafeNativeMethods.ComStreamFromDataStream(new MemoryStream(cursorData))); } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.Clip"]/*' /> /// <devdoc> /// <para> /// Gets or /// sets a <see cref='System.Drawing.Rectangle'/> that represents the current clipping rectangle for this <see cref='System.Windows.Forms.Cursor'/> in /// screen coordinates. /// </para> /// </devdoc> public static Rectangle Clip { get { return ClipInternal; } set { if (!value.IsEmpty) { Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "AdjustCursorClip Demanded"); IntSecurity.AdjustCursorClip.Demand(); } ClipInternal = value; } } /// <devdoc> /// Implemented separately to be used internally from safe places. /// </devdoc> internal static Rectangle ClipInternal { get { NativeMethods.RECT r = new NativeMethods.RECT(); SafeNativeMethods.GetClipCursor(ref r); return Rectangle.FromLTRB(r.left, r.top, r.right, r.bottom); } set { if (value.IsEmpty) { UnsafeNativeMethods.ClipCursor(null); } else { NativeMethods.RECT rcClip = NativeMethods.RECT.FromXYWH(value.X, value.Y, value.Width, value.Height); UnsafeNativeMethods.ClipCursor(ref rcClip); } } } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.Current"]/*' /> /// <devdoc> /// <para> /// Gets or /// sets a <see cref='System.Windows.Forms.Cursor'/> that /// represents the current mouse cursor. The value is NULL if the current mouse cursor is not visible. /// </para> /// </devdoc> public static Cursor Current { get { return CurrentInternal; } set { Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "ModifyCursor Demanded"); IntSecurity.ModifyCursor.Demand(); CurrentInternal = value; } } internal static Cursor CurrentInternal { get { IntPtr curHandle = SafeNativeMethods.GetCursor(); // SECREVIEW : This method is to be used internally from safe places. // IntSecurity.UnmanagedCode.Assert(); return Cursors.KnownCursorFromHCursor( curHandle ); // SECREVIEW RevertAssert automatically called on return from function. } set { IntPtr handle = (value == null) ? IntPtr.Zero : value.handle; UnsafeNativeMethods.SetCursor(new HandleRef(value, handle)); } } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.Handle"]/*' /> /// <devdoc> /// <para> /// Gets /// the Win32 handle for this <see cref='System.Windows.Forms.Cursor'/> . /// </para> /// </devdoc> public IntPtr Handle { get { if (handle == IntPtr.Zero) { throw new ObjectDisposedException(SR.GetString(SR.ObjectDisposed, GetType().Name)); } return handle; } } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.Handle"]/*' /> /// <devdoc> /// <para> /// returns the "hot" location of the cursor. /// </para> /// </devdoc> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] //Minor, not worth breaking change public Point HotSpot { get { Point hotSpot = Point.Empty; NativeMethods.ICONINFO info = new NativeMethods.ICONINFO(); Icon currentIcon = null; // SECREVIEW : Safe to assert here, the handle used was created by us and the Icon created is not exposed. // IntSecurity.ObjectFromWin32Handle.Assert(); try { currentIcon = Icon.FromHandle(this.Handle); } finally { CodeAccessPermission.RevertAssert(); } try { SafeNativeMethods.GetIconInfo(new HandleRef(this, currentIcon.Handle), info); hotSpot = new Point(info.xHotspot, info.yHotspot); } finally { // GetIconInfo creates bitmaps for the hbmMask and hbmColor members of ICONINFO. // The calling application must manage these bitmaps and delete them when they are no longer necessary. if (info.hbmMask != IntPtr.Zero) { // ExternalDelete to prevent Handle underflow SafeNativeMethods.ExternalDeleteObject(new HandleRef(null, info.hbmMask)); info.hbmMask = IntPtr.Zero; } if (info.hbmColor != IntPtr.Zero) { // ExternalDelete to prevent Handle underflow SafeNativeMethods.ExternalDeleteObject(new HandleRef(null, info.hbmColor)); info.hbmColor = IntPtr.Zero; } currentIcon.Dispose(); } return hotSpot; } } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.Position"]/*' /> /// <devdoc> /// <para> /// Gets or sets a <see cref='System.Drawing.Point'/> that specifies the current cursor /// position in screen coordinates. /// </para> /// </devdoc> public static Point Position { get { NativeMethods.POINT p = new NativeMethods.POINT(); UnsafeNativeMethods.GetCursorPos(p); return new Point(p.x, p.y); } set { IntSecurity.AdjustCursorPosition.Demand(); UnsafeNativeMethods.SetCursorPos(value.X, value.Y); } } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.Size"]/*' /> /// <devdoc> /// <para> /// Gets /// the size of this <see cref='System.Windows.Forms.Cursor'/> object. /// </para> /// </devdoc> public Size Size { get { if (cursorSize.IsEmpty) { cursorSize = new Size( UnsafeNativeMethods.GetSystemMetrics(NativeMethods.SM_CXCURSOR), UnsafeNativeMethods.GetSystemMetrics(NativeMethods.SM_CYCURSOR) ); } return cursorSize; } } /// <include file='doc\CurSor.uex' path='docs/doc[@for="CurSor.Tag"]/*' /> [ SRCategory(SR.CatData), Localizable(false), Bindable(true), SRDescription(SR.ControlTagDescr), DefaultValue(null), TypeConverter(typeof(StringConverter)), ] public object Tag { get { return userData; } set { userData = value; } } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.CopyHandle"]/*' /> /// <devdoc> /// Duplicates this the Win32 handle of this <see cref='System.Windows.Forms.Cursor'/>. /// </devdoc> public IntPtr CopyHandle() { Size sz = Size; return SafeNativeMethods.CopyImage(new HandleRef(this, Handle), NativeMethods.IMAGE_CURSOR, sz.Width, sz.Height, 0); } /// <devdoc> /// Destroys the Win32 handle of this <see cref='System.Windows.Forms.Cursor'/>, if the /// <see cref='System.Windows.Forms.Cursor'/> /// owns the handle /// </devdoc> private void DestroyHandle() { if (ownHandle) { UnsafeNativeMethods.DestroyCursor(new HandleRef(this, handle)); } } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.Dispose"]/*' /> /// <devdoc> /// Cleans up the resources allocated by this object. Once called, the cursor /// object is no longer useful. /// </devdoc> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } void Dispose(bool disposing) { /*if (picture != null) { picture = null; // If we have no message loop, OLE may block on this call. // Let pent up SendMessage calls go through here. // NativeMethods.MSG msg = new NativeMethods.MSG(); UnsafeNativeMethods.PeekMessage(ref msg, NativeMethods.NullHandleRef, 0, 0, NativeMethods.PM_NOREMOVE | NativeMethods.PM_NOYIELD); }*/ // do we still keep that? if (handle != IntPtr.Zero) { DestroyHandle(); handle = IntPtr.Zero; } } /// <devdoc> /// Draws this image to a graphics object. The drawing command originates on the graphics /// object, but a graphics object generally has no idea how to render a given image. So, /// it passes the call to the actual image. This version crops the image to the given /// dimensions and allows the user to specify a rectangle within the image to draw. /// </devdoc> // This method is way more powerful than what we expose, but I'll leave it in place. private void DrawImageCore(Graphics graphics, Rectangle imageRect, Rectangle targetRect, bool stretch) { // Support GDI+ Translate method targetRect.X += (int) graphics.Transform.OffsetX; targetRect.Y += (int) graphics.Transform.OffsetY; int rop = 0xcc0020; // RasterOp.SOURCE.GetRop(); IntPtr dc = graphics.GetHdc(); try { // want finally clause to release dc int imageX = 0; int imageY = 0; int imageWidth; int imageHeight; int targetX = 0; int targetY = 0; int targetWidth = 0; int targetHeight = 0; Size cursorSize = Size; // compute the dimensions of the icon, if needed // if (!imageRect.IsEmpty) { imageX = imageRect.X; imageY = imageRect.Y; imageWidth = imageRect.Width; imageHeight = imageRect.Height; } else { imageWidth = cursorSize.Width; imageHeight = cursorSize.Height; } if (!targetRect.IsEmpty) { targetX = targetRect.X; targetY = targetRect.Y; targetWidth = targetRect.Width; targetHeight = targetRect.Height; } else { targetWidth = cursorSize.Width; targetHeight = cursorSize.Height; } int drawWidth, drawHeight; int clipWidth, clipHeight; if (stretch) { // Short circuit the simple case of blasting an icon to the // screen // if (targetWidth == imageWidth && targetHeight == imageHeight && imageX == 0 && imageY == 0 && rop == NativeMethods.SRCCOPY && imageWidth == cursorSize.Width && imageHeight == cursorSize.Height) { SafeNativeMethods.DrawIcon(new HandleRef(graphics, dc), targetX, targetY, new HandleRef(this, handle)); return; } drawWidth = cursorSize.Width * targetWidth / imageWidth; drawHeight = cursorSize.Height * targetHeight / imageHeight; clipWidth = targetWidth; clipHeight = targetHeight; } else { // Short circuit the simple case of blasting an icon to the // screen // if (imageX == 0 && imageY == 0 && rop == NativeMethods.SRCCOPY && cursorSize.Width <= targetWidth && cursorSize.Height <= targetHeight && cursorSize.Width == imageWidth && cursorSize.Height == imageHeight) { SafeNativeMethods.DrawIcon(new HandleRef(graphics, dc), targetX, targetY, new HandleRef(this, handle)); return; } drawWidth = cursorSize.Width; drawHeight = cursorSize.Height; clipWidth = targetWidth < imageWidth ? targetWidth : imageWidth; clipHeight = targetHeight < imageHeight ? targetHeight : imageHeight; } if (rop == NativeMethods.SRCCOPY) { // The ROP is SRCCOPY, so we can be simple here and take // advantage of clipping regions. Drawing the cursor // is merely a matter of offsetting and clipping. // SafeNativeMethods.IntersectClipRect(new HandleRef(this, Handle), targetX, targetY, targetX+clipWidth, targetY+clipHeight); SafeNativeMethods.DrawIconEx(new HandleRef(graphics, dc), targetX - imageX, targetY - imageY, new HandleRef(this, handle), drawWidth, drawHeight, 0, NativeMethods.NullHandleRef, NativeMethods.DI_NORMAL); // Let GDI+ restore clipping return; } Debug.Fail("Cursor.Draw does not support raster ops. How did you even pass one in?"); } finally { graphics.ReleaseHdcInternal(dc); } } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.Draw"]/*' /> /// <devdoc> /// <para> /// Draws this <see cref='System.Windows.Forms.Cursor'/> to a <see cref='System.Drawing.Graphics'/>. /// </para> /// </devdoc> public void Draw(Graphics g, Rectangle targetRect) { DrawImageCore(g, Rectangle.Empty, targetRect, false); } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.DrawStretched"]/*' /> /// <devdoc> /// Draws this <see cref='System.Windows.Forms.Cursor'/> to a <see cref='System.Drawing.Graphics'/>. /// </devdoc> public void DrawStretched(Graphics g, Rectangle targetRect) { DrawImageCore(g, Rectangle.Empty, targetRect, true); } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.Finalize"]/*' /> /// <devdoc> /// Cleans up Windows resources for this object. /// </devdoc> ~Cursor() { Dispose(false); } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.ISerializable.GetObjectData"]/*' /> /// <devdoc> /// ISerializable private implementation /// </devdoc> /// <internalonly/> [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.SerializationFormatter)] void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) { if (cursorData != null) { si.AddValue("CursorData", cursorData, typeof(byte[])); } else if (resourceId != 0) { si.AddValue("CursorResourceId", resourceId, typeof(int)); } else { Debug.Fail("Why are we trying to serialize an empty cursor?"); throw new SerializationException(SR.GetString(SR.CursorNonSerializableHandle)); } } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.Hide"]/*' /> /// <devdoc> /// <para> /// Hides the cursor. For every call to Cursor.hide() there must be a /// balancing call to Cursor.show(). /// </para> /// </devdoc> public static void Hide() { Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "AdjustCursorClip Demanded"); IntSecurity.AdjustCursorClip.Demand(); UnsafeNativeMethods.ShowCursor(false); } private void LoadFromResourceId(int nResourceId) { ownHandle = false; // we don't delete stock cursors. // We assert here on exception -- this constructor is used during clinit, // and it would be a shame if we failed to initialize all of windows forms just // just because a cursor couldn't load. // try { resourceId = nResourceId; handle = SafeNativeMethods.LoadCursor(NativeMethods.NullHandleRef, nResourceId); } catch (Exception e) { handle = IntPtr.Zero; Debug.Fail(e.ToString()); } } // this code is adapted from Icon.GetIconSize please take this into account when changing this private Size GetIconSize(IntPtr iconHandle) { Size iconSize = Size; NativeMethods.ICONINFO info = new NativeMethods.ICONINFO(); SafeNativeMethods.GetIconInfo(new HandleRef(this, iconHandle), info); NativeMethods.BITMAP bmp = new NativeMethods.BITMAP(); if (info.hbmColor != IntPtr.Zero) { UnsafeNativeMethods.GetObject(new HandleRef(null, info.hbmColor), Marshal.SizeOf(typeof(NativeMethods.BITMAP)), bmp); SafeNativeMethods.IntDeleteObject(new HandleRef(null, info.hbmColor)); iconSize = new Size(bmp.bmWidth, bmp.bmHeight); } else if (info.hbmMask != IntPtr.Zero) { UnsafeNativeMethods.GetObject(new HandleRef(null, info.hbmMask), Marshal.SizeOf(typeof(NativeMethods.BITMAP)), bmp); iconSize = new Size(bmp.bmWidth, bmp.bmHeight / 2); } if (info.hbmMask != IntPtr.Zero) { SafeNativeMethods.IntDeleteObject(new HandleRef(null, info.hbmMask)); } return iconSize; } /// <devdoc> /// Loads a picture from the requested stream. /// </devdoc> private void LoadPicture(UnsafeNativeMethods.IStream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } try { Guid g = typeof(UnsafeNativeMethods.IPicture).GUID; UnsafeNativeMethods.IPicture picture = null; new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); try { picture = UnsafeNativeMethods.OleCreateIPictureIndirect(null, ref g, true); UnsafeNativeMethods.IPersistStream ipictureAsIPersist = (UnsafeNativeMethods.IPersistStream)picture; ipictureAsIPersist.Load(stream); if (picture != null && picture.GetPictureType() == NativeMethods.Ole.PICTYPE_ICON) { IntPtr cursorHandle = picture.GetHandle(); Size picSize = GetIconSize(cursorHandle); if (DpiHelper.IsScalingRequired) { picSize = DpiHelper.LogicalToDeviceUnits(picSize); } handle = SafeNativeMethods.CopyImageAsCursor(new HandleRef(this, cursorHandle), NativeMethods.IMAGE_CURSOR, picSize.Width, picSize.Height, 0); ownHandle = true; } else { throw new ArgumentException(SR.GetString(SR.InvalidPictureType, "picture", "Cursor"), "picture"); } } finally { CodeAccessPermission.RevertAssert(); // destroy the picture... if(picture != null) { Marshal.ReleaseComObject(picture); } } } catch (COMException e) { Debug.Fail(e.ToString()); throw new ArgumentException(SR.GetString(SR.InvalidPictureFormat), "stream", e); } } /// <devdoc> /// Saves a picture from the requested stream. /// </devdoc> internal void SavePicture(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } if(this.resourceId != 0) { throw new FormatException(SR.GetString(SR.CursorCannotCovertToBytes)); } try { stream.Write(cursorData, 0, cursorData.Length); } catch (SecurityException) { // VSWhidbey 424904 - dont eat security exceptions. throw; } catch (Exception e) { Debug.Fail(e.ToString()); throw new InvalidOperationException(SR.GetString(SR.InvalidPictureFormat)); } } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.Show"]/*' /> /// <devdoc> /// <para> /// Displays the cursor. For every call to Cursor.show() there must have been /// a previous call to Cursor.hide(). /// </para> /// </devdoc> public static void Show() { UnsafeNativeMethods.ShowCursor(true); } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.ToString"]/*' /> /// <devdoc> /// <para> /// Retrieves a human readable string representing this /// <see cref='System.Windows.Forms.Cursor'/> /// . /// </para> /// </devdoc> public override string ToString() { string s = null; if (!this.ownHandle) s = TypeDescriptor.GetConverter(typeof(Cursor)).ConvertToString(this); else s = base.ToString(); return "[Cursor: " + s + "]"; } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.operatorEQ"]/*' /> public static bool operator ==(Cursor left, Cursor right) { if (object.ReferenceEquals(left, null) != object.ReferenceEquals(right, null)) { return false; } if (!object.ReferenceEquals(left, null)) { return (left.handle == right.handle); } else { return true; } } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.operatorNE"]/*' /> public static bool operator !=(Cursor left, Cursor right) { return !(left == right); } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.GetHashCode"]/*' /> public override int GetHashCode() { // Handle is a 64-bit value in 64-bit machines, uncheck here to avoid overflow exceptions. return unchecked((int)handle); } /// <include file='doc\Cursor.uex' path='docs/doc[@for="Cursor.Equals"]/*' /> public override bool Equals(object obj) { if (!(obj is Cursor)) { return false; } return (this == (Cursor)obj); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Services.InventoryService; using System; using System.Collections.Generic; using System.Reflection; namespace OpenSim.Services.HypergridService { /// <summary> /// Hypergrid inventory service. It serves the IInventoryService interface, /// but implements it in ways that are appropriate for inter-grid /// inventory exchanges. Specifically, it does not performs deletions /// and it responds to GetRootFolder requests with the ID of the /// Suitcase folder, not the actual "My Inventory" folder. /// </summary> public class HGInventoryService : XInventoryService, IInventoryService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private UserAccountCache m_Cache; private string m_HomeURL; private IUserAccountService m_UserAccountService; public HGInventoryService(IConfigSource config, string configName) : base(config, configName) { m_log.Debug("[HGInventory Service]: Starting"); if (configName != string.Empty) m_ConfigName = configName; // // Try reading the [InventoryService] section, if it exists // IConfig invConfig = config.Configs[m_ConfigName]; if (invConfig != null) { // realm = authConfig.GetString("Realm", realm); string userAccountsDll = invConfig.GetString("UserAccountsService", string.Empty); if (userAccountsDll == string.Empty) throw new Exception("Please specify UserAccountsService in HGInventoryService configuration"); Object[] args = new Object[] { config }; m_UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(userAccountsDll, args); if (m_UserAccountService == null) throw new Exception(String.Format("Unable to create UserAccountService from {0}", userAccountsDll)); m_HomeURL = Util.GetConfigVarFromSections<string>(config, "HomeURI", new string[] { "Startup", "Hypergrid", m_ConfigName }, String.Empty); m_Cache = UserAccountCache.CreateUserAccountCache(m_UserAccountService); } m_log.Debug("[HG INVENTORY SERVICE]: Starting..."); } public override bool CreateUserInventory(UUID principalID) { // NOGO return false; } public override bool DeleteFolders(UUID principalID, List<UUID> folderIDs) { // NOGO return false; } public override InventoryFolderBase GetFolderForType(UUID principalID, AssetType type) { //m_log.DebugFormat("[HG INVENTORY SERVICE]: GetFolderForType for {0} {0}", principalID, type); return GetRootFolder(principalID); } public override List<InventoryFolderBase> GetInventorySkeleton(UUID principalID) { // NOGO for this inventory service return new List<InventoryFolderBase>(); } public override InventoryItemBase GetItem(InventoryItemBase item) { InventoryItemBase it = base.GetItem(item); if (it != null) { UserAccount user = m_Cache.GetUser(it.CreatorId); // Adjust the creator data if (user != null && it != null && string.IsNullOrEmpty(it.CreatorData)) it.CreatorData = m_HomeURL + ";" + user.FirstName + " " + user.LastName; } return it; } public override InventoryFolderBase GetRootFolder(UUID principalID) { //m_log.DebugFormat("[HG INVENTORY SERVICE]: GetRootFolder for {0}", principalID); // Warp! Root folder for travelers XInventoryFolder[] folders = m_Database.GetFolders( new string[] { "agentID", "folderName" }, new string[] { principalID.ToString(), "My Suitcase" }); if (folders.Length > 0) return ConvertToOpenSim(folders[0]); // make one XInventoryFolder suitcase = CreateFolder(principalID, UUID.Zero, (int)AssetType.Folder, "My Suitcase"); return ConvertToOpenSim(suitcase); } //private bool CreateSystemFolders(UUID principalID, XInventoryFolder suitcase) //{ // CreateFolder(principalID, suitcase.folderID, (int)AssetType.Animation, "Animations"); // CreateFolder(principalID, suitcase.folderID, (int)AssetType.Bodypart, "Body Parts"); // CreateFolder(principalID, suitcase.folderID, (int)AssetType.CallingCard, "Calling Cards"); // CreateFolder(principalID, suitcase.folderID, (int)AssetType.Clothing, "Clothing"); // CreateFolder(principalID, suitcase.folderID, (int)AssetType.Gesture, "Gestures"); // CreateFolder(principalID, suitcase.folderID, (int)AssetType.Landmark, "Landmarks"); // CreateFolder(principalID, suitcase.folderID, (int)AssetType.LostAndFoundFolder, "Lost And Found"); // CreateFolder(principalID, suitcase.folderID, (int)AssetType.Notecard, "Notecards"); // CreateFolder(principalID, suitcase.folderID, (int)AssetType.Object, "Objects"); // CreateFolder(principalID, suitcase.folderID, (int)AssetType.SnapshotFolder, "Photo Album"); // CreateFolder(principalID, suitcase.folderID, (int)AssetType.LSLText, "Scripts"); // CreateFolder(principalID, suitcase.folderID, (int)AssetType.Sound, "Sounds"); // CreateFolder(principalID, suitcase.folderID, (int)AssetType.Texture, "Textures"); // CreateFolder(principalID, suitcase.folderID, (int)AssetType.TrashFolder, "Trash"); // return true; //} // // Use the inherited methods // //public InventoryCollection GetFolderContent(UUID principalID, UUID folderID) //{ //} //public List<InventoryItemBase> GetFolderItems(UUID principalID, UUID folderID) //{ //} //public override bool AddFolder(InventoryFolderBase folder) //{ // // Check if it's under the Suitcase folder // List<InventoryFolderBase> skel = base.GetInventorySkeleton(folder.Owner); // InventoryFolderBase suitcase = GetRootFolder(folder.Owner); // List<InventoryFolderBase> suitDescendents = GetDescendents(skel, suitcase.ID); // foreach (InventoryFolderBase f in suitDescendents) // if (folder.ParentID == f.ID) // { // XInventoryFolder xFolder = ConvertFromOpenSim(folder); // return m_Database.StoreFolder(xFolder); // } // return false; //} // return false; //} public override bool PurgeFolder(InventoryFolderBase folder) { // NOGO return false; } private List<InventoryFolderBase> GetDescendents(List<InventoryFolderBase> lst, UUID root) { List<InventoryFolderBase> direct = lst.FindAll(delegate(InventoryFolderBase f) { return f.ParentID == root; }); if (direct == null) return new List<InventoryFolderBase>(); List<InventoryFolderBase> indirect = new List<InventoryFolderBase>(); foreach (InventoryFolderBase f in direct) indirect.AddRange(GetDescendents(lst, f.ID)); direct.AddRange(indirect); return direct; } // Use inherited method //public bool UpdateFolder(InventoryFolderBase folder) //{ //} //public override bool MoveFolder(InventoryFolderBase folder) //{ // XInventoryFolder[] x = m_Database.GetFolders( // new string[] { "folderID" }, // new string[] { folder.ID.ToString() }); // if (x.Length == 0) // return false; // // Check if it's under the Suitcase folder // List<InventoryFolderBase> skel = base.GetInventorySkeleton(folder.Owner); // InventoryFolderBase suitcase = GetRootFolder(folder.Owner); // List<InventoryFolderBase> suitDescendents = GetDescendents(skel, suitcase.ID); // foreach (InventoryFolderBase f in suitDescendents) // if (folder.ParentID == f.ID) // { // x[0].parentFolderID = folder.ParentID; // return m_Database.StoreFolder(x[0]); // } // Unfortunately we need to use the inherited method because of how DeRez works. // The viewer sends the folderID hard-wired in the derez message //public override bool AddItem(InventoryItemBase item) //{ // // Check if it's under the Suitcase folder // List<InventoryFolderBase> skel = base.GetInventorySkeleton(item.Owner); // InventoryFolderBase suitcase = GetRootFolder(item.Owner); // List<InventoryFolderBase> suitDescendents = GetDescendents(skel, suitcase.ID); // foreach (InventoryFolderBase f in suitDescendents) // if (item.Folder == f.ID) // return m_Database.StoreItem(ConvertFromOpenSim(item)); // return false; //} //public override bool UpdateItem(InventoryItemBase item) //{ // // Check if it's under the Suitcase folder // List<InventoryFolderBase> skel = base.GetInventorySkeleton(item.Owner); // InventoryFolderBase suitcase = GetRootFolder(item.Owner); // List<InventoryFolderBase> suitDescendents = GetDescendents(skel, suitcase.ID); // foreach (InventoryFolderBase f in suitDescendents) // if (item.Folder == f.ID) // return m_Database.StoreItem(ConvertFromOpenSim(item)); // return false; //} //public override bool MoveItems(UUID principalID, List<InventoryItemBase> items) //{ // // Principal is b0rked. *sigh* // // // // Let's assume they all have the same principal // // Check if it's under the Suitcase folder // List<InventoryFolderBase> skel = base.GetInventorySkeleton(items[0].Owner); // InventoryFolderBase suitcase = GetRootFolder(items[0].Owner); // List<InventoryFolderBase> suitDescendents = GetDescendents(skel, suitcase.ID); // foreach (InventoryItemBase i in items) // { // foreach (InventoryFolderBase f in suitDescendents) // if (i.Folder == f.ID) // m_Database.MoveItem(i.ID.ToString(), i.Folder.ToString()); // } // return true; //} // Let these pass. Use inherited methods. //public bool DeleteItems(UUID principalID, List<UUID> itemIDs) //{ //} //public InventoryFolderBase GetFolder(InventoryFolderBase folder) //{ //} //public List<InventoryItemBase> GetActiveGestures(UUID principalID) //{ //} } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using CocosSharp; using System.Diagnostics; using Microsoft.Xna.Framework.Graphics; namespace tests { public class TextureTest : TextureMenuLayer { public TextureTest(bool bControlMenuVisible, int nMaxCases, int nCurCase) : base(bControlMenuVisible, nMaxCases, nCurCase) { } public override void performTests() { // CCTexture2D *texture; // struct timeval now; // CCTextureCache *cache = CCTextureCache::sharedTextureCache(); CCLog.Log("\n\n--------\n\n"); CCLog.Log("--- PNG 128x128 ---\n"); performTestsPNG("Images/test_image"); // CCLog("--- PVR 128x128 ---\n"); // CCLog("RGBA 8888"); // gettimeofday(&now, NULL); // texture = cache->addImage("Images/test_image_rgba8888.pvr"); // if( texture ) // CCLog(" ms:%f\n", calculateDeltaTime(&now) ); // else // CCLog("ERROR\n"); // cache->removeTexture(texture); // // CCLog("BGRA 8888"); // gettimeofday(&now, NULL); // texture = cache->addImage("Images/test_image_bgra8888.pvr"); // if( texture ) // CCLog(" ms:%f\n", calculateDeltaTime(&now) ); // else // CCLog("ERROR\n"); // cache->removeTexture(texture); // // CCLog("RGBA 4444"); // gettimeofday(&now, NULL); // texture = cache->addImage("Images/test_image_rgba4444.pvr"); // if( texture ) // CCLog(" ms:%f\n", calculateDeltaTime(&now) ); // else // CCLog("ERROR\n"); // cache->removeTexture(texture); // // CCLog("RGB 565"); // gettimeofday(&now, NULL); // texture = cache->addImage("Images/test_image_rgb565.pvr"); // if( texture ) // CCLog(" ms:%f\n", calculateDeltaTime(&now) ); // else // CCLog("ERROR\n"); // cache->removeTexture(texture); CCLog.Log("\n\n--- PNG 512x512 ---\n"); performTestsPNG("Images/texture512x512"); // CCLog("--- PVR 512x512 ---\n"); // CCLog("RGBA 4444"); // gettimeofday(&now, NULL); // texture = cache->addImage("Images/texture512x512_rgba4444.pvr"); // if( texture ) // CCLog(" ms:%f\n", calculateDeltaTime(&now) ); // else // CCLog("ERROR\n"); // cache->removeTexture(texture); // // ---- 1024X1024 // RGBA4444 // Empty image // CCLog.Log("\n\nEMPTY IMAGE\n\n"); CCLog.Log("--- PNG 1024x1024 ---\n"); performTestsPNG("Images/texture1024x1024"); // CCLog("--- PVR 1024x1024 ---\n"); // CCLog("RGBA 4444"); // gettimeofday(&now, NULL); // texture = cache->addImage("Images/texture1024x1024_rgba4444.pvr"); // if( texture ) // CCLog(" ms:%f\n", calculateDeltaTime(&now) ); // else // CCLog("ERROR\n"); // cache->removeTexture(texture); // // CCLog("--- PVR.GZ 1024x1024 ---\n"); // CCLog("RGBA 4444"); // gettimeofday(&now, NULL); // texture = cache->addImage("Images/texture1024x1024_rgba4444.pvr.gz"); // if( texture ) // CCLog(" ms:%f\n", calculateDeltaTime(&now) ); // else // CCLog("ERROR\n"); // cache->removeTexture(texture); // // CCLog("--- PVR.CCZ 1024x1024 ---\n"); // CCLog("RGBA 4444"); // gettimeofday(&now, NULL); // texture = cache->addImage("Images/texture1024x1024_rgba4444.pvr.ccz"); // if( texture ) // CCLog(" ms:%f\n", calculateDeltaTime(&now) ); // else // CCLog("ERROR\n"); // cache->removeTexture(texture); // // ---- 1024X1024 // RGBA4444 // SpriteSheet images // CCLog.Log("\n\nSPRITESHEET IMAGE\n\n"); CCLog.Log("--- PNG 1024x1024 ---\n"); performTestsPNG("Images/PlanetCute-1024x1024"); // CCLog("--- PVR 1024x1024 ---\n"); // CCLog("RGBA 4444"); // gettimeofday(&now, NULL); // texture = cache->addImage("Images/PlanetCute-1024x1024-rgba4444.pvr"); // if( texture ) // CCLog(" ms:%f\n", calculateDeltaTime(&now) ); // else // CCLog("ERROR\n"); // cache->removeTexture(texture); // // CCLog("--- PVR.GZ 1024x1024 ---\n"); // CCLog("RGBA 4444"); // gettimeofday(&now, NULL); // texture = cache->addImage("Images/PlanetCute-1024x1024-rgba4444.pvr.gz"); // if( texture ) // CCLog(" ms:%f\n", calculateDeltaTime(&now) ); // else // CCLog("ERROR\n"); // cache->removeTexture(texture); // // CCLog("--- PVR.CCZ 1024x1024 ---\n"); // CCLog("RGBA 4444"); // gettimeofday(&now, NULL); // texture = cache->addImage("Images/PlanetCute-1024x1024-rgba4444.pvr.ccz"); // if( texture ) // CCLog(" ms:%f\n", calculateDeltaTime(&now) ); // else // CCLog("ERROR\n"); // cache->removeTexture(texture); // // ---- 1024X1024 // RGBA8888 // Landscape Image // CCLog.Log("\n\nLANDSCAPE IMAGE\n\n"); CCLog.Log("--- PNG 1024x1024 ---\n"); performTestsPNG("Images/landscape-1024x1024"); // CCLog("--- PVR 1024x1024 ---\n"); // CCLog("RGBA 8888"); // gettimeofday(&now, NULL); // texture = cache->addImage("Images/landscape-1024x1024-rgba8888.pvr"); // if( texture ) // CCLog(" ms:%f\n", calculateDeltaTime(&now) ); // else // CCLog("ERROR\n"); // cache->removeTexture(texture); // // CCLog("--- PVR.GZ 1024x1024 ---\n"); // CCLog("RGBA 8888"); // gettimeofday(&now, NULL); // texture = cache->addImage("Images/landscape-1024x1024-rgba8888.pvr.gz"); // if( texture ) // CCLog(" ms:%f\n", calculateDeltaTime(&now) ); // else // CCLog("ERROR\n"); // cache->removeTexture(texture); // // CCLog("--- PVR.CCZ 1024x1024 ---\n"); // CCLog("RGBA 8888"); // gettimeofday(&now, NULL); // texture = cache->addImage("Images/landscape-1024x1024-rgba8888.pvr.ccz"); // if( texture ) // CCLog(" ms:%f\n", calculateDeltaTime(&now) ); // else // CCLog("ERROR\n"); // cache->removeTexture(texture); // // 2048x2048 // RGBA444 // // most platform don't support texture with width/height is 2048 // CCLog("\n\n--- PNG 2048x2048 ---\n"); // performTestsPNG("Images/texture2048x2048.png"); // CCLog("--- PVR 2048x2048 ---\n"); // CCLog("RGBA 4444"); // gettimeofday(&now, NULL); // texture = cache->addImage("Images/texture2048x2048_rgba4444.pvr"); // if( texture ) // CCLog(" ms:%f\n", calculateDeltaTime(&now) ); // else // CCLog("ERROR\n"); // cache->removeTexture(texture); } public override string title() { return "Texture Performance Test"; } public override string subtitle() { return "See console for results"; } public void performTestsPNG(string filename) { //struct timeval now; DateTime now; CCTexture2D texture; CCTextureCache cache = CCTextureCache.SharedTextureCache; CCLog.Log("RGBA 8888"); CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Color; //gettimeofday(now); texture = cache.AddImage(filename); //if (texture != null) // CCLog.Log(" ms:%f\n", calculateDeltaTime(now)); //else // CCLog.Log(" ERROR\n"); cache.RemoveTexture(texture); CCLog.Log("RGBA 4444"); CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Bgra4444; //gettimeofday(now); texture = cache.AddImage(filename); //if (texture != null) // CCLog.Log(" ms:%f\n", calculateDeltaTime(now)); //else // CCLog.Log(" ERROR\n"); cache.RemoveTexture(texture); CCLog.Log("RGBA 5551"); CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Bgra5551; //gettimeofday(now); texture = cache.AddImage(filename); //if (texture != null) // CCLog.Log(" ms:%f\n", calculateDeltaTime(now)); //else // CCLog.Log(" ERROR\n"); cache.RemoveTexture(texture); CCLog.Log("RGB 565"); CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Bgr565; //gettimeofday(now); texture = cache.AddImage(filename); //if (texture != null) // CCLog.Log(" ms:%f\n", calculateDeltaTime(now)); //else // CCLog.Log(" ERROR\n"); cache.RemoveTexture(texture); CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Color; } public static CCScene scene() { CCScene pScene = new CCScene(AppDelegate.SharedWindow); TextureTest layer = new TextureTest(false, PerformanceTextureTest.TEST_COUNT, PerformanceTextureTest.s_nTexCurCase); pScene.AddChild(layer); return pScene; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.NotificationHubs { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// NamespacesOperations operations. /// </summary> public partial interface INamespacesOperations { /// <summary> /// Checks the availability of the given service namespace across all /// Azure subscriptions. This is useful because the domain name is /// created based on the service namespace name. /// </summary> /// <param name='parameters'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<CheckAvailabilityResult>> CheckAvailabilityWithHttpMessagesAsync(CheckAvailabilityParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates/Updates a service namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a Namespace Resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NamespaceResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Patches the existing namespace /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to patch a Namespace Resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NamespaceResource>> PatchWithHttpMessagesAsync(string resourceGroupName, string namespaceName, NamespacePatchParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an existing namespace. This operation also removes all /// associated notificationHubs under the namespace. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns the description for the specified namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NamespaceResource>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates an authorization rule for a namespace /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// Aauthorization Rule Name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SharedAccessAuthorizationRuleResource>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a namespace authorization rule /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// Authorization Rule Name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets an authorization rule for a namespace by name. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// Authorization rule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SharedAccessAuthorizationRuleResource>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the available namespaces within a resourceGroup. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. If resourceGroupName value is null /// the method lists all the namespaces within subscription /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NamespaceResource>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all the available namespaces within the subscription /// irrespective of the resourceGroups. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NamespaceResource>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the authorization rules for a namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the Primary and Secondary ConnectionStrings to the namespace /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// The connection string of the namespace for the specified /// authorizationRule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ResourceListKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Regenerates the Primary/Secondary Keys to the Namespace /// Authorization Rule /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// The connection string of the namespace for the specified /// authorizationRule. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate the Namespace Authorization Rule /// Key. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ResourceListKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, PolicykeyResource parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an existing namespace. This operation also removes all /// associated notificationHubs under the namespace. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the available namespaces within a resourceGroup. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NamespaceResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all the available namespaces within the subscription /// irrespective of the resourceGroups. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NamespaceResource>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the authorization rules for a namespace. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using Xunit; namespace Jint.Tests.Ecma { public class Test_15_2_3_5 : EcmaTest { [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateMustExistAsAFunction() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-0-1.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateMustExistAsAFunctionTaking2Parameters() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-0-2.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateThrowsTypeerrorIfOIsUndefined() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-1-1.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateTypeerrorIsNotThrownIfOIsNull() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-1-2.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateThrowsTypeerrorIfOIsABooleanPrimitive() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-1-3.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateThrowsTypeerrorIfOIsANumberPrimitive() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-1-4.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateThrowsTypeerrorIfTypeOfFirstParamIsNotObject() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-1.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void CreateSetsThePrototypeOfTheCreatedObjectToFirstParameterThisCanBeCheckedUsingIsprototypeofOrGetprototypeof() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-2-1.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateReturnedObjectIsAnInstanceOfObject() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-2-2.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void CreateSetsThePrototypeOfTheCreatedObjectToFirstParameterThisCanBeCheckedUsingIsprototypeofOrGetprototypeof2() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-3-1.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void CreateSetsThePrototypeOfTheCreatedObjectToFirstParameterThisCanBeCheckedUsingIsprototypeofOrGetprototypeof3() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-1.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateArgumentPropertiesIsTheMathObject15237Step2() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-10.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsNotPresent8105Step4() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-100.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsOwnDataProperty8105Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-101.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsAnInheritedDataProperty8105Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-102.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsOwnDataPropertyThatOverridesAnInheritedDataProperty8105Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-103.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsOwnDataPropertyThatOverridesAnInheritedAccessorProperty8105Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-104.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsOwnAccessorProperty8105Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-105.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsAnInheritedAccessorProperty8105Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-106.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyThatOverridesAnInheritedDataProperty8105Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-107.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyThatOverridesAnInheritedAccessorProperty8105Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-108.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyWithoutAGetFunction8105Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-109.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateArgumentPropertiesIsADateObject15237Step2() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-11.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyWithoutAGetFunctionWhichOverridesAnInheritedAccessorProperty8105Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-110.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsAnInheritedAccessorPropertyWithoutAGetFunction8105Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-111.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAFunctionObjectWhichImplementsItsOwnGetMethodToAccessTheConfigurableProperty8105Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-112.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAnArrayObjectThatUsesObjectSGetMethodToAccessTheConfigurableProperty8105Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-113.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAStringObjectThatUsesObjectSGetMethodToAccessTheConfigurableProperty8105Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-114.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsABooleanObjectThatUsesObjectSGetMethodToAccessTheConfigurableProperty8105Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-115.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsANumberObjectThatUsesObjectSGetMethodToAccessTheConfigurableProperty8105Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-116.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsTheMathObjectThatUsesObjectSGetMethodToAccessTheConfigurableProperty8105Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-117.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsADateObjectThatUsesObjectSGetMethodToAccessTheConfigurableProperty8105Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-118.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsADateObjectThatUsesObjectSGetMethodToAccessTheConfigurableProperty8105Step4A2() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-119.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateArgumentPropertiesIsARegexpObject15237Step2() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-12.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsTheJsonObjectThatUsesObjectSGetMethodToAccessTheConfigurableProperty8105Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-120.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAnErrorObjectThatUsesObjectSGetMethodToAccessTheConfigurableProperty8105Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-121.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAnArgumentsObjectWhichImplementsItsOwnGetMethodToAccessTheConfigurableProperty8105Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-122.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsTheGlobalObjectThatUsesObjectSGetMethodToAccessTheConfigurableProperty8105Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-124.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsUndefined8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-125.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsNull8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-126.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsTrue8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-127.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsFalse8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-128.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIs08105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-129.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateArgumentPropertiesIsTheJsonObject15237Step2() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-13.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIs08105Step4B2() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-130.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIs08105Step4B3() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-131.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsNan8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-132.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsAPositiveNumber8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-133.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsANegativeNumber8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-134.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsAnEmptyString8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-135.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsANonEmptyString8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-136.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsAFunctionObject8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-137.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsAnArrayObject8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-138.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsAStringObject8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-139.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateArgumentPropertiesIsAnErrorObject15237Step2() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-14.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsABooleanObject8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-140.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsANumberObject8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-141.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsTheMathObject8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-142.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsADateObject8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-143.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsARegexpObject8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-144.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsTheJsonObject8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-145.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsAnErrorObject8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-146.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsAnArgumentsObject8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-147.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsTheGlobalObject8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-149.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateArgumentPropertiesIsTheAgumentsObject15237Step2() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-15.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsAStringValueIsFalseWhichIsTreatedAsTheValueTrue8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-150.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsNewBooleanFalseWhichIsTreatedAsTheValueTrue8105Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-151.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateValuePropertyOfOnePropertyInPropertiesIsPresent8105Step5() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-152.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateValuePropertyOfOnePropertyInPropertiesIsNotPresent8105Step5() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-153.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateValuePropertyOfOnePropertyInPropertiesIsOwnDataProperty8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-154.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateValuePropertyOfOnePropertyInPropertiesIsAnInheritedDataProperty8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-155.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateValuePropertyOfOnePropertyInPropertiesIsOwnDataPropertyThatOverridesAnInheritedDataProperty8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-156.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateValuePropertyOfOnePropertyInPropertiesIsOwnDataPropertyThatOverridesAnInheritedAccessorProperty8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-157.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateValuePropertyOfOnePropertyInPropertiesIsOwnAccessorProperty8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-158.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateValuePropertyOfOnePropertyInPropertiesIsAnInheritedAccessorProperty8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-159.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOwnEnumerableDataPropertyInPropertiesIsDefinedInObj15237Step3() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-16.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateValuePropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyThatOverridesAnInheritedDataProperty8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-160.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateValuePropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyThatOverridesAnInheritedAccessorProperty8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-161.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateValuePropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyWithoutAGetFunction8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-162.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateValuePropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyWithoutAGetFunctionWhichOverridesAnInheritedAccessorProperty8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-163.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateValuePropertyOfOnePropertyInPropertiesIsAnInheritedAccessorPropertyWithoutAGetFunction8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-164.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAFunctionObjectWhichImplementsItsOwnGetMethodToAccessTheValueProperty8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-165.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAnArrayObjectThatUsesObjectSGetMethodToAccessTheValueProperty8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-166.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAStringObjectThatUsesObjectSGetMethodToAccessTheValueProperty8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-167.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsABooleanObjectThatUsesObjectSGetMethodToAccessTheValueProperty8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-168.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsANumberObjectThatUsesObjectSGetMethodToAccessTheValueProperty8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-169.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOwnDataPropertyInPropertiesWhichIsNotEnumerableIsNotDefinedInObj15237Step3() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-17.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsTheMathObjectThatUsesObjectSGetMethodToAccessTheValueProperty8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-170.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsADateObjectThatUsesObjectSGetMethodToAccessTheValueProperty8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-171.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsARegexpObjectThatUsesObjectSGetMethodToAccessTheValueProperty8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-172.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsTheJsonObjectThatUsesObjectSGetMethodToAccessTheValueProperty8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-173.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAnErrorObjectThatUsesObjectSGetMethodToAccessTheValueProperty8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-174.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAnArgumentsObjectWhichImplementsItsOwnGetMethodToAccessTheValueProperty8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-175.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsTheGlobalObjectThatUsesObjectSGetMethodToAccessTheValueProperty8105Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-177.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsTrue8105Step6() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-178.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsNotPresent8105Step6() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-179.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateAnEnumerableInheritedDataPropertyInPropertiesIsNotDefinedInObj15237Step3() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-18.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsOwnDataProperty8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-180.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsAnInheritedDataProperty8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-181.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsOwnDataPropertyThatOverridesAnInheritedDataProperty8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-182.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsOwnDataPropertyThatOverridesAnInheritedAccessorProperty8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-183.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsOwnAccessorProperty8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-184.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsAnInheritedAccessorProperty8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-185.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyThatOverridesAnInheritedDataProperty8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-186.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyThatOverridesAnInheritedAccessorProperty8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-187.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyWithoutAGetFunction8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-188.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyWithoutAGetFunctionWhichOverridesAnInheritedAccessorProperty8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-189.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOwnEnumerableAccessorPropertyInPropertiesIsDefinedInObj15237Step3() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-19.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsAnInheritedAccessorPropertyWithoutAGetFunction8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-190.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAFunctionObjectWhichImplementsItsOwnGetMethodToAccessTheWritableProperty8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-191.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAnArrayObjectThatUsesObjectSGetMethodToAccessTheWritableProperty8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-192.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAStringObjectThatUsesObjectSGetMethodToAccessTheWritableProperty8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-193.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsABooleanObjectThatUsesObjectSGetMethodToAccessTheWritableProperty8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-194.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsANumberObjectThatUsesObjectSGetMethodToAccessTheWritableProperty8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-195.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsTheMathObjectThatUsesObjectSGetMethodToAccessTheWritableProperty8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-196.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsADateObjectThatUsesObjectSGetMethodToAccessTheWritableProperty8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-197.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsARegexpObjectThatUsesObjectSGetMethodToAccessTheWritableProperty8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-198.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsTheJsonObjectThatUsesObjectSGetMethodToAccessTheWritableProperty8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-199.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreatePropertiesIsUndefined() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-2.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOwnAccessorPropertyInPropertiesWhichIsNotEnumerableIsNotDefinedInObj15237Step3() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-20.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAnErrorObjectThatUsesObjectSGetMethodToAccessTheWritableProperty8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-200.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAnArgumentsObjectWhichImplementsItsOwnGetMethodToAccessTheWritableProperty8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-201.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsTheGlobalObjectThatUsesObjectSGetMethodToAccessTheWritableProperty8105Step6A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-203.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsUndefined8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-204.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsNull8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-205.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsTrue8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-206.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsFalse8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-207.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIs08105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-208.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIs08105Step6B2() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-209.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateAnEnumerableInheritedAccessorPropertyInPropertiesIsNotDefinedInObj15237Step3() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-21.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIs08105Step6B3() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-210.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsNan8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-211.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsAPositiveNumberPrimitive8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-212.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsANegativeNumberPrimitive8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-213.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsAnEmptyString8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-214.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsANonEmptyString8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-215.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsAFunctionObject8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-216.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsAnArrayObject8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-217.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsAStringObject8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-218.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsABooleanObject8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-219.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOwnEnumerableDataPropertyThatOverridesAnEnumerableInheritedDataPropertyInPropertiesIsDefinedInObj15237Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-22.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsANumberObject8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-220.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsTheMathObject8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-221.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsADateObject8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-222.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsARegexpObject8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-223.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsTheJsonObject8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-224.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsAnErrorObject8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-225.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsAnArgumentsObject8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-226.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsTheGlobalObject8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-228.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsAStringValueIsFalseWhichIsTreatedAsTheValueTrue8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-229.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOwnEnumerableDataPropertyThatOverridesAnEnumerableInheritedAccessorPropertyInPropertiesIsDefinedInObj15237Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-23.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritablePropertyOfOnePropertyInPropertiesIsNewBooleanFalseWhichIsTreatedAsTheValueTrue8105Step6B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-230.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateGetPropertyOfOnePropertyInPropertiesIsPresent8105Step7() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-231.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateGetPropertyOfOnePropertyInPropertiesIsNotPresent8105Step7() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-232.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateGetPropertyOfOnePropertyInPropertiesIsOwnDataProperty8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-233.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateGetPropertyOfOnePropertyInPropertiesIsAnInheritedDataProperty8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-234.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateGetPropertyOfOnePropertyInPropertiesIsOwnDataPropertyThatOverridesAnInheritedDataProperty8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-235.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateGetPropertyOfOnePropertyInPropertiesIsOwnDataPropertyThatOverridesAnInheritedAccessorProperty8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-236.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateGetPropertyOfOnePropertyInPropertiesIsOwnAccessorProperty8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-237.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateGetPropertyOfOnePropertyInPropertiesIsAnInheritedAccessorProperty8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-238.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateGetPropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyThatOverridesAnInheritedDataProperty8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-239.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOwnEnumerableAccessorPropertyThatOverridesAnEnumerableInheritedDataPropertyInPropertiesIsDefinedInObj15237Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-24.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateGetPropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyThatOverridesAnInheritedAccessorProperty8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-240.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateGetPropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyWithoutAGetFunction8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-241.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateGetPropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyWithoutAGetFunctionWhichOverridesAnInheritedAccessorProperty8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-242.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateGetPropertyOfOnePropertyInPropertiesIsAnInheritedAccessorPropertyWithoutAGetFunction8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-243.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAFunctionObjectWhichImplementsItsOwnGetMethodToAccessTheGetProperty8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-244.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAnArrayObjectThatUsesObjectSGetMethodToAccessTheGetProperty8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-245.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAStringObjectThatUsesObjectSGetMethodToAccessTheGetProperty8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-246.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsABooleanObjectThatUsesObjectSGetMethodToAccessTheGetProperty8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-247.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsANumberObjectThatUsesObjectSGetMethodToAccessTheGetProperty8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-248.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsADateObjectThatUsesObjectSGetMethodToAccessTheGetProperty8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-249.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOwnEnumerableAccessorPropertyThatOverridesAnEnumerableInheritedAccessorPropertyInPropertiesIsDefinedInObj15237Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-25.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsARegexpObjectThatUsesObjectSGetMethodToAccessTheGetProperty8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-250.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsTheMathObjectThatUsesObjectSGetMethodToAccessTheGetProperty8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-251.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsTheJsonObjectThatUsesObjectSGetMethodToAccessTheGetProperty8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-252.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAnErrorObjectThatUsesObjectSGetMethodToAccessTheGetProperty8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-253.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAnArgumentsObjectWhichImplementsItsOwnGetMethodToAccessTheGetProperty8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-254.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsTheGlobalObjectThatUsesObjectSGetMethodToAccessTheGetProperty8105Step7A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-256.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateGetPropertyOfOnePropertyInPropertiesIsUndefined8105Step7B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-257.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateGetPropertyOfOnePropertyInPropertiesIsThePrimitiveValueNull8105Step7B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-258.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateGetPropertyOfOnePropertyInPropertiesIsABooleanPrimitive8105Step7B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-259.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateTypeerrorIsThrownWhenOwnEnumerableAccessorPropertyOfPropertiesWithoutAGetFunction15237Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-26.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateGetPropertyOfOnePropertyInPropertiesIsANumberPrimitive8105Step7B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-260.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateGetPropertyOfOnePropertyInPropertiesIsAPrimitiveString8105Step7B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-261.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateGetPropertyOfOnePropertyInPropertiesIsAnArrayObject8105Step7B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-262.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateGetPropertyOfOnePropertyInPropertiesIsAFunction8105Step7B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-263.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSetPropertyOfOnePropertyInPropertiesIsPresent8105Step8() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-266.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSetPropertyOfOnePropertyInPropertiesIsNotPresent8105Step8() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-267.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSetPropertyOfOnePropertyInPropertiesIsOwnDataProperty8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-268.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSetPropertyOfOnePropertyInPropertiesIsAnInheritedDataProperty8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-269.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOwnEnumerableAccessorPropertyInPropertiesWithoutAGetFunctionThatOverridesAnEnumerableInheritedAccessorPropertyInPropertiesIsDefinedInObj15237Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-27.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSetPropertyOfOnePropertyInPropertiesIsOwnDataPropertyThatOverridesAnInheritedDataProperty8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-270.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSetPropertyOfOnePropertyInPropertiesIsOwnDataPropertyThatOverridesAnInheritedAccessorProperty8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-271.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSetPropertyOfOnePropertyInPropertiesIsOwnAccessorProperty8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-272.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSetPropertyOfOnePropertyInPropertiesIsAnInheritedAccessorProperty8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-273.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSetPropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyThatOverridesAnInheritedDataProperty8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-274.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSetPropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyThatOverridesAnInheritedAccessorProperty8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-275.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSetPropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyWithoutAGetFunction8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-276.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSetPropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyWithoutAGetFunctionWhichOverridesAnInheritedAccessorProperty8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-277.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSetPropertyOfOnePropertyInPropertiesIsAnInheritedAccessorPropertyWithoutAGetFunction8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-278.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAFunctionObjectWhichImplementsItsOwnGetMethodToAccessTheSetProperty8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-279.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreatePropertiesIsAFunctionObjectWhichImplementsItsOwnGetMethodToAccessOwnEnumerableProperty15237Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-28.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAnArrayObjectThatUsesObjectSGetMethodToAccessTheSetProperty8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-280.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAStringObjectThatUsesObjectSGetMethodToAccessTheSetProperty8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-281.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsABooleanObjectThatUsesObjectSGetMethodToAccessTheSetProperty8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-282.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsANumberObjectThatUsesObjectSGetMethodToAccessTheSetProperty8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-283.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsTheMathObjectThatUsesObjectSGetMethodToAccessTheSetProperty8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-284.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsADateObjectThatUsesObjectSGetMethodToAccessTheSetProperty8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-285.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsARegexpObjectThatUsesObjectSGetMethodToAccessTheSetProperty8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-286.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsTheJsonObjectThatUsesObjectSGetMethodToAccessTheSetProperty8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-287.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAnErrorObjectThatUsesObjectSGetMethodToAccessTheSetProperty8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-288.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAnArgumentsObjectWhichImplementsItsOwnGetMethodToAccessTheSetProperty8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-289.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreatePropertiesIsAnArrayObjectThatUsesObjectSGetMethodToAccessOwnEnumerableProperty15237Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-29.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsTheGlobalObjectThatUsesObjectSGetMethodToAccessTheSetProperty8105Step8A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-291.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSetPropertyOfOnePropertyInPropertiesIsUndefined8105Step8B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-292.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSetPropertyOfOnePropertyInPropertiesIsAPrimitiveValueNull8105Step8B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-293.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSetPropertyOfOnePropertyInPropertiesIsAPrimitiveBooleanValueTrue8105Step8B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-294.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSetPropertyOfOnePropertyInPropertiesIsAPrimitiveNumberValue8105Step8B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-295.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSetPropertyOfOnePropertyInPropertiesIsAPrimitiveStringValue8105Step8B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-296.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSetPropertyOfOnePropertyInPropertiesIsAnDateObject8105Step8B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-297.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSetPropertyOfOnePropertyInPropertiesIsAFunction8105Step8B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-298.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateThrowsTypeerrorIfPropertiesIsNull15237Step2() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-3.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreatePropertiesIsAStringObjectThatUsesObjectSGetMethodToAccessOwnEnumerableProperty15237Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-30.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSetPropertyOfOnePropertyInPropertiesIsAHostObjectThatIsnTCallable8105Step8B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-300.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateTypeerrorIsThrownIfBothSetPropertyAndValuePropertyOfOnePropertyInPropertiesArePresent8105Step9A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-301.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateTypeerrorIsThrownIfBothSetPropertyAndWritablePropertyOfOnePropertyInPropertiesArePresent8105Step9A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-302.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateTypeerrorIsThrownIfBothGetPropertyAndValuePropertyOfOnePropertyInPropertiesArePresent8105Step9A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-303.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateTypeerrorIsThrownIfBothGetPropertyAndWritablePropertyOfOnePropertyInPropertiesArePresent8105Step9A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-304.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateDefinesADataPropertyWhenOnePropertyInPropertiesIsGenericDescriptor8129Step4A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-305.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateValueIsSetAsUndefinedIfItIsAbsentInDataDescriptorOfOnePropertyInProperties8129Step4AI() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-306.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateWritableIsSetAsFalseIfItIsAbsentInDataDescriptorOfOnePropertyInProperties8129Step4AI() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-307.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerableIsSetAsFalseIfItIsAbsentInDataDescriptorOfOnePropertyInProperties8129Step4AI() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-308.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurableIsSetAsFalseIfItIsAbsentInDataDescriptorOfOnePropertyInProperties8129Step4AI() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-309.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreatePropertiesIsABooleanObjectThatUsesObjectSGetMethodToAccessOwnEnumerableProperty15237Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-31.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateGetIsSetAsUndefinedIfItIsAbsentInAccessorDescriptorOfOnePropertyInProperties8129Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-310.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSetIsSetAsUndefinedIfItIsAbsentInAccessorDescriptorOfOnePropertyInProperties8129Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-311.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerableIsSetAsFalseIfItIsAbsentInAccessorDescriptorOfOnePropertyInProperties8129Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-312.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurableIsSetAsFalseIfItIsAbsentInAccessorDescriptorOfOnePropertyInProperties8129Step4B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-313.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateSomeEnumerableOwnPropertyInPropertiesIsEmptyObject15237Step7() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-314.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateAllPropertiesInPropertiesAreEnumerableDataPropertyAndAccessorProperty15237Step7() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-315.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertiesOfPropertiesAreGivenNumericalNames15237Step7() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-316.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreatePropertiesIsANumberObjectThatUsesObjectSGetMethodToAccessOwnEnumerableProperty15237Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-32.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreatePropertiesIsTheMathObjectThatUsesObjectSGetMethodToAccessOwnEnumerableProperty15237Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-33.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreatePropertiesIsADateObjectThatUsesObjectSGetMethodToAccessOwnEnumerableProperty15237Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-34.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreatePropertiesIsARegexpObjectThatUsesObjectSGetMethodToAccessOwnEnumerableProperty15237Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-35.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreatePropertiesIsTheJsonObjectThatUsesObjectSGetMethodToAccessOwnEnumerableProperty15237Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-36.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreatePropertiesIsAnErrorObjectThatUsesObjectSGetMethodToAccessOwnEnumerableProperty15237Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-37.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreatePropertiesIsAnArgumentsObjectWhichImplementsItsOwnGetMethodToAccessOwnEnumerableProperty15237Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-38.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnsureThatSideEffectsOfGetsOccurInTheSameOrderAsTheyWouldForForPInPropsPropsP15237Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-39.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateArgumentPropertiesIsAnObject15237Step2() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-4.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnsureThatIfAnExceptionIsThrownItOccursInTheCorrectOrderRelativeToPriorAndSubsequentSideEffects15237Step5A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-40.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateValueOfOnePropertyInPropertiesIsUndefined8105Step1() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-41.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateValueOfOnePropertyInPropertiesIsNull8105Step1() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-42.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateValueOfOnePropertyInPropertiesIsFalse8105Step1() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-43.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateValueOfOnePropertyInPropertiesIsANumberPrimitive8105Step1() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-44.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateValueOfOnePropertyInPropertiesIsAString8105Step1() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-45.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsTrue8105Step3() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-46.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsNotPresent8105Step3() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-47.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsOwnDataProperty8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-48.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsAnInheritedDataProperty8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-49.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateArgumentPropertiesIsAFunctionObject15237Step2() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-5.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsOwnDataPropertyThatOverridesAnInheritedDataProperty8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-50.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsOwnDataPropertyThatOverridesAnInheritedAccessorProperty8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-51.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsOwnAccessorProperty8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-52.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsAnInheritedAccessorProperty8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-53.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyThatOverridesAnInheritedDataProperty8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-54.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyThatOverridesAnInheritedAccessorProperty8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-55.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyWithoutAGetFunction8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-56.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsOwnAccessorPropertyWithoutAGetFunctionWhichOverridesAnInheritedAccessorProperty8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-57.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsAnInheritedAccessorPropertyWithoutAGetFunction8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-58.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAFunctionObjectWhichImplementsItsOwnGetMethodToAccessTheEnumerableProperty8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-59.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateArgumentPropertiesIsAnArrayObject15237Step2() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-6.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAnArrayObjectThatUsesObjectSGetMethodToAccessTheEnumerableProperty8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-60.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAStringObjectThatUsesObjectSGetMethodToAccessTheEnumerableProperty8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-61.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsABooleanObjectThatUsesObjectSGetMethodToAccessTheEnumerableProperty8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-62.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsANumberObjectThatUsesObjectSGetMethodToAccessTheEnumerableProperty8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-63.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsTheMathObjectThatUsesObjectSGetMethodToAccessTheEnumerableProperty8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-64.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsADateObjectThatUsesObjectSGetMethodToAccessTheEnumerableProperty8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-65.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsARegexpObjectThatUsesObjectSGetMethodToAccessTheEnumerableProperty8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-66.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsTheJsonObjectThatUsesObjectSGetMethodToAccessTheEnumerableProperty8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-67.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAnErrorObjectThatUsesObjectSGetMethodToAccessTheEnumerableProperty8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-68.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsAnArgumentsObjectWhichImplementsItsOwnGetMethodToAccessTheEnumerableProperty8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-69.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateArgumentPropertiesIsAStringObject15237Step2() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-7.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateOnePropertyInPropertiesIsTheGlobalObjectThatUsesObjectSGetMethodToAccessTheEnumerableProperty8105Step3A() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-71.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsUndefined8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-72.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateValueOfEnumerablePropertyOfOnePropertyInPropertiesIsNull8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-73.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsTrue8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-74.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsFalse8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-75.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIs08105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-76.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIs08105Step3B2() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-77.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIs08105Step3B3() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-78.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsNan8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-79.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateArgumentPropertiesIsABooleanObjectWhosePrimitiveValueIsTrue15237Step2() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-8.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsAPositiveNumberPrimitive8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-80.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsANegativeNumberPrimitive8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-81.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsAnEmptyString8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-82.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsANonEmptyString8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-83.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsAFunctionObject8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-84.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsAnArrayObject8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-85.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsAStringObject8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-86.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsABooleanObject8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-87.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsANumberObject8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-88.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsTheMathObject8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-89.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateArgumentPropertiesIsANumberObjectWhosePrimitiveValueIsAnyInterestingNumber15237Step2() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-9.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsADateObject8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-90.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsARegexpObject8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-91.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsTheJsonObject8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-92.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsAnErrorObject8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-93.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsAnArgumentsObject8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-94.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsTheGlobalObject8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-96.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsAStringValueIsFalseWhichIsTreatedAsTheValueTrue8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-97.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateEnumerablePropertyOfOnePropertyInPropertiesIsNewBooleanFalseWhichIsTreatedAsTheValueTrue8105Step3B() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-98.js", false); } [Fact] [Trait("Category", "15.2.3.5")] public void ObjectCreateConfigurablePropertyOfOnePropertyInPropertiesIsTrue8105Step4() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-99.js", false); } } }
using System; using System.Collections.Generic; using System.IO; using System.Net.Mail; using System.Text; using System.Text.RegularExpressions; using OpenPop.Mime.Header; using OpenPop.Mime.Traverse; namespace OpenPop.Mime { /// <summary> /// This is the root of the email tree structure.<br/> /// <see cref="Mime.MessagePart"/> for a description about the structure.<br/> /// <br/> /// A Message (this class) contains the headers of an email message such as: /// <code> /// - To /// - From /// - Subject /// - Content-Type /// - Message-ID /// </code> /// which are located in the <see cref="Headers"/> property.<br/> /// <br/> /// Use the <see cref="Message.MessagePart"/> property to find the actual content of the email message. /// </summary> /// <example> /// Examples are available on the <a href="http://hpop.sourceforge.net/">project homepage</a>. /// </example> public class Message { private static Regex _trimEndRegex = new Regex( "\\r\\n$", RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled ); #region Public properties /// <summary> /// Headers of the Message. /// </summary> public MessageHeader Headers { get; private set; } /// <summary> /// This is the body of the email Message.<br/> /// <br/> /// If the body was parsed for this Message, this property will never be <see langword="null"/>. /// </summary> public MessagePart MessagePart { get; private set; } /// <summary> /// The raw content from which this message has been constructed.<br/> /// These bytes can be persisted and later used to recreate the Message. /// </summary> public byte[] RawMessage { get; private set; } #endregion #region Constructors /// <summary> /// Convenience constructor for <see cref="Mime.Message(byte[], bool)"/>.<br/> /// <br/> /// Creates a message from a byte array. The full message including its body is parsed. /// </summary> /// <param name="rawMessageContent">The byte array which is the message contents to parse</param> public Message(byte[] rawMessageContent) : this(rawMessageContent, true) { } /// <summary> /// Constructs a message from a byte array.<br/> /// <br/> /// The headers are always parsed, but if <paramref name="parseBody"/> is <see langword="false"/>, the body is not parsed. /// </summary> /// <param name="rawMessageContent">The byte array which is the message contents to parse</param> /// <param name="parseBody"> /// <see langword="true"/> if the body should be parsed, /// <see langword="false"/> if only headers should be parsed out of the <paramref name="rawMessageContent"/> byte array /// </param> public Message(byte[] rawMessageContent, bool parseBody) { RawMessage = rawMessageContent; // Find the headers and the body parts of the byte array MessageHeader headersTemp; byte[] body; HeaderExtractor.ExtractHeadersAndBody(rawMessageContent, out headersTemp, out body); // Set the Headers property Headers = headersTemp; // Should we also parse the body? if (parseBody) { // Parse the body into a MessagePart MessagePart = new MessagePart(body, Headers); } } #endregion /// <summary> /// This method will convert this <see cref="Message"/> into a <see cref="MailMessage"/> equivalent.<br/> /// The returned <see cref="MailMessage"/> can be used with <see cref="System.Net.Mail.SmtpClient"/> to forward the email.<br/> /// <br/> /// You should be aware of the following about this method: /// <list type="bullet"> /// <item> /// All sender and receiver mail addresses are set. /// If you send this email using a <see cref="System.Net.Mail.SmtpClient"/> then all /// receivers in To, From, Cc and Bcc will receive the email once again. /// </item> /// <item> /// If you view the source code of this Message and looks at the source code of the forwarded /// <see cref="MailMessage"/> returned by this method, you will notice that the source codes are not the same. /// The content that is presented by a mail client reading the forwarded <see cref="MailMessage"/> should be the /// same as the original, though. /// </item> /// <item> /// Content-Disposition headers will not be copied to the <see cref="MailMessage"/>. /// It is simply not possible to set these on Attachments. /// </item> /// <item> /// HTML content will be treated as the preferred view for the <see cref="MailMessage.Body"/>. Plain text content will be used for the /// <see cref="MailMessage.Body"/> when HTML is not available. /// </item> /// </list> /// </summary> /// <returns>A <see cref="MailMessage"/> object that contains the same information that this Message does</returns> public MailMessage ToMailMessage() { // Construct an empty MailMessage to which we will gradually build up to look like the current Message object (this) MailMessage message = new MailMessage(); message.Subject = Headers.Subject; // We here set the encoding to be UTF-8 // We cannot determine what the encoding of the subject was at this point. // But since we know that strings in .NET is stored in UTF, we can // use UTF-8 to decode the subject into bytes message.SubjectEncoding = Encoding.UTF8; // The HTML version should take precedent over the plain text if it is available MessagePart preferredVersion = FindFirstHtmlVersion(); if ( preferredVersion != null ) { // Make sure that the IsBodyHtml property is being set correctly for our content message.IsBodyHtml = true; } else { // otherwise use the first plain text version as the body, if it exists preferredVersion = FindFirstPlainTextVersion(); } if (preferredVersion != null) { message.Body = preferredVersion.GetBodyAsText(); message.BodyEncoding = preferredVersion.BodyEncoding; } // Add body and alternative views (html and such) to the message IEnumerable<MessagePart> textVersions = FindAllTextVersions(); foreach (MessagePart textVersion in textVersions) { // The textVersions also contain the preferred version, therefore // we should skip that one if (textVersion == preferredVersion) continue; MemoryStream stream = new MemoryStream(textVersion.Body); AlternateView alternative = new AlternateView(stream); alternative.ContentId = textVersion.ContentId; alternative.ContentType = textVersion.ContentType; message.AlternateViews.Add(alternative); } // Add attachments to the message IEnumerable<MessagePart> attachments = FindAllAttachments(); foreach (MessagePart attachmentMessagePart in attachments) { MemoryStream stream = new MemoryStream(attachmentMessagePart.Body); Attachment attachment = new Attachment(stream, attachmentMessagePart.ContentType); attachment.ContentId = attachmentMessagePart.ContentId; message.Attachments.Add(attachment); } if(Headers.From != null && Headers.From.HasValidMailAddress) message.From = Headers.From.MailAddress; if (Headers.ReplyTo != null && Headers.ReplyTo.HasValidMailAddress) message.ReplyTo = Headers.ReplyTo.MailAddress; if(Headers.Sender != null && Headers.Sender.HasValidMailAddress) message.Sender = Headers.Sender.MailAddress; foreach (RfcMailAddress to in Headers.To) { if(to.HasValidMailAddress) message.To.Add(to.MailAddress); } foreach (RfcMailAddress cc in Headers.Cc) { if (cc.HasValidMailAddress) message.CC.Add(cc.MailAddress); } foreach (RfcMailAddress bcc in Headers.Bcc) { if (bcc.HasValidMailAddress) message.Bcc.Add(bcc.MailAddress); } message.Body = _trimEndRegex.Replace(message.Body, ""); foreach (var headerKey in Headers.UnknownHeaders.AllKeys) { message.Headers.Add(headerKey, Headers.UnknownHeaders.Get(headerKey)); } return message; } #region MessagePart Searching Methods /// <summary> /// Finds the first text/plain <see cref="MessagePart"/> in this message.<br/> /// This is a convenience method - it simply propagates the call to <see cref="FindFirstMessagePartWithMediaType"/>.<br/> /// <br/> /// If no text/plain version is found, <see langword="null"/> is returned. /// </summary> /// <returns> /// <see cref="MessagePart"/> which has a MediaType of text/plain or <see langword="null"/> /// if such <see cref="MessagePart"/> could not be found. /// </returns> public MessagePart FindFirstPlainTextVersion() { return FindFirstMessagePartWithMediaType("text/plain"); } /// <summary> /// Finds the first text/html <see cref="MessagePart"/> in this message.<br/> /// This is a convenience method - it simply propagates the call to <see cref="FindFirstMessagePartWithMediaType"/>.<br/> /// <br/> /// If no text/html version is found, <see langword="null"/> is returned. /// </summary> /// <returns> /// <see cref="MessagePart"/> which has a MediaType of text/html or <see langword="null"/> /// if such <see cref="MessagePart"/> could not be found. /// </returns> public MessagePart FindFirstHtmlVersion() { return FindFirstMessagePartWithMediaType("text/html"); } /// <summary> /// Finds all the <see cref="MessagePart"/>'s which contains a text version.<br/> /// <br/> /// <see cref="Mime.MessagePart.IsText"/> for MessageParts which are considered to be text versions.<br/> /// <br/> /// Examples of MessageParts media types are: /// <list type="bullet"> /// <item>text/plain</item> /// <item>text/html</item> /// <item>text/xml</item> /// </list> /// </summary> /// <returns>A List of MessageParts where each part is a text version</returns> public List<MessagePart> FindAllTextVersions() { return new TextVersionFinder().VisitMessage(this); } /// <summary> /// Finds all the <see cref="MessagePart"/>'s which are attachments to this message.<br/> /// <br/> /// <see cref="Mime.MessagePart.IsAttachment"/> for MessageParts which are considered to be attachments. /// </summary> /// <returns>A List of MessageParts where each is considered an attachment</returns> public List<MessagePart> FindAllAttachments() { return new AttachmentFinder().VisitMessage(this); } /// <summary> /// Finds the first <see cref="MessagePart"/> in the <see cref="Message"/> hierarchy with the given MediaType.<br/> /// <br/> /// The search in the hierarchy is a depth-first traversal. /// </summary> /// <param name="mediaType">The MediaType to search for. Case is ignored.</param> /// <returns> /// A <see cref="MessagePart"/> with the given MediaType or <see langword="null"/> if no such <see cref="MessagePart"/> was found /// </returns> public MessagePart FindFirstMessagePartWithMediaType(string mediaType) { return new FindFirstMessagePartWithMediaType().VisitMessage(this, mediaType); } /// <summary> /// Finds all the <see cref="MessagePart"/>s in the <see cref="Message"/> hierarchy with the given MediaType. /// </summary> /// <param name="mediaType">The MediaType to search for. Case is ignored.</param> /// <returns> /// A List of <see cref="MessagePart"/>s with the given MediaType.<br/> /// The List might be empty if no such <see cref="MessagePart"/>s were found.<br/> /// The order of the elements in the list is the order which they are found using /// a depth first traversal of the <see cref="Message"/> hierarchy. /// </returns> public List<MessagePart> FindAllMessagePartsWithMediaType(string mediaType) { return new FindAllMessagePartsWithMediaType().VisitMessage(this, mediaType); } #endregion #region Message Persistence /// <summary> /// Save this <see cref="Message"/> to a file.<br/> /// <br/> /// Can be loaded at a later time using the <see cref="Load(FileInfo)"/> method. /// </summary> /// <param name="file">The File location to save the <see cref="Message"/> to. Existent files will be overwritten.</param> /// <exception cref="ArgumentNullException">If <paramref name="file"/> is <see langword="null"/></exception> /// <exception>Other exceptions relevant to using a <see cref="FileStream"/> might be thrown as well</exception> public void Save(FileInfo file) { if (file == null) throw new ArgumentNullException("file"); using (FileStream stream = new FileStream(file.FullName, FileMode.OpenOrCreate)) { Save(stream); } } /// <summary> /// Save this <see cref="Message"/> to a stream.<br/> /// </summary> /// <param name="messageStream">The stream to write to</param> /// <exception cref="ArgumentNullException">If <paramref name="messageStream"/> is <see langword="null"/></exception> /// <exception>Other exceptions relevant to <see cref="Stream.Write"/> might be thrown as well</exception> public void Save(Stream messageStream) { if (messageStream == null) throw new ArgumentNullException("messageStream"); messageStream.Write(RawMessage, 0, RawMessage.Length); } /// <summary> /// Loads a <see cref="Message"/> from a file containing a raw email. /// </summary> /// <param name="file">The File location to load the <see cref="Message"/> from. The file must exist.</param> /// <exception cref="ArgumentNullException">If <paramref name="file"/> is <see langword="null"/></exception> /// <exception cref="FileNotFoundException">If <paramref name="file"/> does not exist</exception> /// <exception>Other exceptions relevant to a <see cref="FileStream"/> might be thrown as well</exception> /// <returns>A <see cref="Message"/> with the content loaded from the <paramref name="file"/></returns> public static Message Load(FileInfo file) { if (file == null) throw new ArgumentNullException("file"); if (!file.Exists) throw new FileNotFoundException("Cannot load message from non-existent file", file.FullName); using (FileStream stream = new FileStream(file.FullName, FileMode.Open)) { return Load(stream); } } /// <summary> /// Loads a <see cref="Message"/> from a <see cref="Stream"/> containing a raw email. /// </summary> /// <param name="messageStream">The <see cref="Stream"/> from which to load the raw <see cref="Message"/></param> /// <exception cref="ArgumentNullException">If <paramref name="messageStream"/> is <see langword="null"/></exception> /// <exception>Other exceptions relevant to <see cref="Stream.Read"/> might be thrown as well</exception> /// <returns>A <see cref="Message"/> with the content loaded from the <paramref name="messageStream"/></returns> public static Message Load(Stream messageStream) { if (messageStream == null) throw new ArgumentNullException("messageStream"); using (MemoryStream outStream = new MemoryStream()) { #if DOTNET4 // TODO: Enable using native v4 framework methods when support is formally added. messageStream.CopyTo(outStream); #else int bytesRead; byte[] buffer = new byte[4096]; while ((bytesRead = messageStream.Read(buffer, 0, 4096)) > 0) { outStream.Write(buffer, 0, bytesRead); } #endif byte[] content = outStream.ToArray(); return new Message(content); } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Foundation; using MonoTouch.UIKit; using QuartzSample; using MonoTouch.CoreGraphics; using System.Drawing; namespace QuartzSample { public partial class QuartzBlendingViewController : QuartzViewController { #region Constructors // The IntPtr and initWithCoder constructors are required for items that need // to be able to be created from a xib rather than from managed code public QuartzBlendingViewController (IntPtr handle) : base (handle) { Initialize (); } [Export ("initWithCoder:")] public QuartzBlendingViewController (NSCoder coder) : base (coder) { Initialize (); } public QuartzBlendingViewController () : base ("QuartzBlendingViewController", null) { Initialize (); } public QuartzBlendingViewController (CreateView creator, string title, string info) : base (creator, "QuartzBlendingViewController", title, info) { Array.Sort (Colors, ColorSortByLuminance); } void Initialize () { } #endregion static UIColor [] Colors = new UIColor [] { UIColor.Red, UIColor.Green, UIColor.Blue, UIColor.Yellow, UIColor.Magenta, UIColor.Cyan, UIColor.Orange, UIColor.Purple, UIColor.Brown, UIColor.White, UIColor.LightGray, UIColor.DarkGray, UIColor.Black }; static string [] BlendModes = new string [] { "Normal", "Multiply", "Screen", "Overlay", "Darken", "Lighten", "ColorDodge", "ColorBurn", "SoftLight", "HardLight", "Difference", "Exclusion", "Hue", "Saturation", "Color", "Luminosity", // Porter-Duff Blend Modes "Clear", "Copy", "SourceIn", "SourceOut", "SourceAtop", "DestinationOver", "DestinationIn", "DestinationOut", "DestinationAtop", "XOR", "PlusDarker", "PlusLighter", }; public override void ViewDidLoad () { base.ViewDidLoad (); picker.Model = new BlendSelector (this); var qbv = (QuartzBlendingView) quartzView; picker.Select (Array.IndexOf (Colors, qbv.DestinationColor), 0, false); picker.Select (Array.IndexOf (Colors, qbv.SourceColor), 1, false); picker.Select ((int) qbv.BlendMode, 2, false); } static float LuminanceForColor (UIColor color) { CGColor cgcolor = color.CGColor; var components = cgcolor.Components; float luminance = 0; switch (cgcolor.ColorSpace.Model){ case CGColorSpaceModel.Monochrome: // For grayscale colors, the luminance is the color value luminance = components[0]; break; case CGColorSpaceModel.RGB: // For RGB colors, we calculate luminance assuming sRGB Primaries as per // http://en.wikipedia.org/wiki/Luminance_(relative) luminance = 0.2126f * components[0] + 0.7152f * components[1] + 0.0722f * components[2]; break; default: // We don't implement support for non-gray, non-rgb colors at this time. // Since our only consumer is colorSortByLuminance, we return a larger than normal // value to ensure that these types of colors are sorted to the end of the list. luminance = 2.0f; break; } return luminance; } // Simple comparison function that sorts the two (presumed) UIColors according to their luminance value. static int ColorSortByLuminance (UIColor color1, UIColor color2) { float luminance1 = LuminanceForColor(color1); float luminance2 = LuminanceForColor(color2); if (luminance1 == luminance2) return 0; else if (luminance1 < luminance2) return -1; else return 1; } public class BlendSelector : UIPickerViewModel { QuartzBlendingViewController parent; public BlendSelector (QuartzBlendingViewController parent) { this.parent = parent; } public override int GetComponentCount (UIPickerView picker){ return 3; } public override int GetRowsInComponent (UIPickerView picker, int component) { if (component == 0 || component == 1) return Colors.Length; return BlendModes.Length; } public override float GetComponentWidth (UIPickerView picker, int component) { if (component == 0 || component == 1) return 48f; return 192f; } const int kColorTag = 1; const int kLabelTag = 1; public override UIView GetView (UIPickerView picker, int row, int component, UIView view) { var size = picker.RowSizeForComponent (component); if (component == 0 || component == 1){ if (view == null || view.Tag != kColorTag){ view = new UIView (new RectangleF (0, 0, size.Width-4, size.Height-4)){ Tag = kColorTag }; } view.BackgroundColor = Colors [row]; } else { if (view == null || view.Tag != kLabelTag){ view = new UILabel (new RectangleF (0, 0, size.Width-4, size.Height-4)){ Tag = kLabelTag, Opaque = false, BackgroundColor = UIColor.Clear }; } var label = (UILabel) view; label.TextColor = UIColor.Black; label.Text = BlendModes [row]; label.Font = UIFont.BoldSystemFontOfSize (18f); } return view; } public override void Selected (UIPickerView picker, int row, int component) { var qbv = (QuartzBlendingView) parent.quartzView; qbv.DestinationColor = Colors [picker.SelectedRowInComponent (0)]; qbv.SourceColor = Colors [picker.SelectedRowInComponent (1)]; qbv.BlendMode = (CGBlendMode) picker.SelectedRowInComponent (2); qbv.SetNeedsDisplay (); } } } public class QuartzBlendingView : QuartzView { public UIColor SourceColor { get; set; } public UIColor DestinationColor { get; set; } public CGBlendMode BlendMode { get; set; } public QuartzBlendingView () : base () { SourceColor = UIColor.White; DestinationColor = UIColor.Black; BlendMode = CGBlendMode.Normal; } public override void DrawInContext (CGContext context) { // Start with a background whose color we don't use in the demo context.SetGrayFillColor (0.2f, 1); context.FillRect (Bounds); // We want to just lay down the background without any blending so we use the Copy mode rather than Normal context.SetBlendMode(CGBlendMode.Copy); // Draw a rect with the "background" color - this is the "Destination" for the blending formulas context.SetFillColorWithColor (DestinationColor.CGColor); context.FillRect(new RectangleF (110, 20, 100, 100)); // Set up our blend mode context.SetBlendMode (BlendMode); // And draw a rect with the "foreground" color - this is the "Source" for the blending formulas context.SetFillColorWithColor (SourceColor.CGColor); context.FillRect (new RectangleF (60, 45, 200, 50)); } } }
using System; using System.Linq; using System.Reflection; using System.Collections.Generic; using UnityEngine; using UnityEngine.Experimental.VFX; using UnityEngine.Experimental.VFX.Utility; using UnityEditor.Experimental.VFX; using UnityEditor.VFX; using UnityEditor; using UnityEditorInternal; namespace UnityEditor.Experimental.VFX.Utility { [CustomEditor(typeof(VFXParameterBinder))] public class VFXParameterBinderEditor : Editor { ReorderableList m_List; SerializedProperty m_Elements; SerializedProperty m_Component; SerializedProperty m_ExecuteInEditor; GenericMenu m_Menu; VFXBinderEditor m_ElementEditor; static readonly Color validColor = new Color(0.5f, 1.0f, 0.2f); static readonly Color invalidColor = new Color(1.0f, 0.5f, 0.2f); static readonly Color errorColor = new Color(1.0f, 0.2f, 0.2f); static class Styles { public static GUIStyle labelStyle; static Styles() { labelStyle = new GUIStyle(EditorStyles.label) { padding = new RectOffset(20, 0, 2, 0), richText = true}; } } private void OnEnable() { BuildMenu(); m_Elements = serializedObject.FindProperty("m_Bindings"); m_Component = serializedObject.FindProperty("m_VisualEffect"); m_ExecuteInEditor = serializedObject.FindProperty("m_ExecuteInEditor"); m_List = new ReorderableList(serializedObject, m_Elements, false, true, true, true); m_List.drawHeaderCallback = DrawHeader; m_List.drawElementCallback = DrawElement; m_List.onRemoveCallback = RemoveElement; m_List.onAddCallback = AddElement; m_List.onSelectCallback = SelectElement; } private void OnDisable() { } public override void OnInspectorGUI() { EditorGUI.BeginChangeCheck(); EditorGUILayout.Space(); EditorGUILayout.PropertyField(m_ExecuteInEditor); EditorGUILayout.Space(); m_List.DoLayoutList(); EditorGUILayout.Space(); if (EditorGUI.EndChangeCheck()) serializedObject.ApplyModifiedProperties(); if (m_ElementEditor != null) { EditorGUI.BeginChangeCheck(); var fieldAttribute = BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic; var binding = m_ElementEditor.serializedObject.targetObject; var type = binding.GetType(); var fields = type.GetFields(fieldAttribute); foreach (var field in fields) { var property = m_ElementEditor.serializedObject.FindProperty(field.Name); if (property == null) continue; using (new GUILayout.HorizontalScope()) { var attrib = field.GetCustomAttributes(true).OfType<VFXParameterBindingAttribute>().FirstOrDefault<VFXParameterBindingAttribute>(); if (attrib != null) { var parameter = property.FindPropertyRelative("m_Name"); string parm = parameter.stringValue; parm = EditorGUILayout.TextField(ObjectNames.NicifyVariableName(property.name), parm); if (parm != parameter.stringValue) { parameter.stringValue = parm; serializedObject.ApplyModifiedProperties(); } if (GUILayout.Button("v", EditorStyles.toolbarButton, GUILayout.Width(14))) CheckTypeMenu(property, attrib, (m_Component.objectReferenceValue as VisualEffect).visualEffectAsset); } else { EditorGUILayout.PropertyField(property, true); } } } if (EditorGUI.EndChangeCheck()) m_ElementEditor.serializedObject.ApplyModifiedProperties(); var component = (m_Component.objectReferenceValue as VisualEffect); bool valid = (binding as VFXBinderBase).IsValid(component); if (!valid) { EditorGUILayout.HelpBox("This binding is not correctly configured, please ensure Parameter is valid and/or objects are not null", MessageType.Warning); } } } private class MenuPropertySetName { public SerializedProperty property; public string value; } public void CheckTypeMenu(SerializedProperty property, VFXParameterBindingAttribute attribute, VisualEffectAsset asset) { GenericMenu menu = new GenericMenu(); var parameters = (asset.GetResource().graph as UnityEditor.VFX.VFXGraph).children.OfType<UnityEditor.VFX.VFXParameter>(); foreach (var param in parameters) { string typeName = param.type.ToString(); if (attribute.EditorTypes.Contains(typeName)) { MenuPropertySetName set = new MenuPropertySetName { property = property, value = param.exposedName }; menu.AddItem(new GUIContent(param.exposedName), false, SetFieldName, set); } } menu.ShowAsContext(); } public void SetFieldName(object o) { var set = o as MenuPropertySetName; set.property.FindPropertyRelative("m_Name").stringValue = set.value; m_ElementEditor.serializedObject.ApplyModifiedProperties(); } public void BuildMenu() { m_Menu = new GenericMenu(); List<Type> relevantTypes = new List<Type>(); foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { foreach (Type t in assembly.GetTypes()) { if (typeof(VFXBinderBase).IsAssignableFrom(t) && !t.IsAbstract) relevantTypes.Add(t); } } foreach (Type type in relevantTypes) { string name = type.ToString(); var attrib = type.GetCustomAttributes(true).OfType<VFXBinderAttribute>().FirstOrDefault<VFXBinderAttribute>(); if (attrib != null) name = attrib.MenuPath; m_Menu.AddItem(new GUIContent(name), false, AddBinding, type); } } public void AddBinding(object type) { Type t = type as Type; var obj = (serializedObject.targetObject as VFXParameterBinder).gameObject; Undo.AddComponent(obj, t); } public void SelectElement(ReorderableList list) { UpdateSelection(list.index); } public void UpdateSelection(int selected) { if (selected >= 0) { Editor editor = null; CreateCachedEditor(m_Elements.GetArrayElementAtIndex(selected).objectReferenceValue, typeof(VFXBinderEditor), ref editor); m_ElementEditor = editor as VFXBinderEditor; } else m_ElementEditor = null; } public void AddElement(ReorderableList list) { m_Menu.ShowAsContext(); } public void DrawElement(Rect rect, int index, bool isActive, bool isFocused) { var target = m_Elements.GetArrayElementAtIndex(index).objectReferenceValue as VFXBinderBase; Rect iconRect = new Rect(rect.xMin + 4, rect.yMin + 4, 8, 8); if (target != null) { var element = target.ToString(); GUI.Label(rect, new GUIContent(element), Styles.labelStyle); var component = (m_Component.objectReferenceValue as VisualEffect); bool valid = target.IsValid(component); EditorGUI.DrawRect(iconRect, valid ? validColor : invalidColor); } else { EditorGUI.DrawRect(iconRect, errorColor); GUI.Label(rect, "<color=red>(Missing or Null Parameter Binder)</color>", Styles.labelStyle); } } public void RemoveElement(ReorderableList list) { int index = m_List.index; var element = m_Elements.GetArrayElementAtIndex(index).objectReferenceValue; if(element != null) { Undo.DestroyObjectImmediate(element); m_Elements.DeleteArrayElementAtIndex(index); // Delete object reference } else { Undo.RecordObject(serializedObject.targetObject, "Remove null entry"); } m_Elements.DeleteArrayElementAtIndex(index); // Remove list entry UpdateSelection(-1); } public void DrawHeader(Rect rect) { GUI.Label(rect, "Parameter Bindings"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; namespace System.Diagnostics { internal static partial class ProcessManager { /// <summary>Gets the IDs of all processes on the current machine.</summary> public static int[] GetProcessIds() { return EnumerateProcessIds().ToArray(); } /// <summary>Gets process infos for each process on the specified machine.</summary> /// <param name="machineName">The target machine.</param> /// <returns>An array of process infos, one per found process.</returns> public static ProcessInfo[] GetProcessInfos(string machineName) { ThrowIfRemoteMachine(machineName); int[] procIds = GetProcessIds(machineName); // Iterate through all process IDs to load information about each process var reusableReader = new ReusableTextReader(); var processes = new List<ProcessInfo>(procIds.Length); foreach (int pid in procIds) { ProcessInfo pi = CreateProcessInfo(pid, reusableReader); if (pi != null) { processes.Add(pi); } } return processes.ToArray(); } /// <summary>Gets an array of module infos for the specified process.</summary> /// <param name="processId">The ID of the process whose modules should be enumerated.</param> /// <returns>The array of modules.</returns> internal static ProcessModuleCollection GetModules(int processId) { var modules = new ProcessModuleCollection(0); // Process from the parsed maps file each entry representing a module foreach (Interop.procfs.ParsedMapsModule entry in Interop.procfs.ParseMapsModules(processId)) { int sizeOfImage = (int)(entry.AddressRange.Value - entry.AddressRange.Key); // A single module may be split across multiple map entries; consolidate based on // the name and address ranges of sequential entries. if (modules.Count > 0) { ProcessModule module = modules[modules.Count - 1]; if (module.FileName == entry.FileName && ((long)module.BaseAddress + module.ModuleMemorySize == entry.AddressRange.Key)) { // Merge this entry with the previous one module.ModuleMemorySize += sizeOfImage; continue; } } // It's not a continuation of a previous entry but a new one: add it. unsafe { modules.Add(new ProcessModule() { FileName = entry.FileName, ModuleName = Path.GetFileName(entry.FileName), BaseAddress = new IntPtr(unchecked((void*)entry.AddressRange.Key)), ModuleMemorySize = sizeOfImage, EntryPointAddress = IntPtr.Zero // unknown }); } } // Move the main executable module to be the first in the list if it's not already string exePath = Process.GetExePath(processId); for (int i = 0; i < modules.Count; i++) { ProcessModule module = modules[i]; if (module.FileName == exePath) { if (i > 0) { modules.RemoveAt(i); modules.Insert(0, module); } break; } } // Return the set of modules found return modules; } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary> /// Creates a ProcessInfo from the specified process ID. /// </summary> internal static ProcessInfo CreateProcessInfo(int pid, ReusableTextReader reusableReader = null) { reusableReader ??= new ReusableTextReader(); if (Interop.procfs.TryReadStatFile(pid, out Interop.procfs.ParsedStat stat, reusableReader)) { Interop.procfs.TryReadStatusFile(pid, out Interop.procfs.ParsedStatus status, reusableReader); return CreateProcessInfo(ref stat, ref status, reusableReader); } return null; } /// <summary> /// Creates a ProcessInfo from the data parsed from a /proc/pid/stat file and the associated tasks directory. /// </summary> internal static ProcessInfo CreateProcessInfo(ref Interop.procfs.ParsedStat procFsStat, ref Interop.procfs.ParsedStatus procFsStatus, ReusableTextReader reusableReader, string processName = null) { int pid = procFsStat.pid; var pi = new ProcessInfo() { ProcessId = pid, ProcessName = processName ?? Process.GetUntruncatedProcessName(ref procFsStat) ?? string.Empty, BasePriority = (int)procFsStat.nice, SessionId = procFsStat.session, PoolPagedBytes = (long)procFsStatus.VmSwap, VirtualBytes = (long)procFsStatus.VmSize, VirtualBytesPeak = (long)procFsStatus.VmPeak, WorkingSetPeak = (long)procFsStatus.VmHWM, WorkingSet = (long)procFsStatus.VmRSS, PageFileBytes = (long)procFsStatus.VmSwap, PrivateBytes = (long)procFsStatus.VmData, // We don't currently fill in the other values. // A few of these could probably be filled in from getrusage, // but only for the current process or its children, not for // arbitrary other processes. }; // Then read through /proc/pid/task/ to find each thread in the process... string tasksDir = Interop.procfs.GetTaskDirectoryPathForProcess(pid); try { foreach (string taskDir in Directory.EnumerateDirectories(tasksDir)) { // ...and read its associated /proc/pid/task/tid/stat file to create a ThreadInfo string dirName = Path.GetFileName(taskDir); int tid; Interop.procfs.ParsedStat stat; if (int.TryParse(dirName, NumberStyles.Integer, CultureInfo.InvariantCulture, out tid) && Interop.procfs.TryReadStatFile(pid, tid, out stat, reusableReader)) { unsafe { pi._threadInfoList.Add(new ThreadInfo() { _processId = pid, _threadId = (ulong)tid, _basePriority = pi.BasePriority, _currentPriority = (int)stat.nice, _startAddress = IntPtr.Zero, _threadState = ProcFsStateToThreadState(stat.state), _threadWaitReason = ThreadWaitReason.Unknown }); } } } } catch (IOException) { // Between the time that we get an ID and the time that we try to read the associated // directories and files in procfs, the process could be gone. } // Finally return what we've built up return pi; } // ---------------------------------- // ---- Unix PAL layer ends here ---- // ---------------------------------- /// <summary>Enumerates the IDs of all processes on the current machine.</summary> internal static IEnumerable<int> EnumerateProcessIds() { // Parse /proc for any directory that's named with a number. Each such // directory represents a process. foreach (string procDir in Directory.EnumerateDirectories(Interop.procfs.RootPath)) { string dirName = Path.GetFileName(procDir); int pid; if (int.TryParse(dirName, NumberStyles.Integer, CultureInfo.InvariantCulture, out pid)) { Debug.Assert(pid >= 0); yield return pid; } } } /// <summary>Gets a ThreadState to represent the value returned from the status field of /proc/pid/stat.</summary> /// <param name="c">The status field value.</param> /// <returns></returns> private static ThreadState ProcFsStateToThreadState(char c) { // Information on these in fs/proc/array.c // `man proc` does not document them all switch (c) { case 'R': // Running return ThreadState.Running; case 'D': // Waiting on disk case 'P': // Parked case 'S': // Sleeping in a wait case 't': // Tracing/debugging case 'T': // Stopped on a signal return ThreadState.Wait; case 'x': // dead case 'X': // Dead case 'Z': // Zombie return ThreadState.Terminated; case 'W': // Paging or waking case 'K': // Wakekill return ThreadState.Transition; case 'I': // Idle return ThreadState.Ready; default: Debug.Fail($"Unexpected status character: {c}"); return ThreadState.Unknown; } } } }
using System; using QuoteMyGoods.Models; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; namespace QuoteMyGoods.Migrations { [DbContext(typeof(QMGContext))] [Migration("20160314100611_addPricing")] partial class addPricing { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "7.0.0-rc1-16348") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasAnnotation("Relational:Name", "RoleNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasAnnotation("Relational:TableName", "AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasAnnotation("Relational:TableName", "AspNetUserRoles"); }); modelBuilder.Entity("QuoteMyGoods.Models.Product", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Category"); b.Property<string>("Description"); b.Property<string>("ImgUrl"); b.Property<string>("Name"); b.Property<decimal>("Price"); b.HasKey("Id"); }); modelBuilder.Entity("QuoteMyGoods.Models.QMGUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasAnnotation("Relational:Name", "EmailIndex"); b.HasIndex("NormalizedUserName") .HasAnnotation("Relational:Name", "UserNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.HasOne("QuoteMyGoods.Models.QMGUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.HasOne("QuoteMyGoods.Models.QMGUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); b.HasOne("QuoteMyGoods.Models.QMGUser") .WithMany() .HasForeignKey("UserId"); }); } } }
#region License // // Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com> // // 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.SqlClient; using System.Linq; using FluentMigrator.Runner.Announcers; using FluentMigrator.Runner.Generators.Postgres; using FluentMigrator.Runner.Processors; using FluentMigrator.Runner.Processors.MySql; using FluentMigrator.Runner.Processors.Postgres; using FluentMigrator.Runner.Processors.SQLite; using FluentMigrator.Runner.Processors.SqlServer; using MySql.Data.MySqlClient; using Npgsql; using FluentMigrator.Runner.Generators.SQLite; using FluentMigrator.Runner.Generators.SqlServer; using FluentMigrator.Runner.Generators.MySql; using FirebirdSql.Data.FirebirdClient; using FluentMigrator.Runner.Processors.Firebird; using FluentMigrator.Runner.Generators.Firebird; namespace FluentMigrator.Tests.Integration { public class IntegrationTestBase { public void ExecuteWithSupportedProcessors(Action<IMigrationProcessor> test) { ExecuteWithSupportedProcessors(test, true); } public void ExecuteWithSupportedProcessors(Action<IMigrationProcessor> test, Boolean tryRollback) { ExecuteWithSupportedProcessors(test, tryRollback, new Type[] { }); } public void ExecuteWithSupportedProcessors(Action<IMigrationProcessor> test, Boolean tryRollback, params Type[] exceptProcessors) { if (exceptProcessors.Count(t => typeof(SqlServerProcessor).IsAssignableFrom(t)) == 0) { ExecuteWithSqlServer2005(test, tryRollback); ExecuteWithSqlServer2008(test, tryRollback); ExecuteWithSqlServer2012(test, tryRollback); ExecuteWithSqlServer2014(test, tryRollback); } if (exceptProcessors.Count(t => typeof(SqliteProcessor).IsAssignableFrom(t)) == 0) ExecuteWithSqlite(test, IntegrationTestOptions.SqlLite); if (exceptProcessors.Count(t => typeof(MySqlProcessor).IsAssignableFrom(t)) == 0) ExecuteWithMySql(test, IntegrationTestOptions.MySql); if (exceptProcessors.Count(t => typeof(PostgresProcessor).IsAssignableFrom(t)) == 0) ExecuteWithPostgres(test, IntegrationTestOptions.Postgres, tryRollback); if (exceptProcessors.Count(t => typeof(FirebirdProcessor).IsAssignableFrom(t)) == 0) ExecuteWithFirebird(test, IntegrationTestOptions.Firebird); } protected static void ExecuteWithSqlServer2014(Action<IMigrationProcessor> test, bool tryRollback) { var serverOptions = IntegrationTestOptions.SqlServer2014; if (!serverOptions.IsEnabled) return; var announcer = new TextWriterAnnouncer(System.Console.Out); announcer.Heading("Testing Migration against MS SQL Server 2014"); var generator = new SqlServer2014Generator(); ExecuteWithSqlServer(serverOptions, announcer, generator, test, tryRollback); } protected static void ExecuteWithSqlServer2012(Action<IMigrationProcessor> test, bool tryRollback) { var serverOptions = IntegrationTestOptions.SqlServer2012; if (!serverOptions.IsEnabled) return; var announcer = new TextWriterAnnouncer(System.Console.Out); announcer.Heading("Testing Migration against MS SQL Server 2012"); var generator = new SqlServer2012Generator(); ExecuteWithSqlServer(serverOptions, announcer, generator, test, tryRollback); } protected static void ExecuteWithSqlServer2008(Action<IMigrationProcessor> test, bool tryRollback) { var serverOptions = IntegrationTestOptions.SqlServer2008; if (!serverOptions.IsEnabled) return; var announcer = new TextWriterAnnouncer(System.Console.Out); announcer.Heading("Testing Migration against MS SQL Server 2008"); var generator = new SqlServer2008Generator(); ExecuteWithSqlServer(serverOptions, announcer, generator, test, tryRollback); } protected static void ExecuteWithSqlServer2005(Action<IMigrationProcessor> test, bool tryRollback) { var serverOptions = IntegrationTestOptions.SqlServer2005; if (!serverOptions.IsEnabled) return; var announcer = new TextWriterAnnouncer(System.Console.Out); announcer.Heading("Testing Migration against MS SQL Server 2005"); var generator = new SqlServer2005Generator(); ExecuteWithSqlServer(serverOptions, announcer, generator, test, tryRollback); } private static void ExecuteWithSqlServer(IntegrationTestOptions.DatabaseServerOptions serverOptions, TextWriterAnnouncer announcer, SqlServer2005Generator generator, Action<IMigrationProcessor> test, bool tryRollback) { using (var connection = new SqlConnection(serverOptions.ConnectionString)) { var processor = new SqlServerProcessor(connection, generator, announcer, new ProcessorOptions(), new SqlServerDbFactory()); test(processor); if (tryRollback && !processor.WasCommitted) { processor.RollbackTransaction(); } } } protected static void ExecuteWithSqlite(Action<IMigrationProcessor> test, IntegrationTestOptions.DatabaseServerOptions serverOptions) { if (!serverOptions.IsEnabled) return; var announcer = new TextWriterAnnouncer(System.Console.Out); announcer.Heading("Testing Migration against SQLite"); var factory = new SqliteDbFactory(); using (var connection = factory.CreateConnection(serverOptions.ConnectionString)) { var processor = new SqliteProcessor(connection, new SqliteGenerator(), announcer, new ProcessorOptions(), factory); test(processor); } } protected static void ExecuteWithPostgres(Action<IMigrationProcessor> test, IntegrationTestOptions.DatabaseServerOptions serverOptions, Boolean tryRollback) { if (!serverOptions.IsEnabled) return; var announcer = new TextWriterAnnouncer(System.Console.Out); announcer.Heading("Testing Migration against Postgres"); using (var connection = new NpgsqlConnection(serverOptions.ConnectionString)) { var processor = new PostgresProcessor(connection, new PostgresGenerator(), new TextWriterAnnouncer(System.Console.Out), new ProcessorOptions(), new PostgresDbFactory()); test(processor); if (!processor.WasCommitted) { processor.RollbackTransaction(); } } } protected static void ExecuteWithMySql(Action<IMigrationProcessor> test, IntegrationTestOptions.DatabaseServerOptions serverOptions) { if (!serverOptions.IsEnabled) return; var announcer = new TextWriterAnnouncer(System.Console.Out); announcer.Heading("Testing Migration against MySQL Server"); using (var connection = new MySqlConnection(serverOptions.ConnectionString)) { var processor = new MySqlProcessor(connection, new MySqlGenerator(), announcer, new ProcessorOptions(), new MySqlDbFactory()); test(processor); } } protected static void ExecuteWithFirebird(Action<IMigrationProcessor> test, IntegrationTestOptions.DatabaseServerOptions serverOptions) { if (!serverOptions.IsEnabled) return; var announcer = new TextWriterAnnouncer(System.Console.Out); announcer.ShowSql = true; announcer.Heading("Testing Migration against Firebird Server"); if (!System.IO.File.Exists("fbtest.fdb")) { FbConnection.CreateDatabase(serverOptions.ConnectionString); } using (var connection = new FbConnection(serverOptions.ConnectionString)) { var options = FirebirdOptions.AutoCommitBehaviour(); var processor = new FirebirdProcessor(connection, new FirebirdGenerator(options), announcer, new ProcessorOptions(), new FirebirdDbFactory(), options); try { test(processor); } catch (Exception) { if (!processor.WasCommitted) processor.RollbackTransaction(); throw; } connection.Close(); } } } }
/* * Copyright (c) 2007-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.Drawing; using System.Windows.Forms; using OpenMetaverse.Imaging; using OpenMetaverse.Assets; namespace OpenMetaverse.GUI { /// <summary> /// PictureBox GUI component for displaying a client's mini-map /// </summary> public class MiniMap : PictureBox { private static Brush BG_COLOR = Brushes.Navy; private UUID _MapImageID; private GridClient _Client; private Image _MapLayer; //warning CS0414: The private field `OpenMetaverse.GUI.MiniMap._MousePosition' is assigned but its value is never used //private Point _MousePosition; ToolTip _ToolTip; /// <summary> /// Gets or sets the GridClient associated with this control /// </summary> public GridClient Client { get { return _Client; } set { if (value != null) InitializeClient(value); } } /// <summary> /// PictureBox control for an unspecified client's mini-map /// </summary> public MiniMap() { this.BorderStyle = BorderStyle.FixedSingle; this.SizeMode = PictureBoxSizeMode.Zoom; } /// <summary> /// PictureBox control for the specified client's mini-map /// </summary> public MiniMap(GridClient client) : this () { InitializeClient(client); _ToolTip = new ToolTip(); _ToolTip.Active = true; _ToolTip.AutomaticDelay = 1; this.MouseHover += new System.EventHandler(MiniMap_MouseHover); this.MouseMove += new MouseEventHandler(MiniMap_MouseMove); } /// <summary>Sets the map layer to the specified bitmap image</summary> /// <param name="mapImage"></param> public void SetMapLayer(Bitmap mapImage) { if (this.InvokeRequired) this.BeginInvoke((MethodInvoker)delegate { SetMapLayer(mapImage); }); else { if (mapImage == null) { Bitmap bmp = new Bitmap(256, 256); Graphics g = Graphics.FromImage(bmp); g.Clear(this.BackColor); g.FillRectangle(BG_COLOR, 0f, 0f, 256f, 256f); g.DrawImage(bmp, 0, 0); _MapLayer = bmp; } else _MapLayer = mapImage; } } private void InitializeClient(GridClient client) { _Client = client; _Client.Grid.CoarseLocationUpdate += Grid_CoarseLocationUpdate; _Client.Network.SimChanged += Network_OnCurrentSimChanged; } void Grid_CoarseLocationUpdate(object sender, CoarseLocationUpdateEventArgs e) { UpdateMiniMap(e.Simulator); } private void UpdateMiniMap(Simulator sim) { if (!this.IsHandleCreated) return; if (this.InvokeRequired) this.BeginInvoke((MethodInvoker)delegate { UpdateMiniMap(sim); }); else { if (_MapLayer == null) SetMapLayer(null); Bitmap bmp = (Bitmap)_MapLayer.Clone(); Graphics g = Graphics.FromImage(bmp); Vector3 myCoarsePos; if (!sim.AvatarPositions.TryGetValue(Client.Self.AgentID, out myCoarsePos)) return; int i = 0; _Client.Network.CurrentSim.AvatarPositions.ForEach( delegate(KeyValuePair<UUID, Vector3> coarse) { int x = (int)coarse.Value.X; int y = 255 - (int)coarse.Value.Y; if (coarse.Key == Client.Self.AgentID) { g.FillEllipse(Brushes.Yellow, x - 5, y - 5, 10, 10); g.DrawEllipse(Pens.Khaki, x - 5, y - 5, 10, 10); } else { Pen penColor; Brush brushColor; if (Client.Network.CurrentSim.ObjectsAvatars.Find(delegate(Avatar av) { return av.ID == coarse.Key; }) != null) { brushColor = Brushes.PaleGreen; penColor = Pens.Green; } else { brushColor = Brushes.LightGray; penColor = Pens.Gray; } if (myCoarsePos.Z - coarse.Value.Z > 1) { Point[] points = new Point[3] { new Point(x - 6, y - 6), new Point(x + 6, y - 6), new Point(x, y + 6) }; g.FillPolygon(brushColor, points); g.DrawPolygon(penColor, points); } else if (myCoarsePos.Z - coarse.Value.Z < -1) { Point[] points = new Point[3] { new Point(x - 6, y + 6), new Point(x + 6, y + 6), new Point(x, y - 6) }; g.FillPolygon(brushColor, points); g.DrawPolygon(penColor, points); } else { g.FillEllipse(brushColor, x - 5, y - 5, 10, 10); g.DrawEllipse(penColor, x - 5, y - 5, 10, 10); } } i++; } ); g.DrawImage(bmp, 0, 0); this.Image = bmp; } } void MiniMap_MouseHover(object sender, System.EventArgs e) { _ToolTip.SetToolTip(this, "test"); _ToolTip.Show("test", this); //TODO: tooltip popup with closest avatar's name, if within range } void MiniMap_MouseMove(object sender, MouseEventArgs e) { _ToolTip.Hide(this); //warning CS0414: The private field `OpenMetaverse.GUI.MiniMap._MousePosition' is assigned but its value is never used //_MousePosition = e.Location; } void Network_OnCurrentSimChanged(object sender, SimChangedEventArgs e) { if (_Client.Network.Connected) return; GridRegion region; if (Client.Grid.GetGridRegion(Client.Network.CurrentSim.Name, GridLayerType.Objects, out region)) { SetMapLayer(null); _MapImageID = region.MapImageID; ManagedImage nullImage; Client.Assets.RequestImage(_MapImageID, ImageType.Baked, delegate(TextureRequestState state, AssetTexture asset) { if(state == TextureRequestState.Finished) OpenJPEG.DecodeToImage(asset.AssetData, out nullImage, out _MapLayer); }); } } } }
// ----- // Copyright 2010 Deyan Timnev // This file is part of the Matrix Platform (www.matrixplatform.com). // The Matrix Platform is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. The Matrix Platform is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public License along with the Matrix Platform. If not, see http://www.gnu.org/licenses/lgpl.html // ----- using System; using System.Collections.Generic; using System.Text; using System.Threading; using Matrix.Common.Core.Serialization; using NUnit.Framework; namespace Matrix.Framework.SuperPool.UnitTest { /// <summary> /// Test fixture class, tests various types of super pool calls. /// Tests are conducted with 2 local clients on a super pool. /// </summary> [TestFixture] public class CallTest { /// <summary> /// The tests are executed on a bunch of implementors, configured /// differently to make sure all tests run on various configurations. /// </summary> List<CallTestImplementor> _implementors = new List<CallTestImplementor>(); CallTestImplementor _referenceImplementor; CallTestImplementor _binaryImplementor; /// <summary> /// Constructor. /// </summary> public CallTest() { // Load the implementors. _referenceImplementor = CreateDefaultImplementor(); _implementors.Add(_referenceImplementor); _binaryImplementor = CreateBinaryLocalImplementor(); _implementors.Add(_binaryImplementor); //_implementors.Add(CreateJSonLocalImplementor()); } /// <summary> /// Implementor works on local referencing model. /// </summary> CallTestImplementor CreateDefaultImplementor() { Matrix.Framework.SuperPool.Core.SuperPool pool = new Matrix.Framework.SuperPool.Core.SuperPool("DefaultImplementor.Pool"); CallTestImplementor implementor = new CallTestImplementor(); pool.AddClient(implementor.Client1); pool.AddClient(implementor.Client2); implementor.Disposables.Add(pool); return implementor; } /// <summary> /// Implementor works on local referencing model. /// </summary> CallTestImplementor CreateBinaryLocalImplementor() { Matrix.Framework.MessageBus.Core.MessageBus bus = new Matrix.Framework.MessageBus.Core.MessageBus("BinaryLocalImplementor.Pool", new BinarySerializer()); Matrix.Framework.SuperPool.Core.SuperPool pool = new Matrix.Framework.SuperPool.Core.SuperPool(bus); CallTestImplementor implementor = new CallTestImplementor(); pool.AddClient(implementor.Client1); pool.AddClient(implementor.Client2); implementor.Disposables.Add(pool); implementor.Client1.EnvelopeDuplicationMode = Matrix.Framework.MessageBus.Core.Envelope.DuplicationModeEnum.DuplicateBoth; implementor.Client1.EnvelopeMultiReceiverDuplicationMode = Matrix.Framework.MessageBus.Core.Envelope.DuplicationModeEnum.DuplicateBoth; implementor.Client2.EnvelopeDuplicationMode = Matrix.Framework.MessageBus.Core.Envelope.DuplicationModeEnum.DuplicateBoth; implementor.Client2.EnvelopeMultiReceiverDuplicationMode = Matrix.Framework.MessageBus.Core.Envelope.DuplicationModeEnum.DuplicateBoth; return implementor; } ///// <summary> ///// Implementor works on local referencing model. ///// </summary> //CallTestImplementor CreateJSonLocalImplementor() //{ // MessageBus.MessageBus bus = new MessageBus.MessageBus("JSonLocalImplementor.Pool", new JSonSerializer()); // MessageSuperPool pool = new MessageSuperPool(bus); // CallTestImplementor implementor = new CallTestImplementor(); // pool.AddClient(implementor.Client1); // pool.AddClient(implementor.Client2); // implementor.Disposables.Add(pool); // implementor.Client1.DefaultEnvelopeDuplicationMode = MessageBus.Envelope.DuplicationModeEnum.DuplicateBoth; // implementor.Client2.DefaultEnvelopeDuplicationMode = MessageBus.Envelope.DuplicationModeEnum.DuplicateBoth; // return implementor; //} [TestFixtureSetUp] public void Init() { foreach (CallTestImplementor implementor in _implementors) { implementor.Initialize(); } } [TestFixtureTearDown] public void UnInit() { foreach (CallTestImplementor implementor in _implementors) { implementor.Uninit(); } } [Test] public void SimpleCallTestReference([Values(10000, 100000)] int length) { _referenceImplementor.SimpleCallTest(length); } [Test] public void SimpleCallTestBinarySerialization([Values(10000, 100000)] int length) { _binaryImplementor.SimpleCallTest(length); } [Test] public void VariableCallTest([Values(100)] int length) { foreach (CallTestImplementor implementor in _implementors) { implementor.VariableCallTest(length); } } [Test] public void RefCallTest() { foreach (CallTestImplementor implementor in _implementors) { implementor.RefCallTest(); } } [Test] public void OutCallTest() { foreach (CallTestImplementor implementor in _implementors) { implementor.OutCallTest(); } } [Test] public void AsyncResultCallTest() { foreach (CallTestImplementor implementor in _implementors) { implementor.AsyncResultCallTest(); } } //[Test] //public void LongTest_AsyncTimeoutResultCallTest() //{ // foreach (CallTestImplementor implementor in _implementors) // { // implementor.AsyncTimeoutResultCallTest(); // } //} [Test] public void AsyncTimeoutResultCallTestException() { foreach (CallTestImplementor implementor in _implementors) { implementor.AsyncTimeoutResultCallTestException(); } } [Test] public void CallConfirmedTest() { foreach (CallTestImplementor implementor in _implementors) { implementor.ConfirmedCallTest(); } } /// <summary> /// This test is only runed on default implementor. /// </summary> [Test] public void DirectCall([Values(10000, 100000, 1000000)] int length) { _referenceImplementor.DirectCallTest(length); } [Test] public void CallFirst() { foreach (CallTestImplementor implementor in _implementors) { implementor.CallFirst(); } } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // 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.Collections.Generic; using System.Threading.Tasks; using NUnit.Framework; using Sensus.Shared.Concurrent; namespace Sensus.Shared.Tests.Concurrent { public abstract class IConcurrentTests { #region Fields private const int DelayTime = 100; private readonly IConcurrent _concurrent; #endregion #region Constructors protected IConcurrentTests(IConcurrent concurrent) { _concurrent = concurrent; } #endregion [Test] public void ActionIsThreadSafe() { var test = new List<int> { 1, 2, 3 }; var task1 = Task.Run(() => { _concurrent.ExecuteThreadSafe(() => { foreach (var i in test) { Task.Delay(DelayTime).Wait(); } }); }); var task2 = Task.Run(() => { _concurrent.ExecuteThreadSafe(() => { test.Add(4); Task.Delay(DelayTime).Wait(); test.Add(5); }); }); Task.WaitAll(task1, task2); } [Test] public void FuncIsThreadSafe() { var test = new List<int> { 1, 2, 3 }; var task1 = Task.Run(() => { var output = _concurrent.ExecuteThreadSafe(() => { foreach (var i in test) { Task.Delay(DelayTime).Wait(); } return test; }); Assert.AreSame(output, test); }); var task2 = Task.Run(() => { var output = _concurrent.ExecuteThreadSafe(() => { test.Add(4); Task.Delay(DelayTime).Wait(); test.Add(5); return test; }); Assert.AreSame(output, test); }); Task.WaitAll(task1, task2); } [Test] public void BasicActionIsThreadSafe() { var test = new List<int> { 1, 2, 3 }; _concurrent.ExecuteThreadSafe(() => { test.Add(4); foreach (var i in test) { Task.Delay(DelayTime).Wait(); } test.Add(5); }); Assert.Contains(4, test); Assert.Contains(5, test); } [Test] public void BasicFuncIsThreadSafe() { var test = new List<int> { 1, 2, 3 }; var output = _concurrent.ExecuteThreadSafe(() => { test.Add(4); foreach (var i in test) { Task.Delay(DelayTime).Wait(); } test.Add(5); return test; }); Assert.Contains(4, output); Assert.Contains(5, output); Assert.AreSame(test, output); } [Test] public void InnerActionIsThreadSafe() { var test = new List<int> { 1, 2, 3 }; var cancel = new System.Threading.CancellationTokenSource(); var task = Task.Run(() => { _concurrent.ExecuteThreadSafe(() => { _concurrent.ExecuteThreadSafe(() => { test.Add(4); foreach (var i in test) { Task.Delay(DelayTime).Wait(); } test.Add(5); }); }); }, cancel.Token); task.Wait(1000); if (!task.IsCompleted) { cancel.Cancel(); throw new System.Exception("It appears that we deadlocked"); } Assert.IsTrue(task.IsCompleted); Assert.Contains(4, test); Assert.Contains(5, test); } [Test] public void InnerFuncIsThreadSafe() { var test = new List<int> { 1, 2, 3 }; var output = default(List<int>); var cancel = new System.Threading.CancellationTokenSource(); var task = Task.Run(() => { output = _concurrent.ExecuteThreadSafe(() => { return _concurrent.ExecuteThreadSafe(() => { test.Add(4); foreach (var i in test) { Task.Delay(DelayTime).Wait(); } test.Add(5); return test; }); }); }, cancel.Token); task.Wait(1000); if (!task.IsCompleted) { cancel.Cancel(); throw new System.Exception("It appears that we deadlocked"); } Assert.Contains(4, output); Assert.Contains(5, output); Assert.AreSame(test, output); } } }
//------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using CoreFoundation; using Foundation; using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows; using UIKit; using Microsoft.Identity.Core; using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Helpers; using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.OAuth2; using Microsoft.Identity.Core.Cache; using Microsoft.Identity.Core.Helpers; using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Broker; using System.Globalization; using Security; namespace Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Platform { internal class iOSBroker : IBroker { private static SemaphoreSlim brokerResponseReady = null; private static NSUrl brokerResponse = null; private readonly ICoreLogger _logger; private string _brokerRequestNonce; private bool _brokerV3Installed = false; public iOSBroker(ICoreLogger logger) { _logger = logger; } public IPlatformParameters PlatformParameters { get; set; } public bool CanInvokeBroker { get { PlatformParameters pp = PlatformParameters as PlatformParameters; if (pp == null) { return false; } bool canStartBroker = false; if (pp.UseBroker) { pp.CallerViewController.InvokeOnMainThread(() => { if (IsBrokerInstalled("msauthv3://")) { _logger.Info("iOS Broker (msauthv3://) can be invoked. "); _brokerV3Installed = true; canStartBroker = true; } }); if (!canStartBroker) { pp.CallerViewController.InvokeOnMainThread(() => { if (IsBrokerInstalled("msauth://")) { _logger.Info("iOS Broker (msauth://) can be invoked. "); canStartBroker = true; } }); } } return canStartBroker; } } private bool IsBrokerInstalled(string brokerUriScheme) { return UIApplication.SharedApplication.CanOpenUrl(new NSUrl(brokerUriScheme)); } public async Task<AdalResultWrapper> AcquireTokenUsingBrokerAsync(IDictionary<string, string> brokerPayload) { if (brokerPayload.ContainsKey(BrokerParameter.SilentBrokerFlow)) { _logger.Info("iOS Broker payload contains silent flow key in payload. " + "Throwing AdalSilentTokenAcquisitionException() "); throw new AdalSilentTokenAcquisitionException(); } brokerResponse = null; brokerResponseReady = new SemaphoreSlim(0); //call broker string base64EncodedString = Base64UrlHelpers.Encode(BrokerKeyHelper.GetOrCreateBrokerKey(_logger)); brokerPayload["broker_key"] = base64EncodedString; brokerPayload["max_protocol_ver"] = "2"; if (brokerPayload.TryGetValue("claims", out string claims) && !string.IsNullOrEmpty(claims)) { brokerPayload.Add("skip_cache", "YES"); string encodedClaims = EncodingHelper.UrlEncode(claims); brokerPayload[BrokerParameter.Claims] = encodedClaims; } if (_brokerV3Installed) { _brokerRequestNonce = Guid.NewGuid().ToString(); brokerPayload[BrokerParameter.BrokerNonce] = _brokerRequestNonce; string applicationToken = TryReadBrokerApplicationTokenFromKeychain(brokerPayload); if (!string.IsNullOrEmpty(applicationToken)) { brokerPayload.Add(BrokerConstants.ApplicationToken, applicationToken); } } if (brokerPayload.ContainsKey(BrokerParameter.BrokerInstallUrl)) { HandleInstallUrl(brokerPayload); } else { string queryParams = brokerPayload.ToQueryParameter(); _logger.InfoPii("Invoking the iOS broker " + queryParams, "Invoking the iOS broker. "); NSUrl url = new NSUrl("msauth://broker?" + queryParams); DispatchQueue.MainQueue.DispatchAsync(() => UIApplication.SharedApplication.OpenUrl(url)); } await brokerResponseReady.WaitAsync().ConfigureAwait(false); PlatformParameters = null; return ProcessBrokerResponse(); } private void HandleInstallUrl(IDictionary<string, string> brokerPayload) { string url = brokerPayload[BrokerParameter.BrokerInstallUrl]; Uri uri = new Uri(url); string query = uri.Query; if (query.StartsWith("?", StringComparison.OrdinalIgnoreCase)) { query = query.Substring(1); } _logger.Info("Invoking the iOS broker app link"); Dictionary<string, string> keyPair = EncodingHelper.ParseKeyValueList(query, '&', true, false, null); DispatchQueue.MainQueue.DispatchAsync(() => UIApplication.SharedApplication.OpenUrl(new NSUrl(keyPair["app_link"]))); throw new AdalException(AdalErrorIOSEx.BrokerApplicationRequired, AdalErrorMessageIOSEx.BrokerApplicationRequired); } private AdalResultWrapper ProcessBrokerResponse() { _logger.InfoPii( "Processing reponse from iOS broker " + brokerResponse.Query, "Processing response from iOS Broker. "); string[] keyValuePairs = brokerResponse.Query.Split('&'); IDictionary<string, string> responseDictionary = new Dictionary<string, string>(); foreach (string pair in keyValuePairs) { string[] keyValue = pair.Split('='); responseDictionary[keyValue[0]] = EncodingHelper.UrlDecode(keyValue[1]); if (responseDictionary[keyValue[0]].Equals("(null)", StringComparison.OrdinalIgnoreCase) && keyValue[0].Equals("code", StringComparison.OrdinalIgnoreCase)) { responseDictionary["error"] = "broker_error"; } } return ResultFromBrokerResponse(responseDictionary); } private AdalResultWrapper ResultFromBrokerResponse(IDictionary<string, string> responseDictionary) { TokenResponse response; if (responseDictionary.ContainsKey("error") || responseDictionary.ContainsKey("error_description")) { _logger.Info("Broker response returned an error. "); response = TokenResponse.CreateFromBrokerResponse(responseDictionary); } else { string expectedHash = responseDictionary["hash"]; string encryptedResponse = responseDictionary["response"]; string decryptedResponse = BrokerKeyHelper.DecryptBrokerResponse(encryptedResponse); string responseActualHash = PlatformProxyFactory.GetPlatformProxy().CryptographyManager.CreateSha256Hash(decryptedResponse); byte[] rawHash = Convert.FromBase64String(responseActualHash); string hash = BitConverter.ToString(rawHash); if (expectedHash.Equals(hash.Replace("-", ""), StringComparison.OrdinalIgnoreCase)) { responseDictionary = EncodingHelper.ParseKeyValueList(decryptedResponse, '&', false, null); response = TokenResponse.CreateFromBrokerResponse(responseDictionary); _logger.Info("Broker response successful. "); } else { response = new TokenResponse { Error = AdalError.BrokerReponseHashMismatch, ErrorDescription = AdalErrorMessage.BrokerReponseHashMismatch }; _logger.InfoPii("Broker response hash mismatch: " + response.Error, "Broker response hash mismatch. "); } if (!ValidateBrokerResponseNonceWithRequestNonce(responseDictionary)) { response = new TokenResponse { Error = AdalError.BrokerNonceMismatch, ErrorDescription = AdalErrorMessage.BrokerNonceMismatch }; } if (responseDictionary.ContainsKey(BrokerConstants.ApplicationToken)) { TryWriteBrokerApplicationTokenToKeychain( responseDictionary[BrokerParameter.ClientId], responseDictionary[BrokerConstants.ApplicationToken]); } } var dateTimeOffset = new DateTimeOffset(new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)); dateTimeOffset = dateTimeOffset.AddSeconds(response.ExpiresOn); return response.GetResult(dateTimeOffset, dateTimeOffset); } private bool ValidateBrokerResponseNonceWithRequestNonce(IDictionary<string, string> brokerResponseDictionary) { if (_brokerV3Installed) { string brokerResponseNonce = brokerResponseDictionary[BrokerParameter.BrokerNonce]; bool ok = string.Equals(brokerResponseNonce, _brokerRequestNonce, StringComparison.InvariantCultureIgnoreCase); if (!ok) { _logger.Error( string.Format( CultureInfo.CurrentCulture, "Nonce check failed! Broker response nonce is: {0}, \nBroker request nonce is: {1}", brokerResponseNonce, _brokerRequestNonce)); } return ok; } return true; } private void TryWriteBrokerApplicationTokenToKeychain(string clientId, string applicationToken) { iOSTokenCacheAccessor iOSTokenCacheAccessor = new iOSTokenCacheAccessor(); try { SecStatusCode secStatusCode = iOSTokenCacheAccessor.SaveBrokerApplicationToken(clientId, applicationToken); _logger.Info(string.Format( CultureInfo.CurrentCulture, BrokerConstants.AttemptToSaveBrokerApplicationToken + "SecStatusCode: {0}", secStatusCode)); } catch(Exception ex) { throw new AdalException( AdalErrorIOSEx.WritingApplicationTokenToKeychainFailed, AdalErrorMessageIOSEx.WritingApplicationTokenToKeychainFailed + ex.Message); } } private string TryReadBrokerApplicationTokenFromKeychain(IDictionary<string, string> brokerPaylaod) { iOSTokenCacheAccessor iOSTokenCacheAccessor = new iOSTokenCacheAccessor(); try { SecStatusCode secStatusCode = iOSTokenCacheAccessor.TryGetBrokerApplicationToken(brokerPaylaod[BrokerParameter.ClientId], out string appToken); _logger.Info(string.Format( CultureInfo.CurrentCulture, BrokerConstants.SecStatusCodeFromTryGetBrokerApplicationToken + "SecStatusCode: {0}", secStatusCode)); return appToken; } catch(Exception ex) { throw new AdalException( AdalErrorIOSEx.ReadingApplicationTokenFromKeychainFailed, AdalErrorMessageIOSEx.ReadingApplicationTokenFromKeychainFailed + ex.Message); } } public static void SetBrokerResponse(NSUrl responseUrl) { brokerResponse = responseUrl; brokerResponseReady?.Release(); } } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\LocalPlayer.h:163 namespace UnrealEngine { public partial class ULocalPlayer : UPlayer { public ULocalPlayer(IntPtr adress) : base(adress) { } public ULocalPlayer(UObject Parent = null, string Name = "LocalPlayer") : base(IntPtr.Zero) { NativePointer = E_NewObject_ULocalPlayer(Parent, Name); NativeManager.AddNativeWrapper(NativePointer, this); } [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_PROP_ULocalPlayer_LastViewLocation_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_ULocalPlayer_LastViewLocation_SET(IntPtr Ptr, IntPtr Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_PROP_ULocalPlayer_Origin_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_ULocalPlayer_Origin_SET(IntPtr Ptr, IntPtr Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_PROP_ULocalPlayer_Size_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_ULocalPlayer_Size_SET(IntPtr Ptr, IntPtr Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern ObjectPointerDescription E_PROP_ULocalPlayer_ViewportClient_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_ULocalPlayer_ViewportClient_SET(IntPtr Ptr, IntPtr Value); #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_NewObject_ULocalPlayer(IntPtr Parent, string Name); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_ULocalPlayer_GetControllerId(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern StringWrapper E_ULocalPlayer_GetGameLoginOptions(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern StringWrapper E_ULocalPlayer_GetNickname(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_ULocalPlayer_GetPixelBoundingBox(IntPtr self, IntPtr actorBox, IntPtr outLowerLeft, IntPtr outUpperRight, IntPtr optionalAllotedSize); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_ULocalPlayer_GetPixelPoint(IntPtr self, IntPtr inPoint, IntPtr outPoint, IntPtr optionalAllotedSize); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_ULocalPlayer_GetViewPoint(IntPtr self, IntPtr outViewInfo); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_ULocalPlayer_InitOnlineSession(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_ULocalPlayer_IsCachedUniqueNetIdPairedWithControllerId(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_ULocalPlayer_IsPrimaryPlayer(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_ULocalPlayer_PlayerAdded(IntPtr self, IntPtr inViewportClient, int inControllerID); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_ULocalPlayer_PlayerRemoved(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_ULocalPlayer_SendSplitJoin(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_ULocalPlayer_SetControllerId(IntPtr self, int newControllerId); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_ULocalPlayer_SpawnPlayActor(IntPtr self, string uRL, string outError, IntPtr inWorld); #endregion #region Property /// <summary> /// The location of the player's view the previous frame. /// </summary> public FVector LastViewLocation { get => E_PROP_ULocalPlayer_LastViewLocation_GET(NativePointer); set => E_PROP_ULocalPlayer_LastViewLocation_SET(NativePointer, value); } /// <summary> /// The coordinates for the upper left corner of the master viewport subregion allocated to this player. 0-1 /// </summary> public FVector2D Origin { get => E_PROP_ULocalPlayer_Origin_GET(NativePointer); set => E_PROP_ULocalPlayer_Origin_SET(NativePointer, value); } /// <summary> /// The size of the master viewport subregion allocated to this player. 0-1 /// </summary> public FVector2D Size { get => E_PROP_ULocalPlayer_Size_GET(NativePointer); set => E_PROP_ULocalPlayer_Size_SET(NativePointer, value); } public UGameViewportClient ViewportClient { get => E_PROP_ULocalPlayer_ViewportClient_GET(NativePointer); set => E_PROP_ULocalPlayer_ViewportClient_SET(NativePointer, value); } #endregion #region ExternMethods /// <summary> /// Returns the controller ID for the player /// </summary> public int GetControllerId() => E_ULocalPlayer_GetControllerId(this); /// <summary> /// Retrieves any game-specific login options for this player /// <para>if this function returns a non-empty string, the returned option or options be added </para> /// passed in to the level loading and connection code. Options are in URL format, /// <para>key=value, with multiple options concatenated together with an & between each key/value pair </para> /// </summary> /// <return>URL</return> public virtual string GetGameLoginOptions() => E_ULocalPlayer_GetGameLoginOptions(this); /// <summary> /// Retrieves this player's name/tag from the online subsystem /// <para>if this function returns a non-empty string, the returned name will replace the "Name" URL parameter </para> /// passed around in the level loading and connection code, which normally comes from DefaultEngine.ini /// </summary> /// <return>Name</return> public virtual string GetNickname() => E_ULocalPlayer_GetNickname(this); /// <summary> /// This function will give you two points in Pixel Space that surround the World Space box. /// </summary> /// <param name="actorBox">The World Space Box</param> /// <param name="outLowerLeft">The Lower Left corner of the Pixel Space box</param> /// <param name="outUpperRight">The Upper Right corner of the pixel space box</param> /// <return>False</return> public bool GetPixelBoundingBox(FBox actorBox, FVector2D outLowerLeft, FVector2D outUpperRight, FVector2D optionalAllotedSize = null) => E_ULocalPlayer_GetPixelBoundingBox(this, actorBox, outLowerLeft, outUpperRight, optionalAllotedSize); /// <summary> /// This function will give you a point in Pixel Space from a World Space position /// </summary> /// <param name="inPoint">The point in world space</param> /// <param name="outPoint">The point in pixel space</param> /// <return>False</return> public bool GetPixelPoint(FVector inPoint, FVector2D outPoint, FVector2D optionalAllotedSize = null) => E_ULocalPlayer_GetPixelPoint(this, inPoint, outPoint, optionalAllotedSize); /// <summary> /// Retrieve the viewpoint of this player. /// </summary> /// <param name="outViewInfo">Upon return contains the view information for the player.</param> /// <param name="stereoPass">Which stereoscopic pass, if any, to get the viewport for. This will include eye offsetting</param> protected virtual void GetViewPoint(FMinimalViewInfo outViewInfo) => E_ULocalPlayer_GetViewPoint(this, outViewInfo); /// <summary> /// Called to initialize the online delegates /// </summary> public virtual void InitOnlineSession() => E_ULocalPlayer_InitOnlineSession(this); /// <summary> /// Returns true if the cached unique net id, is the one assigned to the controller id from the OSS /// </summary> public bool IsCachedUniqueNetIdPairedWithControllerId() => E_ULocalPlayer_IsCachedUniqueNetIdPairedWithControllerId(this); /// <summary> /// Determines whether this player is the first and primary player on their machine. /// </summary> /// <return>true</return> public bool IsPrimaryPlayer() => E_ULocalPlayer_IsPrimaryPlayer(this); /// <summary> /// Called at creation time for internal setup /// </summary> public virtual void PlayerAdded(UGameViewportClient inViewportClient, int inControllerID) => E_ULocalPlayer_PlayerAdded(this, inViewportClient, inControllerID); /// <summary> /// Called when the player is removed from the viewport client /// </summary> public virtual void PlayerRemoved() => E_ULocalPlayer_PlayerRemoved(this); /// <summary> /// Send a splitscreen join command to the server to allow a splitscreen player to connect to the game /// <para>the client must already be connected to a server for this function to work </para> /// @note this happens automatically for all viewports that exist during the initial server connect /// <para>so it's only necessary to manually call this for viewports created after that </para> /// if the join fails (because the server was full, for example) all viewports on this client will be disconnected /// </summary> public virtual void SendSplitJoin() => E_ULocalPlayer_SendSplitJoin(this); /// <summary> /// Change the ControllerId for this player; if the specified ControllerId is already taken by another player, changes the ControllerId /// <para>for the other player to the ControllerId currently in use by this player. </para> /// </summary> /// <param name="newControllerId">the ControllerId to assign to this player.</param> public virtual void SetControllerId(int newControllerId) => E_ULocalPlayer_SetControllerId(this, newControllerId); /// <summary> /// Create an actor for this player. /// </summary> /// <param name="uRL">The URL the player joined with.</param> /// <param name="outError">If an error occurred, returns the error description.</param> /// <param name="inWorld">World in which to spawn the play actor</param> /// <return>False</return> public virtual bool SpawnPlayActor(string uRL, string outError, UWorld inWorld) => E_ULocalPlayer_SpawnPlayActor(this, uRL, outError, inWorld); #endregion public static implicit operator IntPtr(ULocalPlayer self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator ULocalPlayer(ObjectPointerDescription PtrDesc) { return NativeManager.GetWrapper<ULocalPlayer>(PtrDesc); } } }
// QueryParser.cs // using ES6; using jQueryApi; using KnockoutApi; using Slick; using SparkleXrm.GridEditor; using System; using System.Collections.Generic; using System.Html; using System.Runtime.CompilerServices; using Xrm; using Xrm.Sdk; using Xrm.Sdk.Messages; using Xrm.Sdk.Metadata; using Xrm.Sdk.Metadata.Query; namespace ClientUI.ViewModels { public class QueryParser { public const string ParentRecordPlaceholder = "#ParentRecordPlaceholder#"; public IEnumerable<string> Entities; public Dictionary<string, EntityQuery> EntityLookup = new Dictionary<string, EntityQuery>(); Dictionary<string, EntityQuery> AliasEntityLookup = new Dictionary<string, EntityQuery>(); Dictionary<string, AttributeQuery> LookupAttributes = new Dictionary<string, AttributeQuery>(); public QueryParser(IEnumerable<string> entities) { Entities = entities; } public Promise GetQuickFinds() { return GetViewDefinition(true, null); } public Promise GetView(string entityLogicalName, string viewName) { return GetViewDefinition(false, viewName); } private Promise GetViewDefinition(bool isQuickFind, string viewName) { // Get the Quick Find View for the entity string getviewfetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='savedquery'> <attribute name='name' /> <attribute name='fetchxml' /> <attribute name='layoutxml' /> <attribute name='returnedtypecode' /> <filter type='and'> <filter type='or'>"; List<Promise> entityMetadata = new List<Promise>(); foreach (string entity in Entities) { entityMetadata.Add(Utility.GetEntityMetadata(entity).Then(delegate (object metadata) { return Promise.Resolve(metadata); })); } Script.Literal("debugger"); return Promise.All(entityMetadata).Then(delegate (List<EntityMetadata> result) { Script.Literal("debugger"); foreach (EntityMetadata metadata in result) { getviewfetchXml += @"<condition attribute='returnedtypecode' operator='eq' value='" + metadata.ObjectTypeCode.ToString() + @"'/>"; } return Promise.Resolve(true); }).Then(delegate (bool ok) { getviewfetchXml += @"</filter>"; if (isQuickFind) { getviewfetchXml += @"<condition attribute='isquickfindquery' operator='eq' value='1'/> <condition attribute='isdefault' operator='eq' value='1'/>"; } else if (viewName != null && viewName.Length > 0) { getviewfetchXml += @"<condition attribute='name' operator='eq' value='" + XmlHelper.Encode(viewName) + @"'/>"; } else { // Get default associated view getviewfetchXml += @"<condition attribute='querytype' operator='eq' value='2'/> <condition attribute='isdefault' operator='eq' value='1'/>"; } getviewfetchXml += @"</filter> </entity> </fetch>"; // Get the Quick Find View EntityCollection quickFindQuery = OrganizationServiceProxy.RetrieveMultiple(getviewfetchXml); Dictionary<string, Entity> entityLookup = new Dictionary<string, Entity>(); // Preseve the requested view order foreach (Entity view in quickFindQuery.Entities) { entityLookup[view.GetAttributeValueString("returnedtypecode")] = view; } foreach (string typeName in Entities) { Entity view = entityLookup[typeName]; string fetchXml = view.GetAttributeValueString("fetchxml"); string layoutXml = view.GetAttributeValueString("layoutxml"); EntityQuery query; if (EntityLookup.ContainsKey(typeName)) { query = EntityLookup[typeName]; } else { query = new EntityQuery(); query.LogicalName = typeName; query.Views = new Dictionary<string, FetchQuerySettings>(); query.Attributes = new Dictionary<string, AttributeQuery>(); EntityLookup[typeName] = query; } // Parse the fetch and layout to get the attributes and columns FetchQuerySettings config = Parse(fetchXml, layoutXml); query.Views[view.GetAttributeValueString("name")] = config; if (isQuickFind) { query.QuickFindQuery = config; } } return Promise.Resolve(true); }) ; //foreach (string entity in Entities) //{ // int? typeCode = (int?)Script.Literal("Mscrm.EntityPropUtil.EntityTypeName2CodeMap[{0}]", entity); //} } private FetchQuerySettings Parse(string fetchXml, string layoutXml) { FetchQuerySettings querySettings = new FetchQuerySettings(); //Quick find view features placeholders from {0} up to {4} based on attribute type. jQueryObject fetchXmlDOM = jQuery.FromHtml("<query>" + fetchXml .Replace("{0}", "#Query#") .Replace("{1}", "#QueryInt#") .Replace("{2}", "#QueryCurrency#") .Replace("{3}", "#QueryDateTime#") .Replace("{4}", "#QueryFloat#") + "</query>"); jQueryObject fetchElement = fetchXmlDOM.Find("fetch"); querySettings.FetchXml = fetchXmlDOM; ParseFetchXml(querySettings); querySettings.Columns = ParseLayoutXml(querySettings.RootEntity, layoutXml); return querySettings; } private List<Column> ParseLayoutXml(EntityQuery rootEntity, string layoutXml) { jQueryObject layout = jQuery.FromHtml(layoutXml); jQueryObject cells = layout.Find("cell"); List<Column> columns = new List<Column>(); cells.Each(delegate(int index, Element element) { string cellName = element.GetAttribute("name").ToString(); string logicalName = cellName; EntityQuery entity; AttributeQuery attribute; // Is this an alias attribute? int pos = cellName.IndexOf('.'); if (pos > -1) { // Aliased entity string alias = cellName.Substr(0, pos); logicalName = cellName.Substr(pos + 1); entity = AliasEntityLookup[alias]; } else { // Root entity entity=rootEntity; } // Does the attribute allready exist? if (entity.Attributes.ContainsKey(logicalName)) { // Already exists attribute = entity.Attributes[logicalName]; } else { // New attribute = new AttributeQuery(); attribute.Columns = new List<Column>(); attribute.LogicalName = logicalName; entity.Attributes[attribute.LogicalName] = attribute; } // Add column object widthAttribute = element.GetAttribute("width"); if (widthAttribute != null) { int width = int.Parse(element.GetAttribute("width").ToString()); object disableSorting = element.GetAttribute("disableSorting"); Column col = GridDataViewBinder.NewColumn(attribute.LogicalName, attribute.LogicalName, width); // Display name get's queried later col.Sortable = !(disableSorting != null && disableSorting.ToString() == "1"); attribute.Columns.Add(col); columns.Add(col); } }); return columns; } public void QueryMetadata() { // Load the display Names MetadataQueryBuilder builder = new MetadataQueryBuilder(); List<string> entities = new List<string>(); List<string> attributes = new List<string>(); foreach (string entityLogicalName in EntityLookup.Keys) { entities.Add(entityLogicalName); EntityQuery entity = EntityLookup[entityLogicalName]; foreach (string attributeLogicalName in entity.Attributes.Keys) { AttributeQuery attribute = entity.Attributes[attributeLogicalName]; string fieldName = attribute.LogicalName; int pos = fieldName.IndexOf('.'); if (entity.AliasName != null && pos>-1) { fieldName = fieldName.Substr(pos); } attributes.Add(fieldName); } } builder.AddEntities(entities, new List<string>("Attributes", "DisplayName", "DisplayCollectionName", "PrimaryImageAttribute")); builder.AddAttributes(attributes, new List<string>("DisplayName", "AttributeType", "IsPrimaryName")); builder.SetLanguage((int)Script.Literal("USER_LANGUAGE_CODE")); RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse) OrganizationServiceProxy.Execute(builder.Request); // Update the display names // TODO: Add the lookup relationship in brackets for alias entitie foreach (EntityMetadata entityMetadata in response.EntityMetadata) { // Get the entity EntityQuery entityQuery = EntityLookup[entityMetadata.LogicalName]; entityQuery.DisplayName = entityMetadata.DisplayName.UserLocalizedLabel.Label; entityQuery.DisplayCollectionName = entityMetadata.DisplayCollectionName.UserLocalizedLabel.Label; entityQuery.PrimaryImageAttribute = entityMetadata.PrimaryImageAttribute; entityQuery.EntityTypeCode = entityMetadata.ObjectTypeCode; foreach (AttributeMetadata attribute in entityMetadata.Attributes) { if (entityQuery.Attributes.ContainsKey(attribute.LogicalName)) { // Set the type AttributeQuery attributeQuery = entityQuery.Attributes[attribute.LogicalName]; attributeQuery.AttributeType = attribute.AttributeType; switch (attribute.AttributeType) { case AttributeTypeCode.Lookup: case AttributeTypeCode.Picklist: case AttributeTypeCode.Customer: case AttributeTypeCode.Owner: case AttributeTypeCode.Status: case AttributeTypeCode.State: case AttributeTypeCode.Boolean_: LookupAttributes[attribute.LogicalName] = attributeQuery; break; } attributeQuery.IsPrimaryName = attribute.IsPrimaryName; // If the type is a lookup, then add the 'name' on to the end in the fetchxml // this is so that we search the text value and not the numeric/guid value foreach (Column col in attributeQuery.Columns) { col.Name = attribute.DisplayName.UserLocalizedLabel.Label; col.DataType = attribute.IsPrimaryName.Value ? "PrimaryNameLookup" : attribute.AttributeType.ToString(); } } } } } private void ParseFetchXml(FetchQuerySettings querySettings) { jQueryObject fetchElement = querySettings.FetchXml; // Get the entities and link entities - only support 1 level deep jQueryObject entityElement = fetchElement.Find("entity"); string logicalName = entityElement.GetAttribute("name"); EntityQuery rootEntity; // Get query from cache or create new if (!EntityLookup.ContainsKey(logicalName)) { rootEntity = new EntityQuery(); rootEntity.LogicalName = logicalName; rootEntity.Attributes = new Dictionary<string, AttributeQuery>(); EntityLookup[rootEntity.LogicalName] = rootEntity; } else { rootEntity = EntityLookup[logicalName]; } // Get Linked Entities(1 deep) jQueryObject linkEntities = entityElement.Find("link-entity"); linkEntities.Each(delegate(int index, Element element) { EntityQuery link = new EntityQuery(); link.Attributes = new Dictionary<string, AttributeQuery>(); link.AliasName = element.GetAttribute("alias").ToString(); link.LogicalName = element.GetAttribute("name").ToString(); link.Views = new Dictionary<string, FetchQuerySettings>(); if (!EntityLookup.ContainsKey(link.LogicalName)) { EntityLookup[link.LogicalName] = link; } else { string alias = link.AliasName; link = EntityLookup[link.LogicalName]; link.AliasName = alias; } if (!AliasEntityLookup.ContainsKey(link.AliasName)) { AliasEntityLookup[link.AliasName] = link; } }); querySettings.RootEntity = rootEntity; // Issue #35 - Add any lookup/picklist quick find fields that are not included in results attributes will cause a format execption // because we don't have the metadata - this means that 'name' is not appended to the attribute // Add the search string and adjust any lookup columns jQueryObject conditions = fetchElement.Find("filter[isquickfindfields='1']"); conditions.First().Children().Each(delegate(int index, Element element) { logicalName = element.GetAttribute("attribute").ToString(); jQueryObject e = jQuery.FromElement(element); jQueryObject p =e.Parents("link-entity"); if (!querySettings.RootEntity.Attributes.ContainsKey(logicalName)) { AttributeQuery attribute = new AttributeQuery(); attribute.LogicalName = logicalName; attribute.Columns = new List<Column>(); querySettings.RootEntity.Attributes[logicalName] = attribute; } }); } public string GetFetchXmlForQuery(string entityLogicalName, string queryName, string searchTerm, SearchTermOptions searchOptions) { FetchQuerySettings config; if (queryName == "QuickFind") { config = EntityLookup[entityLogicalName].QuickFindQuery; } else { config = EntityLookup[entityLogicalName].Views[queryName]; } jQueryObject fetchElement = config.FetchXml.Clone().Find("fetch"); fetchElement.Attribute("distinct", "true"); fetchElement.Attribute("no-lock", "true"); jQueryObject orderByElement = fetchElement.Find("order"); orderByElement.Remove(); // Add the search string and adjust any lookup columns jQueryObject conditions = fetchElement.Find("filter[isquickfindfields='1']"); conditions.First().Children().Each(delegate(int index, Element element) { // Is this a lookup column? string logicalName = element.GetAttribute("attribute").ToString(); if (LookupAttributes.ContainsKey(logicalName)) { element.SetAttribute("attribute", logicalName + "name"); } }); //See what field types can we use for query and remove those attributes we cannot query using this search term. if (Number.IsNaN(Int32.Parse(searchTerm))) { fetchElement.Find("condition[value='#QueryInt#']").Remove(); } if (Number.IsNaN(Decimal.Parse(searchTerm))) { fetchElement.Find("condition[value='#QueryCurrency#']").Remove(); } if (Number.IsNaN(Date.Parse(searchTerm).GetDate())) { fetchElement.Find("condition[value='#QueryDateTime#']").Remove(); } if (Number.IsNaN(Double.Parse(searchTerm))) { fetchElement.Find("condition[value='#QueryFloat#']").Remove(); } // Add the sort order placeholder string fetchXml = fetchElement.Parent().GetHtml();//.Replace("</entity>", "{3}</entity>"); //Prepare search term based on options string textSearchTerm = searchTerm; if (searchOptions != null && (searchOptions & SearchTermOptions.PrefixWildcard) == SearchTermOptions.PrefixWildcard) { //Trimming, in case there are already wildcards with user input while (textSearchTerm.StartsWith("*") || textSearchTerm.StartsWith("%")) { textSearchTerm = textSearchTerm.Substring(1, textSearchTerm.Length); } textSearchTerm = "%" + textSearchTerm; } if (searchOptions != null && (searchOptions & SearchTermOptions.SuffixWildcard) == SearchTermOptions.SuffixWildcard) { //Trimming, in case there are already wildcards while (textSearchTerm.EndsWith("*") || textSearchTerm.EndsWith("%")) { textSearchTerm = textSearchTerm.Substring(0, textSearchTerm.Length - 1); } textSearchTerm = textSearchTerm + "%"; } // Add the Query term fetchXml = fetchXml.Replace("#Query#", XmlHelper.Encode(textSearchTerm)) .Replace("#QueryInt#", Int32.Parse(searchTerm).ToString()) .Replace("#QueryCurrency#", Double.Parse(searchTerm).ToString()) .Replace("#QueryDateTime#", XmlHelper.Encode(Date.Parse(searchTerm).Format("MM/dd/yyyy"))) .Replace("#QueryFloat#", Double.Parse(searchTerm).ToString()); return fetchXml; } public static string GetFetchXmlParentFilter(FetchQuerySettings query, string parentAttribute) { jQueryObject fetchElement = query.FetchXml.Find("fetch"); fetchElement.Attribute("count", "{0}"); fetchElement.Attribute("paging-cookie", "{1}"); fetchElement.Attribute("page", "{2}"); fetchElement.Attribute("returntotalrecordcount", "true"); fetchElement.Attribute("distinct", "true"); fetchElement.Attribute("no-lock", "true"); jQueryObject orderByElement = fetchElement.Find("order"); // Get the default order by field - currently only supports a single sort by column query.OrderByAttribute = orderByElement.GetAttribute("attribute"); query.OrderByDesending = orderByElement.GetAttribute("descending") == "true"; orderByElement.Remove(); // Get the root filter (if there is one) jQueryObject filter = fetchElement.Find("entity>filter"); if (filter != null ) { // Check that it is an 'and' filter string filterType = filter.GetAttribute("type"); if (filterType == "or") { // wrap up in an and filter jQueryObject andFilter = jQuery.FromHtml("<filter type='and'>" + filter.GetHtml() + "</filter>"); // remove existing filter filter.Remove(); filter = andFilter; // Add in the existing filter fetchElement.Find("entity").Append(andFilter); } } // Add in the parent query filter jQueryObject parentFilter = jQuery.FromHtml("<condition attribute='" + parentAttribute + "' operator='eq' value='" + ParentRecordPlaceholder + "'/>"); filter.Append(parentFilter); // Add the order by placeholder for the EntityDataViewModel return query.FetchXml.GetHtml().Replace("</entity>", "{3}</entity>"); } } [IgnoreNamespace] [Flags] public enum SearchTermOptions { None = 0, PrefixWildcard = 1, SuffixWildcard = 2 } [Imported] [ScriptName("Object")] [IgnoreNamespace] public class FetchQuerySettings { public string DisplayName; public List<Column> Columns; public EntityDataViewModel DataView; public jQueryObject FetchXml; public EntityQuery RootEntity; public Observable<string> RecordCount; public string OrderByAttribute; public bool OrderByDesending; } [Imported] [ScriptName("Object")] [IgnoreNamespace] public class EntityQuery { public string DisplayCollectionName; public string DisplayName; public string LogicalName; public string AliasName; public FetchQuerySettings QuickFindQuery; public Dictionary<string, FetchQuerySettings> Views; public int? EntityTypeCode; public string PrimaryImageAttribute; public Dictionary<string,AttributeQuery> Attributes; } [Imported] [ScriptName("Object")] [IgnoreNamespace] public class AttributeQuery { public List<Column> Columns; public string LogicalName; public AttributeTypeCode AttributeType; public bool? IsPrimaryName; } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Physics.Manager; namespace OpenSim.Region.Physics.POSPlugin { public class POSPrim : PhysicsActor { private Vector3 _position; private Vector3 _velocity; private Vector3 _acceleration; private Vector3 _size; private Vector3 m_rotationalVelocity = Vector3.Zero; private Quaternion _orientation; private bool iscolliding; public POSPrim() { } public override int PhysicsActorType { get { return (int) ActorTypes.Prim; } set { return; } } public override Vector3 RotationalVelocity { get { return m_rotationalVelocity; } set { m_rotationalVelocity = value; } } public override bool IsPhysical { get { return false; } set { return; } } public override bool ThrottleUpdates { get { return false; } set { return; } } public override bool IsColliding { get { return iscolliding; } set { iscolliding = value; } } public override bool CollidingGround { get { return false; } set { return; } } public override bool CollidingObj { get { return false; } set { return; } } public override bool Stopped { get { return false; } } public override Vector3 Position { get { return _position; } set { _position = value; } } public override Vector3 Size { get { return _size; } set { _size = value; } } public override float Mass { get { return 0f; } } public override Vector3 Force { get { return Vector3.Zero; } set { return; } } public override int VehicleType { get { return 0; } set { return; } } public override void VehicleFloatParam(int param, float value) { } public override void VehicleVectorParam(int param, Vector3 value) { } public override void VehicleRotationParam(int param, Quaternion rotation) { } public override void VehicleFlags(int param, bool remove) { } public override void SetVolumeDetect(int param) { } public override Vector3 CenterOfMass { get { return Vector3.Zero; } } public override Vector3 GeometricCenter { get { return Vector3.Zero; } } public override PrimitiveBaseShape Shape { set { return; } } public override float Buoyancy { get { return 0f; } set { return; } } public override bool FloatOnWater { set { return; } } public override Vector3 Velocity { get { return _velocity; } set { _velocity = value; } } public override float CollisionScore { get { return 0f; } set { } } public override Quaternion Orientation { get { return _orientation; } set { _orientation = value; } } public override Vector3 Acceleration { get { return _acceleration; } set { _acceleration = value; } } public override bool Kinematic { get { return true; } set { } } public override void AddForce(Vector3 force, bool pushforce) { } public override void AddAngularForce(Vector3 force, bool pushforce) { } public override Vector3 Torque { get { return Vector3.Zero; } set { return; } } public override void SetMomentum(Vector3 momentum) { } public override bool Flying { get { return false; } set { } } public override bool SetAlwaysRun { get { return false; } set { return; } } public override uint LocalID { set { return; } } public override bool Grabbed { set { return; } } public override void link(PhysicsActor obj) { } public override void delink() { } public override void LockAngularMotion(Vector3 axis) { } public override bool Selected { set { return; } } public override void CrossingFailure() { } public override Vector3 PIDTarget { set { return; } } public override bool PIDActive { get { return false; } set { return; } } public override float PIDTau { set { return; } } public override float PIDHoverHeight { set { return; } } public override bool PIDHoverActive { set { return; } } public override PIDHoverType PIDHoverType { set { return; } } public override float PIDHoverTau { set { return; } } public override Quaternion APIDTarget { set { return; } } public override bool APIDActive { set { return; } } public override float APIDStrength { set { return; } } public override float APIDDamping { set { return; } } public override void SubscribeEvents(int ms) { } public override void UnSubscribeEvents() { } public override bool SubscribedEvents() { return false; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using DC = Roar.implementation.DataConversion; public class DataModel { public string name; public Hashtable attributes = new Hashtable (); private Hashtable previousAttributes = new Hashtable (); private bool hasChanged = false; private string serverDataAPI; private string node; private bool isServerCalling = false; public bool HasDataFromServer { get; set; } protected DC.IXmlToHashtable xmlParser; protected IRequestSender api; protected Roar.ILogger logger; public DataModel (string name, string url, string node, ArrayList conditions, DC.IXmlToHashtable xmlParser, IRequestSender api, Roar.ILogger logger) { this.name = name; serverDataAPI = url; this.node = node; this.xmlParser = xmlParser; this.api = api; this.logger = logger; } // Return code for calls attempting to access/modify Model data // if none is present private void OnNoData () { OnNoData (null); } private void OnNoData (string key) { string msg = "No data intialised for Model: " + name; if (key != null) msg += " (Invalid access for \"" + key + "\")"; logger.DebugLog ("[roar] -- " + msg); } // Removes all attributes from the model public void Clear (bool silent = false) { attributes = new Hashtable (); // Set internal changed flag this.hasChanged = true; if (!silent) { RoarManager.OnComponentChange (name); } } // Internal call to retrieve model data from server and pass back // to `callback`. `params` is optional obj to pass to RoarAPI call. // `persistModel` optional can prevent Model data clearing. public bool Fetch (Roar.Callback cb) { return Fetch (cb, null, false); } public bool Fetch (Roar.Callback cb, Hashtable p) { return Fetch (cb, p, false); } public bool Fetch (Roar.Callback cb, Hashtable p, bool persist) { // Bail out if call for this Model is already underway if (this.isServerCalling) return false; // Reset the internal register if (!persist) attributes = new Hashtable (); // Using direct call (serverDataAPI url) rather than API mapping // - Unity doesn't easily support functions as strings: func['sub']['mo']() api.MakeCall (serverDataAPI, p, new OnFetch (cb, this)); this.isServerCalling = true; return true; } private class OnFetch : SimpleRequestCallback<IXMLNode> { protected DataModel model; public OnFetch (Roar.Callback in_cb, DataModel in_model) : base(in_cb) { model = in_model; } public override void Prologue () { // Reset this function call model.isServerCalling = false; } public override object OnSuccess (Roar.CallbackInfo<IXMLNode> info) { model.logger.DebugLog ("onFetch got given: " + info.data.DebugAsString ()); // First process the data for Model use string[] t = model.serverDataAPI.Split ('/'); if (t.Length != 2) throw new System.ArgumentException ("Invalid url format - must be abc/def"); string path = "roar>0>" + t [0] + ">0>" + t [1] + ">0>" + model.node; List<IXMLNode> nn = info.data.GetNodeList (path); if (nn == null) { model.logger.DebugLog (string.Format ("Unable to get node\nFor path = {0}\nXML = {1}", path, info.data.DebugAsString ())); } else { model.ProcessData (nn); } return model.attributes; } } // Preps the data from server and places it within the Model private void ProcessData (List<IXMLNode> d) { Hashtable o = new Hashtable (); if (d == null) logger.DebugLog ("[roar] -- No data to process!"); else { for (var i=0; i<d.Count; i++) { string key = xmlParser.GetKey (d [i]); if (key == null) { logger.DebugLog (string.Format ("no key found for {0}", d [i].DebugAsString ())); continue; } Hashtable hh = xmlParser.BuildHashtable (d [i]); if (o.ContainsKey (key)) { logger.DebugLog ("Duplicate key found"); } else { o [key] = hh; } } } // Flag server cache called // Must do before `set()` to flag before change events are fired HasDataFromServer = true; // Update the Model this.Set (o); logger.DebugLog ("Setting the model in " + name + " to : " + Roar.Json.ObjectToJSON (o)); logger.DebugLog ("[roar] -- Data Loaded: " + name); // Broadcast data ready event RoarManager.OnComponentReady (this.name); } // Shallow clone object public static Hashtable Clone (Hashtable obj) { if (obj == null) return null; Hashtable copy = new Hashtable (); foreach (DictionaryEntry prop in obj) { copy [prop.Key] = prop.Value; } return copy; } // Have to prefix 'set' as '_set' due to Unity function name restrictions public DataModel Set (Hashtable data) { return Set (data, false); } public DataModel Set (Hashtable data, bool silent) { // Setup temporary copy of attributes to be assigned // to the previousAttributes register if a change occurs var prev = Clone (this.attributes); foreach (DictionaryEntry prop in data) { this.attributes [prop.Key] = prop.Value; // Set internal changed flag this.hasChanged = true; // Broadcasts an attribute specific change event of the form: // **change:attribute_name** if (!silent) { RoarManager.OnComponentChange (this.name); } } // Broadcasts a `change` event if the model changed if (HasChanged && !silent) { this.previousAttributes = prev; this.Change (); } return this; } // Removes an attribute from the data model // and fires a change event unless `silent` is passed as an option public void Unset (string key) { Unset (key, false); } public void Unset (string key, bool silent) { // Setup temporary copy of attributes to be assigned // to the previousAttributes register if a change occurs var prev = Clone (this.attributes); // Check that server data is present if (!HasDataFromServer) { this.OnNoData (key); return; } if (this.attributes [key] != null) { // Remove the specific element this.attributes.Remove (key); this.hasChanged = true; // Broadcasts an attribute specific change event of the form: // **change:attribute_name** if (!silent) { RoarManager.OnComponentChange (this.name); } } // Broadcasts a `change` event if the model changed if (HasChanged && !silent) { this.previousAttributes = prev; this.Change (); } } // Returns the value of a given data key (usually an object) // Using '_get' due to Unity restrictions on function names public Hashtable Get (string key) { // Check that server data is present if (!HasDataFromServer) { this.OnNoData (key); return null; } if (this.attributes [key] != null) { return this.attributes [key] as Hashtable; } logger.DebugLog ("[roar] -- No property found: " + key); return null; } // Returns the embedded value within an object attribute public string GetValue (string key) { var o = this.Get (key); if (o != null) return o ["value"] as string; else return null; } // Returns an array of all the elements in this.attributes public ArrayList List () { var l = new ArrayList (); // Check that server data is present if (!HasDataFromServer) { this.OnNoData (); return l; } foreach (DictionaryEntry prop in this.attributes) { l.Add (prop.Value); } return l; } // Returns the object of an attribute key from the PREVIOUS register public Hashtable Previous (string key) { // Check that server data is present if (!HasDataFromServer) { this.OnNoData (key); return null; } if (this.previousAttributes [key] != null) return this.previousAttributes [key] as Hashtable; else return null; } // Checks whether element `key` is present in the // list of ikeys in the Model. Optional `number` to search, default 1 // Returns true if player has equal or greater number, false if not, and // null for an invalid query. public bool Has (string key) { return Has (key, 1); } public bool Has (string key, int number) { // Fire warning *only* if no data intitialised, but continue if (!HasDataFromServer) { this.OnNoData (key); return false; } int count = 0; foreach (DictionaryEntry i in this.attributes) { // Search `ikey`, `id` and `shop_ikey` keys and increment counter if found if ((i.Value as Hashtable) ["ikey"] as string == key) count++; else if ((i.Value as Hashtable) ["id"] as string == key) count++; else if ((i.Value as Hashtable) ["shop_ikey"] as string == key) count++; } if (count >= number) return true; else { return false; } } // Similar to Model.Has(), but returns the number of elements in the // Model of id or ikey `key`. public int Quantity (string key) { // Fire warning *only* if no data initialised, but continue if (!HasDataFromServer) { this.OnNoData (key); return 0; } int count = 0; foreach (DictionaryEntry i in this.attributes) { // Search `ikey`, `id` and `shop_ikey` keys and increment counter if found if ((i.Value as Hashtable) ["ikey"] as string == key) count++; else if ((i.Value as Hashtable) ["id"] as string == key) count++; else if ((i.Value as Hashtable) ["shop_ikey"] as string == key) count++; } return count; } // Flag to indicate whether the model has changed since last "change" event public bool HasChanged { get { return hasChanged; } } // Manually fires a "change" event on this model public void Change () { RoarManager.OnComponentChange (this.name); this.hasChanged = false; } }
// Copyright (c) Oleg Zudov. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using Zu.WebBrowser.AsyncInteractions; using Zu.WebBrowser.BasicTypes; using MyCommunicationLib.Communication.MarionetteComands; using System; using System.Collections.Generic; using System.Linq; namespace Zu.Firefox { public class FirefoxDriverElements : IElements { private IAsyncFirefoxDriver asyncFirefoxDriver; public FirefoxDriverElements(IAsyncFirefoxDriver asyncFirefoxDriver) { this.asyncFirefoxDriver = asyncFirefoxDriver; } public async Task Click(string elementId, CancellationToken cancellationToken = default (CancellationToken)) { await asyncFirefoxDriver.CheckConnected(cancellationToken).ConfigureAwait(false); if (asyncFirefoxDriver.ClientMarionette == null) throw new Exception("error: no clientMarionette"); var comm1 = new ClickElementCommand(elementId); await asyncFirefoxDriver.ClientMarionette.SendRequestAsync(comm1, cancellationToken).ConfigureAwait(false); if (comm1.Error != null) throw new WebBrowserException(comm1.Error); } public async Task<JToken> FindElement(string strategy, string expr, string startNode, string notElementId, TimeSpan timeout, CancellationToken cancellationToken = default (CancellationToken)) { try { JToken res = null; var waitEnd = default (DateTime); var nowTime = DateTime.Now; while (true) { res = await FindElementNotWait(strategy, expr, startNode, cancellationToken).ConfigureAwait(false); if (!ResultValueConverter.ValueIsNull(res)) { if (notElementId == null) break; else { var elId = GetElementFromResponse(res); if (elId != notElementId) break; } } if (waitEnd == default (DateTime)) { var implicitWait = timeout; if (implicitWait == default (TimeSpan)) implicitWait = await asyncFirefoxDriver.Options.Timeouts.GetImplicitWait().ConfigureAwait(false); if (implicitWait == default (TimeSpan)) break; waitEnd = nowTime + implicitWait; } if (DateTime.Now > waitEnd) break; await Task.Delay(50).ConfigureAwait(false); } if (ResultValueConverter.ValueIsNull(res)) throw new WebBrowserException($"Element not found by {strategy} = {expr}", "no such element"); return res; } catch { throw; } } public static string GetElementFromResponse(JToken response) { if (response == null) return null; string id = null; var json = response is JValue ? JToken.Parse(response.Value<string>()) : response["value"]; if (json is JValue) { if (((JValue)json).Value == null) return null; else return ((JValue)json).Value<string>(); } id = json?["element-6066-11e4-a52e-4f735466cecf"]?.ToString(); if (id == null) id = json?["ELEMENT"]?.ToString(); return id; } public async Task<JToken> FindElementNotWait(string strategy, string expr, string startNode = null, CancellationToken cancellationToken = default (CancellationToken)) { await asyncFirefoxDriver.CheckConnected(cancellationToken).ConfigureAwait(false); if (asyncFirefoxDriver.ClientMarionette == null) throw new Exception("error: no clientMarionette"); var comm1 = new FindElementCommand(strategy, expr, startNode); await asyncFirefoxDriver.ClientMarionette.SendRequestAsync(comm1, cancellationToken).ConfigureAwait(false); if (comm1.Error != null) throw new WebBrowserException(comm1.Error); return comm1.Result; } public async Task<JToken> FindElements(string strategy, string expr, string startNode, string notElementId, TimeSpan timeout, CancellationToken cancellationToken = default (CancellationToken)) { try { JToken res = null; var waitEnd = default (DateTime); var nowTime = DateTime.Now; while (true) { res = await FindElementsNotWait(strategy, expr, startNode, cancellationToken).ConfigureAwait(false); if ((res as JArray)?.Any() != true) { if (notElementId == null) break; else { var elId = GetElementsFromResponse(res); if (elId?.FirstOrDefault() != notElementId) break; } } if (waitEnd == default (DateTime)) { var implicitWait = timeout; if (implicitWait == default (TimeSpan)) implicitWait = await asyncFirefoxDriver.Options.Timeouts.GetImplicitWait().ConfigureAwait(false); if (implicitWait == default (TimeSpan)) break; waitEnd = nowTime + implicitWait; } if (DateTime.Now > waitEnd) break; await Task.Delay(50).ConfigureAwait(false); } //if ((res as JArray)?.Any() != true) throw new WebBrowserException($"Elements not found by {strategy} = {expr}", "no such element"); return res; } catch { throw; } //var res = await FindElementsNotWait(strategy, expr, startNode, cancellationToken = default(CancellationToken)); //if ((res as JArray)?.Any() != true) //{ // var implicitWait = await asyncFirefoxDriver.Options.Timeouts.GetImplicitWait(); // if (implicitWait != default(TimeSpan)) // { // var waitEnd = DateTime.Now + implicitWait; // while (((res as JArray)?.Any() != true) && DateTime.Now < waitEnd) // { // Thread.Sleep(50); // res = await FindElementsNotWait(strategy, expr, startNode, cancellationToken = default(CancellationToken)); // } // } //} //if (res == null) throw new WebBrowserException($"Elements not found by {strategy} = {expr}", "no such element"); //return res; ////return asyncChromeDriver.WindowCommands.FindElements(strategy, expr, startNode, cancellationToken); } public async Task<JToken> FindElementsNotWait(string strategy, string expr, string startNode = null, CancellationToken cancellationToken = default (CancellationToken)) { await asyncFirefoxDriver.CheckConnected(cancellationToken).ConfigureAwait(false); if (asyncFirefoxDriver.ClientMarionette == null) throw new Exception("error: no clientMarionette"); var comm1 = new FindElementsCommand(strategy, expr, startNode); await asyncFirefoxDriver.ClientMarionette.SendRequestAsync(comm1, cancellationToken).ConfigureAwait(false); if (comm1.Error != null) throw new WebBrowserException(comm1.Error); return comm1.Result; } public async Task<string> ClearElement(string elementId, CancellationToken cancellationToken = default (CancellationToken)) { await asyncFirefoxDriver.CheckConnected(cancellationToken).ConfigureAwait(false); if (asyncFirefoxDriver.ClientMarionette == null) throw new Exception("error: no clientMarionette"); var comm1 = new ClearElementCommand(elementId); await asyncFirefoxDriver.ClientMarionette.SendRequestAsync(comm1, cancellationToken).ConfigureAwait(false); if (comm1.Error != null) throw new WebBrowserException(comm1.Error); return "ok"; } public async Task<string> GetActiveElement(CancellationToken cancellationToken = default (CancellationToken)) { await asyncFirefoxDriver.CheckConnected(cancellationToken).ConfigureAwait(false); if (asyncFirefoxDriver.ClientMarionette == null) throw new Exception("error: no clientMarionette"); var comm1 = new GetActiveElementCommand(); await asyncFirefoxDriver.ClientMarionette.SendRequestAsync(comm1, cancellationToken).ConfigureAwait(false); if (comm1.Error != null) throw new WebBrowserException(comm1.Error); return FirefoxDriverElements.GetElementFromResponse(comm1.Result); } public async Task<string> GetElementAttribute(string elementId, string attrName, CancellationToken cancellationToken = default (CancellationToken)) { await asyncFirefoxDriver.CheckConnected(cancellationToken).ConfigureAwait(false); if (asyncFirefoxDriver.ClientMarionette == null) throw new Exception("error: no clientMarionette"); var comm1 = new GetElementAttributeCommand(elementId, attrName); await asyncFirefoxDriver.ClientMarionette.SendRequestAsync(comm1, cancellationToken).ConfigureAwait(false); if (comm1.Error != null) throw new WebBrowserException(comm1.Error); return (string)comm1.Result["value"]; // comm1.Result is JValue ? comm1.Result.ToString() : comm1.Result?["value"]?.ToString(); } public Task<WebPoint> GetElementLocation(string elementId, CancellationToken cancellationToken = default (CancellationToken)) { throw new System.NotImplementedException(); } public async Task<string> GetElementProperty(string elementId, string propertyName, CancellationToken cancellationToken = default (CancellationToken)) { await asyncFirefoxDriver.CheckConnected(cancellationToken).ConfigureAwait(false); if (asyncFirefoxDriver.ClientMarionette == null) throw new Exception("error: no clientMarionette"); var comm1 = new GetElementPropertyCommand(elementId, propertyName); await asyncFirefoxDriver.ClientMarionette.SendRequestAsync(comm1, cancellationToken).ConfigureAwait(false); if (comm1.Error != null) throw new WebBrowserException(comm1.Error); return (string)comm1.Result["value"]; // comm1.Result is JValue ? comm1.Result.ToString() : comm1.Result?["value"]?.ToString(); } public async Task<WebRect> GetElementRect(string elementId, CancellationToken cancellationToken = default (CancellationToken)) { await asyncFirefoxDriver.CheckConnected(cancellationToken).ConfigureAwait(false); if (asyncFirefoxDriver.ClientMarionette == null) throw new Exception("error: no clientMarionette"); var comm1 = new GetElementRectCommand(elementId); await asyncFirefoxDriver.ClientMarionette.SendRequestAsync(comm1, cancellationToken).ConfigureAwait(false); if (comm1.Error != null) throw new WebBrowserException(comm1.Error); return ResultValueConverter.ToWebRect(comm1.Result); } public Task<WebSize> GetElementSize(string elementId, CancellationToken cancellationToken = default (CancellationToken)) { throw new System.NotImplementedException(); } public async Task<string> GetElementTagName(string elementId, CancellationToken cancellationToken = default (CancellationToken)) { await asyncFirefoxDriver.CheckConnected(cancellationToken).ConfigureAwait(false); if (asyncFirefoxDriver.ClientMarionette == null) throw new Exception("error: no clientMarionette"); var comm1 = new GetElementTagNameCommand(elementId); await asyncFirefoxDriver.ClientMarionette.SendRequestAsync(comm1, cancellationToken).ConfigureAwait(false); if (comm1.Error != null) throw new WebBrowserException(comm1.Error); return (string)comm1.Result["value"]; // comm1.Result is JValue ? comm1.Result.ToString() : comm1.Result?["value"]?.ToString(); } public async Task<string> GetElementText(string elementId, CancellationToken cancellationToken = default (CancellationToken)) { await asyncFirefoxDriver.CheckConnected(cancellationToken).ConfigureAwait(false); if (asyncFirefoxDriver.ClientMarionette == null) throw new Exception("error: no clientMarionette"); var comm1 = new GetElementTextCommand(elementId); await asyncFirefoxDriver.ClientMarionette.SendRequestAsync(comm1, cancellationToken).ConfigureAwait(false); if (comm1.Error != null) throw new WebBrowserException(comm1.Error); return (string)comm1.Result["value"]; // comm1.Result is JValue ? (JValue)comm1.Result.ToString() : comm1.Result?["value"]?.ToString(); } public async Task<string> GetElementValueOfCssProperty(string elementId, string propertyName, CancellationToken cancellationToken = default (CancellationToken)) { await asyncFirefoxDriver.CheckConnected(cancellationToken).ConfigureAwait(false); if (asyncFirefoxDriver.ClientMarionette == null) throw new Exception("error: no clientMarionette"); var comm1 = new GetElementValueOfCssPropertyCommand(elementId, propertyName); await asyncFirefoxDriver.ClientMarionette.SendRequestAsync(comm1, cancellationToken).ConfigureAwait(false); if (comm1.Error != null) throw new WebBrowserException(comm1.Error); return (string)comm1.Result["value"]; // comm1.Result is JValue ? comm1.Result.ToString() : comm1.Result?["value"]?.ToString(); } public async Task<bool> IsElementDisplayed(string elementId, CancellationToken cancellationToken = default (CancellationToken)) { await asyncFirefoxDriver.CheckConnected(cancellationToken).ConfigureAwait(false); if (asyncFirefoxDriver.ClientMarionette == null) throw new Exception("error: no clientMarionette"); var comm1 = new IsElementDisplayedCommand(elementId); await asyncFirefoxDriver.ClientMarionette.SendRequestAsync(comm1, cancellationToken).ConfigureAwait(false); if (comm1.Error != null) throw new WebBrowserException(comm1.Error); return ResultValueConverter.ToBool(comm1.Result); } public async Task<bool> IsElementEnabled(string elementId, CancellationToken cancellationToken = default (CancellationToken)) { await asyncFirefoxDriver.CheckConnected(cancellationToken).ConfigureAwait(false); if (asyncFirefoxDriver.ClientMarionette == null) throw new Exception("error: no clientMarionette"); var comm1 = new IsElementEnabledCommand(elementId); await asyncFirefoxDriver.ClientMarionette.SendRequestAsync(comm1, cancellationToken).ConfigureAwait(false); if (comm1.Error != null) throw new WebBrowserException(comm1.Error); return ResultValueConverter.ToBool(comm1.Result); } public async Task<bool> IsElementSelected(string elementId, CancellationToken cancellationToken = default (CancellationToken)) { await asyncFirefoxDriver.CheckConnected(cancellationToken).ConfigureAwait(false); if (asyncFirefoxDriver.ClientMarionette == null) throw new Exception("error: no clientMarionette"); var comm1 = new IsElementSelectedCommand(elementId); await asyncFirefoxDriver.ClientMarionette.SendRequestAsync(comm1, cancellationToken).ConfigureAwait(false); if (comm1.Error != null) throw new WebBrowserException(comm1.Error); return ResultValueConverter.ToBool(comm1.Result); } public async Task<string> SendKeysToElement(string elementId, string value, CancellationToken cancellationToken = default (CancellationToken)) { await asyncFirefoxDriver.CheckConnected(cancellationToken).ConfigureAwait(false); if (asyncFirefoxDriver.ClientMarionette == null) throw new Exception("error: no clientMarionette"); var comm1 = new SendKeysToElementCommand(elementId, value); await asyncFirefoxDriver.ClientMarionette.SendRequestAsync(comm1, cancellationToken).ConfigureAwait(false); if (comm1.Error != null) throw new WebBrowserException(comm1.Error); return "ok"; } public async Task<string> SubmitElement(string elementId, CancellationToken cancellationToken = default (CancellationToken)) { await asyncFirefoxDriver.CheckConnected(cancellationToken).ConfigureAwait(false); if (asyncFirefoxDriver.ClientMarionette == null) throw new Exception("error: no clientMarionette"); string elementType = await GetElementProperty(elementId, "type", cancellationToken).ConfigureAwait(false); if (elementType != null && elementType == "submit") { await this.Click(elementId, cancellationToken).ConfigureAwait(false); } else { var json = await asyncFirefoxDriver.Elements.FindElement("xpath", "./ancestor-or-self::form", elementId).ConfigureAwait(false); var form = GetElementFromResponse(json); var elementDictionary = new Dictionary<string, object>(); elementDictionary.Add("ELEMENT", form); elementDictionary.Add("element-6066-11e4-a52e-4f735466cecf", form); await asyncFirefoxDriver.JavaScriptExecutor.ExecuteScript("var e = arguments[0].ownerDocument.createEvent('Event');" + "e.initEvent('submit', true, true);" + "if (arguments[0].dispatchEvent(e)) { arguments[0].submit(); }", cancellationToken, elementDictionary).ConfigureAwait(false); // json.ToString());// "{ \"ELEMENT\": \"" + form + "\"}" ); } //var comm1 = new SubmitElementCommand(elementId); //await asyncFirefoxDriver.ClientMarionette?.SendRequestAsync(comm1, cancellationToken); //if (comm1.Error != null) throw new WebBrowserException(comm1.Error); return "ok"; } //public static string GetElementFromResponse(JToken response) //{ // string id = null; // var json = response is JValue ? JToken.Parse(response.Value<string>()) : response["value"]; // id = json?["element-6066-11e4-a52e-4f735466cecf"]?.ToString(); // if (id == null) // id = json?["ELEMENT"]?.ToString(); // return id; //} public static List<string> GetElementsFromResponse(JToken response) { var toReturn = new List<string>(); if (response is JArray) foreach (var item in response) { string id = null; try { var json = item is JValue ? JToken.Parse(item.Value<string>()) : item; id = json?["element-6066-11e4-a52e-4f735466cecf"]?.ToString(); if (id == null) id = json?["ELEMENT"]?.ToString(); } catch { } toReturn.Add(id); } return toReturn; } #region FindElement variants public Task<JToken> FindElement(string strategy, string expr, CancellationToken cancellationToken = default (CancellationToken)) { return FindElement(strategy, expr, null, null, default (TimeSpan), cancellationToken); } public Task<JToken> FindElement(string strategy, string expr, TimeSpan timeout, CancellationToken cancellationToken = default (CancellationToken)) { return FindElement(strategy, expr, null, null, timeout, cancellationToken); } public Task<JToken> FindElement(string strategy, string expr, int timeoutMs, CancellationToken cancellationToken = default (CancellationToken)) { return FindElement(strategy, expr, null, null, TimeSpan.FromMilliseconds(timeoutMs), cancellationToken); } public Task<JToken> FindElement(string strategy, string expr, string startNode, CancellationToken cancellationToken = default (CancellationToken)) { return FindElement(strategy, expr, startNode, null, default (TimeSpan), cancellationToken); } public Task<JToken> FindElement(string strategy, string expr, string startNode, TimeSpan timeout, CancellationToken cancellationToken = default (CancellationToken)) { return FindElement(strategy, expr, startNode, null, timeout, cancellationToken); } public Task<JToken> FindElement(string strategy, string expr, string startNode, int timeoutMs, CancellationToken cancellationToken = default (CancellationToken)) { return FindElement(strategy, expr, startNode, null, TimeSpan.FromMilliseconds(timeoutMs), cancellationToken); } public Task<JToken> FindElement(string strategy, string expr, string startNode, string notElementId, CancellationToken cancellationToken = default (CancellationToken)) { return FindElement(strategy, expr, startNode, notElementId, default (TimeSpan), cancellationToken); } public Task<JToken> FindElement(string strategy, string expr, string startNode, string notElementId, int timeoutMs, CancellationToken cancellationToken = default (CancellationToken)) { return FindElement(strategy, expr, startNode, notElementId, TimeSpan.FromMilliseconds(timeoutMs), cancellationToken); } public Task<JToken> FindElements(string strategy, string expr, CancellationToken cancellationToken = default (CancellationToken)) { return FindElements(strategy, expr, null, null, default (TimeSpan), cancellationToken); } public Task<JToken> FindElements(string strategy, string expr, TimeSpan timeout, CancellationToken cancellationToken = default (CancellationToken)) { return FindElements(strategy, expr, null, null, timeout, cancellationToken); } public Task<JToken> FindElements(string strategy, string expr, int timeoutMs, CancellationToken cancellationToken = default (CancellationToken)) { return FindElements(strategy, expr, null, null, TimeSpan.FromMilliseconds(timeoutMs), cancellationToken); } public Task<JToken> FindElements(string strategy, string expr, string startNode, CancellationToken cancellationToken = default (CancellationToken)) { return FindElements(strategy, expr, startNode, null, default (TimeSpan), cancellationToken); } public Task<JToken> FindElements(string strategy, string expr, string startNode, TimeSpan timeout, CancellationToken cancellationToken = default (CancellationToken)) { return FindElements(strategy, expr, startNode, null, timeout, cancellationToken); } public Task<JToken> FindElements(string strategy, string expr, string startNode, int timeoutMs, CancellationToken cancellationToken = default (CancellationToken)) { return FindElements(strategy, expr, startNode, null, TimeSpan.FromMilliseconds(timeoutMs), cancellationToken); } public Task<JToken> FindElements(string strategy, string expr, string startNode, string notElementId, CancellationToken cancellationToken = default (CancellationToken)) { return FindElements(strategy, expr, startNode, notElementId, default (TimeSpan), cancellationToken); } public Task<JToken> FindElements(string strategy, string expr, string startNode, string notElementId, int timeoutMs, CancellationToken cancellationToken = default (CancellationToken)) { return FindElements(strategy, expr, startNode, notElementId, TimeSpan.FromMilliseconds(timeoutMs), cancellationToken); } #endregion } }
/*``The contents of this file are subject to the Erlang Public License, * Version 1.1, (the "License"); you may not use this file except in * compliance with the License. You should have received a copy of the * Erlang Public License along with this software. If not, it can be * retrieved via the world wide web at http://www.erlang.org/. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See * the License for the specific language governing rights and limitations * under the License. * * The Initial Developer of the Original Code is Ericsson Utvecklings AB. * Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings * AB. All Rights Reserved.'' * * Converted from Java to C# by Vlad Dumitrescu (vlad_Dumitrescu@hotmail.com) */ namespace Otp { /* * This class represents local node types. It is used to group the * node types {@link OtpNode OtpNode} and {@link OtpSelf OtpSelf}. **/ using System; public class OtpLocalNode:AbstractNode { private int serial = 0; private int pidCount = 1; private int portCount = 1; private int[] refId; protected internal int _port; protected internal System.Net.Sockets.TcpClient epmd; public static bool ignoreLocalEpmdConnectErrors = false; // handle status changes protected OtpNodeStatus handler; /* * Create a node with the given name and the default cookie. **/ protected internal OtpLocalNode(System.String node) : base(node) { init(); } /* * Create a node with the given name and cookie. **/ protected internal OtpLocalNode(System.String node, System.String cookie) : base(node, cookie, false) { init(); } protected internal OtpLocalNode(System.String node, System.String cookie, bool shortName) : base(node, cookie, shortName) { init(); } private void init() { serial = 0; pidCount = 1; portCount = 1; refId = new int[3]; refId[0] = 1; refId[1] = 0; refId[2] = 0; handler = new OtpNodeStatus(); } /* * Register interest in certain system events. The {@link * OtpNodeStatus OtpNodeStatus} handler object contains callback * methods, that will be called when certain events occur. * * @param handler the callback object to register. To clear the * handler, specify null as the handler to use. * **/ public virtual void registerStatusHandler(OtpNodeStatus handler) { lock (this) { this.handler = handler; } } public void registerStatusHandler(OtpNodeStatus.ConnectionStatusDelegate callback) { this.handler.registerStatusHandler(callback); } /*use these wrappers to call handler functions */ internal void remoteStatus(System.String node, bool up, System.Object info) { lock (this) { if (handler == null) return; try { handler.remoteStatus(node, up, info); } catch (System.Exception) { } } } internal void localStatus(System.String node, bool up, System.Object info) { lock (this) { if (handler == null) return; try { handler.localStatus(node, up, info); } catch (System.Exception) { } } } internal void connAttempt(System.String node, bool incoming, System.Object info) { lock (this) { if (handler == null) return; try { handler.connAttempt(node, incoming, info); } catch (System.Exception) { } } } internal void epmdFailedConnAttempt(System.String node, System.Object info) { lock (this) { if (handler == null) return; try { handler.epmdFailedConnAttempt(node, info); } catch (System.Exception) { } } } /* * Get the port number used by this node. * * @return the port number this server node is accepting * connections on. **/ public virtual int port() { return this._port; } /* * Set the Epmd socket after publishing this nodes listen port to * Epmd. * * @param s The socket connecting this node to Epmd. **/ protected internal virtual void setEpmd(System.Net.Sockets.TcpClient s) { this.epmd = s; } /* * Get the Epmd socket. * * @return The socket connecting this node to Epmd. **/ protected internal virtual System.Net.Sockets.TcpClient getEpmd() { return epmd; } /* * Create an Erlang {@link Pid pid}. Erlang pids are based * upon some node specific information; this method creates a pid * using the information in this node. Each call to this method * produces a unique pid. * * @return an Erlang pid. **/ public virtual Erlang.Pid createPid() { lock(this) { Erlang.Pid p = new Erlang.Pid(_node, pidCount, serial, _creation); pidCount++; if (pidCount > 0x7fff) { pidCount = 0; serial++; if (serial > 0x07) { serial = 0; } } return p; } } /* * Create an Erlang {@link Port port}. Erlang ports are * based upon some node specific information; this method creates a * port using the information in this node. Each call to this method * produces a unique port. It may not be meaningful to create a port * in a non-Erlang environment, but this method is provided for * completeness. * * @return an Erlang port. **/ public virtual Erlang.Port createPort() { lock(this) { Erlang.Port p = new Erlang.Port(_node, portCount, _creation); portCount++; if (portCount > 0x3ffff) portCount = 0; return p; } } /* * Create an Erlang {@link Ref reference}. Erlang * references are based upon some node specific information; this * method creates a reference using the information in this node. * Each call to this method produces a unique reference. * * @return an Erlang reference. **/ public virtual Erlang.Ref createRef() { lock(this) { Erlang.Ref r = new Erlang.Ref(_node, refId, _creation); // increment ref ids (3 ints: 18 + 32 + 32 bits) refId[0]++; if (refId[0] > 0x3ffff) { refId[0] = 0; refId[1]++; if (refId[1] == 0) { refId[2]++; } } return r; } } } }
using IKVM.Attributes; using IKVM.Runtime; using java.io; using java.lang; using java.util.concurrent; using System; using System.Runtime.CompilerServices; using System.Threading; namespace lanterna.gui2 { //[Implements(new string[] { "lanterna.gui2.AsynchronousTextGUIThread" })] public class SeparateTextGUIThread : AbstractTextGUIThread, AsynchronousTextGUIThread, TextGUIThread { //[Implements(new string[] { "lanterna.gui2.TextGUIThreadFactory" }), InnerClass, SourceFile("SeparateTextGUIThread.java")] public class Factory : java.lang.Object, TextGUIThreadFactory { //[LineNumberTable(149)] //[MethodImpl(MethodImplOptions.NoInlining)] public Factory() { } //[LineNumberTable(152)] //[MethodImpl(MethodImplOptions.NoInlining)] public virtual TextGUIThread createTextGUIThread(TextGUI textGUI) { return new SeparateTextGUIThread(textGUI, null); } } private volatile AsynchronousTextGUIThread.State state; //[Modifiers] private Thread textGUIThread; //[Modifiers] private CountDownLatch waitLatch; //[LineNumberTable(44), Modifiers] //[MethodImpl(MethodImplOptions.NoInlining)] internal static void access_000(SeparateTextGUIThread x0) { x0.mainGUILoop(); } //[LineNumberTable(44), Modifiers] //[MethodImpl(MethodImplOptions.NoInlining)] internal SeparateTextGUIThread(TextGUI x0, SeparateTextGUIThread_1 x1) : this(x0) { } //[LineNumberTable(new byte[] { 159, 130, 130, 106, 109, 242, 70, 115 })] //[MethodImpl(MethodImplOptions.NoInlining)] private SeparateTextGUIThread(TextGUI textGUI) : base(textGUI) { this.waitLatch = new CountDownLatch(1); this.textGUIThread = new SeparateTextGUIThread_1(this, "LanternaGUI"); this.state = AsynchronousTextGUIThread.State._CREATED; Thread.MemoryBarrier(); } //[LineNumberTable(new byte[] { 159, 116, 66, 255, 8, 100, 115, 245, 34, 232, 59, 98, 206, 229, 93, 115, 243, 32, 99, 243, 94, 115, 239, 35, 144, 137, 152, 255, 10, 86, 115, 255, 9, 59, 234, 49, 99, 103, 229, 81, 115, 246, 48, 99, 112, 103, 227, 72, 199, 115, 248, 54, 99, 112, 103, 131, 199, 115, 52, 115, 108, 99 })] //[MethodImpl(MethodImplOptions.NoInlining)] private void mainGUILoop() { IOException ex; RuntimeException ex2; try { try { try { this._textGUI.updateScreen(); } catch (IOException arg_12_0) { ex = ByteCodeHelper.MapException<IOException>(arg_12_0, 1); goto IL_4A; } } catch (Exception arg_1B_0) { RuntimeException expr_20 = ByteCodeHelper.MapException<RuntimeException>(arg_1B_0, 0); if (expr_20 == null) { throw; } ex2 = expr_20; goto IL_4D; } } catch { this.state = AsynchronousTextGUIThread.State._STOPPED; Thread.MemoryBarrier(); this.waitLatch.countDown(); throw; } IOException ex5; RuntimeException ex6; while (true) { try { IL_CB: if (this.state == AsynchronousTextGUIThread.State._STARTED) { try { try { try { if (!this.processEventsAndUpdate()) { try { Thread.sleep(1L); } catch (InterruptedException arg_F1_0) { InterruptedException ex3 = ByteCodeHelper.MapException<InterruptedException>(arg_F1_0, 1); } } continue; } catch (EOFException arg_102_0) { EOFException ex4 = ByteCodeHelper.MapException<EOFException>(arg_102_0, 1); goto IL_150; } } catch (IOException arg_10C_0) { ex5 = ByteCodeHelper.MapException<IOException>(arg_10C_0, 1); goto IL_154; } } catch (Exception arg_115_0) { RuntimeException expr_11A = ByteCodeHelper.MapException<RuntimeException>(arg_115_0, 0); if (expr_11A == null) { throw; } ex6 = expr_11A; goto IL_157; } } } catch { this.state = AsynchronousTextGUIThread.State._STOPPED; Thread.MemoryBarrier(); this.waitLatch.countDown(); throw; } break; continue; continue; IL_154: IOException ex7 = ex5; try { IOException e = ex7; if (!this.exceptionHandler.onIOException(e)) { continue; } this.stop(); } catch { this.state = AsynchronousTextGUIThread.State._STOPPED; Thread.MemoryBarrier(); this.waitLatch.countDown(); throw; } break; continue; IL_157: RuntimeException ex8 = ex6; try { RuntimeException e2 = ex8; if (!this.exceptionHandler.onRuntimeException(e2)) { continue; } this.stop(); } catch { this.state = AsynchronousTextGUIThread.State._STOPPED; Thread.MemoryBarrier(); this.waitLatch.countDown(); throw; } break; } goto IL_23C; IL_150: try { this.stop(); } catch { this.state = AsynchronousTextGUIThread.State._STOPPED; Thread.MemoryBarrier(); this.waitLatch.countDown(); throw; } IL_23C: this.state = AsynchronousTextGUIThread.State._STOPPED; Thread.MemoryBarrier(); this.waitLatch.countDown(); return; goto IL_CB; IL_4A: ex5 = ex; try { IOException e3 = ex5; this.exceptionHandler.onIOException(e3); } catch { this.state = AsynchronousTextGUIThread.State._STOPPED; Thread.MemoryBarrier(); this.waitLatch.countDown(); throw; } goto IL_CB; IL_4D: ex6 = ex2; try { RuntimeException e4 = ex6; this.exceptionHandler.onRuntimeException(e4); } catch { this.state = AsynchronousTextGUIThread.State._STOPPED; Thread.MemoryBarrier(); this.waitLatch.countDown(); throw; } goto IL_CB; } //[LineNumberTable(new byte[] { 159, 125, 98, 112, 162, 115 })] //[MethodImpl(MethodImplOptions.NoInlining)] public virtual void stop() { if (this.state != AsynchronousTextGUIThread.State._STARTED) { return; } this.state = AsynchronousTextGUIThread.State._STOPPING; Thread.MemoryBarrier(); } //[LineNumberTable(new byte[] { 159, 127, 162, 108, 115 })] //[MethodImpl(MethodImplOptions.NoInlining)] public virtual void start() { this.textGUIThread.start(); this.state = AsynchronousTextGUIThread.State._STARTED; Thread.MemoryBarrier(); } //[LineNumberTable(new byte[] { 159, 123, 130, 110 }), Throws(new string[] { "java.lang.InterruptedException" })] //[MethodImpl(MethodImplOptions.NoInlining)] public virtual void waitForStop() { this.waitLatch.await(); } //[LineNumberTable(83)] public virtual AsynchronousTextGUIThread.State getState() { return this.state; } //[LineNumberTable(88)] public override Thread getThread() { return this.textGUIThread; } //[LineNumberTable(new byte[] { 159, 119, 98, 112, 191, 50, 106 }), Throws(new string[] { "java.lang.IllegalStateException" })] //[MethodImpl(MethodImplOptions.NoInlining)] public override void invokeLater(Runnable runnable) { if (this.state != AsynchronousTextGUIThread.State._STARTED) { string arg_5C_0 = new StringBuilder().append("Cannot schedule ").append(runnable).append(" for execution on the TextGUIThread ").append("because the thread is in ").append(this.state).append(" state").toString(); //Throwable.__<suppressFillInStackTrace>(); throw new IllegalStateException(arg_5C_0); } base.invokeLater(runnable); } } }
using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using W = DocumentFormat.OpenXml.Wordprocessing; using D = DocumentFormat.OpenXml.Drawing; using S = DocumentFormat.OpenXml.Spreadsheet; using Signum.Engine.Templating; using Signum.Entities.DynamicQuery; using Signum.Utilities; using Signum.Utilities.DataStructures; using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Signum.Entities.Word; using System.Reflection; using Signum.Utilities.Reflection; namespace Signum.Engine.Word { public class WordTemplateParser : ITemplateParser { public List<TemplateError> Errors = new List<TemplateError>(); public QueryDescription QueryDescription { get; private set; } public ScopedDictionary<string, ValueProviderBase> Variables { get; private set; } = new ScopedDictionary<string, ValueProviderBase>(null); public Type? ModelType { get; private set; } OpenXmlPackage document; WordTemplateEntity template; public WordTemplateParser(OpenXmlPackage document, QueryDescription queryDescription, Type? modelType, WordTemplateEntity template) { this.QueryDescription = queryDescription; this.ModelType = modelType; this.document = document; this.template = template; } public void ParseDocument() { foreach (var part in document.AllParts().Where(p => p.RootElement != null)) { foreach (var item in part.RootElement.Descendants()) { if (item is W.Paragraph wp) ReplaceRuns(wp, new WordprocessingNodeProvider()); if (item is D.Paragraph dp) ReplaceRuns(dp, new DrawingNodeProvider()); if (item is S.SharedStringItem s) ReplaceRuns(s, new SpreadsheetNodeProvider()); } TableBinder.ValidateTables(part, this.template, this.Errors); } } private void ReplaceRuns(OpenXmlCompositeElement par, INodeProvider nodeProvider) { FixNakedText(par, nodeProvider); string text = par.ChildElements.Where(a => nodeProvider.IsRun(a)).ToString(r => nodeProvider.GetText(r), ""); var matches = TemplateUtils.KeywordsRegex.Matches(text).Cast<Match>().ToList(); if (matches.Any()) { List<ElementInfo> infos = GetElementInfos(par.ChildElements, nodeProvider); par.RemoveAllChildren(); var stack = new Stack<ElementInfo>(infos.AsEnumerable().Reverse()); foreach (var m in matches) { var interval = new Interval<int>(m.Index, m.Index + m.Length); // [Before][Start][Ignore][Ignore][End]...[Remaining] // [ Match ] ElementInfo start = stack.Pop(); //Start while (start.Interval.Max <= interval.Min) //Before { par.Append(start.Element); start = stack.Pop(); } var startRun = (OpenXmlCompositeElement)nodeProvider.CastRun(start.Element); if (start.Interval.Min < interval.Min) { var firstRunPart = nodeProvider.NewRun( (OpenXmlCompositeElement?)nodeProvider.GetRunProperties(startRun)?.CloneNode(true), start.Text!.Substring(0, m.Index - start.Interval.Min), SpaceProcessingModeValues.Preserve ); par.Append(firstRunPart); } par.Append(new MatchNode(nodeProvider, m) { RunProperties = (OpenXmlCompositeElement?)nodeProvider.GetRunProperties(startRun)?.CloneNode(true) }); ElementInfo end = start; while (end.Interval.Max < interval.Max) //Ignore end = stack.Pop(); if (interval.Max < end.Interval.Max) //End { var endRun = (OpenXmlCompositeElement)end.Element; var textPart = end.Text!.Substring(interval.Max - end.Interval.Min); var endRunPart = nodeProvider.NewRun( nodeProvider.GetRunProperties(startRun)?.Let(r => (OpenXmlCompositeElement)r.CloneNode(true)), textPart, SpaceProcessingModeValues.Preserve ); stack.Push(new ElementInfo(endRunPart, textPart) { Interval = new Interval<int>(interval.Max, end.Interval.Max) }); } } while (!stack.IsEmpty()) //Remaining { var pop = stack.Pop(); par.Append(pop.Element); } } } private void FixNakedText(OpenXmlCompositeElement par, INodeProvider nodeProvider) //Simple Spreadsheets cells { if (par.ChildElements.Count != 1) return; var only = par.ChildElements.Only(); if (!nodeProvider.IsText(only)) return; var text = nodeProvider.GetText(only!); if (!TemplateUtils.KeywordsRegex.IsMatch(text)) return; par.RemoveChild(only); par.AppendChild(nodeProvider.WrapInRun(only!)); } private static List<ElementInfo> GetElementInfos(IEnumerable<OpenXmlElement> childrens, INodeProvider nodeProvider) { var infos = childrens.Select(c => new ElementInfo(c, nodeProvider.IsRun(c) ? nodeProvider.GetText(c) : null)).ToList(); int currentPosition = 0; foreach (ElementInfo ri in infos) { ri.Interval = new Interval<int>(currentPosition, currentPosition + (ri.Text == null ? 0 : ri.Text.Length)); currentPosition = ri.Interval.Max; } return infos; } class ElementInfo { public readonly OpenXmlElement Element; public readonly string? Text; public Interval<int> Interval; public ElementInfo(OpenXmlElement element, string? text) { Element = element; Text = text; } public override string ToString() { return Interval + " " + Element.LocalName + (Text == null ? null : (": '" + Text + "'")); } } Stack<BlockContainerNode> stack = new Stack<BlockContainerNode>(); public void CreateNodes() { foreach (var root in document.AllRootElements()) { var lists = root.Descendants<MatchNode>().ToList(); foreach (var matchNode in lists) { var m = matchNode.Match; var expr = m.Groups["expr"].Value; var keyword = m.Groups["keyword"].Value; var variable = m.Groups["dec"].Value; switch (keyword) { case "": var s = TemplateUtils.SplitToken(expr); if (s == null) AddError(true, "{0} has invalid format".FormatWith(expr)); else { var vp = ValueProviderBase.TryParse(s.Value.Token, variable, this); matchNode.Parent.ReplaceChild(new TokenNode(matchNode.NodeProvider, vp!, s.Value.Format!) { RunProperties = (OpenXmlCompositeElement?)matchNode.RunProperties?.CloneNode(true) }, matchNode); DeclareVariable(vp); } break; case "declare": { var vp = ValueProviderBase.TryParse(expr, variable, this); matchNode.Parent.ReplaceChild(new DeclareNode(matchNode.NodeProvider, vp!, this.AddError) { RunProperties = (OpenXmlCompositeElement?)matchNode.RunProperties?.CloneNode(true) }, matchNode); DeclareVariable(vp); } break; case "any": { ConditionBase cond = TemplateUtils.ParseCondition(expr, variable, this); AnyNode any = new AnyNode(matchNode.NodeProvider, cond) { AnyToken = new MatchNodePair(matchNode) }; PushBlock(any); if (cond is ConditionCompare cc) DeclareVariable(cc.ValueProvider); break; } case "notany": { var an = PeekBlock<AnyNode>(); if (an != null) { an.NotAnyToken = new MatchNodePair(matchNode); } break; } case "endany": { var an = PopBlock<AnyNode>(); if (an != null) { an.EndAnyToken = new MatchNodePair(matchNode); an.ReplaceBlock(); } break; } case "if": { var cond = TemplateUtils.ParseCondition(expr, variable, this); IfNode ifn = new IfNode(matchNode.NodeProvider, cond) { IfToken = new MatchNodePair(matchNode) }; PushBlock(ifn); if (cond is ConditionCompare cc) DeclareVariable(cc.ValueProvider); break; } case "else": { var an = PeekBlock<IfNode>(); if (an != null) { an.ElseToken = new MatchNodePair(matchNode); } break; } case "endif": { var ifn = PopBlock<IfNode>(); if (ifn != null) { ifn.EndIfToken = new MatchNodePair(matchNode); ifn.ReplaceBlock(); } break; } case "foreach": { var vp = ValueProviderBase.TryParse(expr, variable, this); if (vp is TokenValueProvider tvp && tvp.ParsedToken.QueryToken != null && QueryToken.IsCollection(tvp.ParsedToken.QueryToken.Type)) AddError(false, $"@foreach[{expr}] is a collection, missing 'Element' token at the end"); var fn = new ForeachNode(matchNode.NodeProvider, vp!) { ForeachToken = new MatchNodePair(matchNode) }; PushBlock(fn); DeclareVariable(vp); break; } case "endforeach": { var fn = PopBlock<ForeachNode>(); if (fn != null) { fn.EndForeachToken = new MatchNodePair(matchNode); fn.ReplaceBlock(); } break; } default: AddError(true, "'{0}' is deprecated".FormatWith(keyword)); break; } } } } void PushBlock(BlockContainerNode node) { stack.Push(node); Variables = new ScopedDictionary<string, ValueProviderBase>(Variables); } T? PopBlock<T>() where T : BlockContainerNode { if (stack.IsEmpty()) { AddError(true, "No {0} has been opened".FormatWith(BlockContainerNode.UserString(typeof(T)))); return null; } BlockContainerNode n = stack.Pop(); if (n == null || !(n is T)) { AddError(true, "Unexpected '{0}'".FormatWith(BlockContainerNode.UserString(n?.GetType()))); return null; } Variables = Variables.Previous!; return (T)n; } T? PeekBlock<T>() where T : BlockContainerNode { if (stack.IsEmpty()) { AddError(true, "No {0} has been opened".FormatWith(BlockContainerNode.UserString(typeof(T)))); return null; } BlockContainerNode n = stack.Peek(); if (n == null || !(n is T)) { AddError(true, "Unexpected '{0}'".FormatWith(BlockContainerNode.UserString(n?.GetType()))); return null; } Variables = Variables.Previous!; Variables = new ScopedDictionary<string, ValueProviderBase>(Variables); return (T)n; } public void AddError(bool fatal, string message) { this.Errors.Add(new TemplateError(fatal, message)); } void DeclareVariable(ValueProviderBase? token) { if (token?.Variable.HasText() == true) { if (Variables.TryGetValue(token!.Variable!, out ValueProviderBase? t)) { if (!t.Equals(token)) AddError(true, "There is already a variable '{0}' defined in this scope".FormatWith(token.Variable)); } else { Variables.Add(token!.Variable!, token); } } } public void AssertClean() { foreach (var root in this.document.AllRootElements()) { var list = root.Descendants<MatchNode>().ToList(); if (list.Any()) throw new InvalidOperationException("{0} unexpected MatchNode instances found: \r\n{1}".FormatWith(list.Count, list.ToString(d => @$"{d.Before()?.InnerText ?? "- None - "} {d.InnerText} <-- Unexpected {d.After()?.InnerText ?? "-- None --"}", "\r\n\r\n").Indent(2))); } } } static class OpenXmlExtensions { public static OpenXmlElement? Before(this OpenXmlElement element) { return element.Follow(a => a.Parent).Select(p => p.PreviousSibling()).FirstOrDefault(e => e != null && e.InnerText.HasText()); } public static OpenXmlElement? After(this OpenXmlElement element) { return element.Follow(a => a.Parent).Select(p => p.NextSibling()).FirstOrDefault(e => e != null && e.InnerText.HasText()); } } }
// Copyright 2016 MaterialUI for Unity http://materialunity.com // Please see license file for terms and conditions of use, and more information. using UnityEngine; using UnityEditor; using UnityEngine.UI; using Object = UnityEngine.Object; namespace MaterialUI { [ExecuteInEditMode] public static class MaterialUIEditorTools { private static GameObject m_LastInstance; private static GameObject m_SelectedObject; private static bool m_NotCanvas; #region GeneralCreationMethods public static void CreateInstance(string assetPath, string objectName, params int[] instantiationOptions) { m_LastInstance = Object.Instantiate(AssetDatabase.LoadAssetAtPath("Assets/MaterialUI/Prefabs/" + assetPath + ".prefab", typeof(GameObject))) as GameObject; m_LastInstance.name = objectName; CreateCanvasIfNeeded(); m_LastInstance.transform.SetParent(m_SelectedObject.transform); m_LastInstance.GetComponent<RectTransform>().anchoredPosition = Vector2.zero; m_LastInstance.GetComponent<RectTransform>().localScale = new Vector3(1f, 1f, 1f); Selection.activeObject = m_LastInstance; if (instantiationOptions.Length > 0) { GameObject savedLastInstance = m_LastInstance; InstantiationHelper instantiationHelper = m_LastInstance.GetComponent<InstantiationHelper>(); if (instantiationHelper == null) { instantiationHelper = m_LastInstance.GetComponentInChildren<InstantiationHelper>(); m_LastInstance = instantiationHelper.gameObject; Selection.activeObject = m_LastInstance; } instantiationHelper.HelpInstantiate(instantiationOptions); if (savedLastInstance != null) { Selection.activeObject = savedLastInstance; } } Undo.RegisterCreatedObjectUndo(m_LastInstance, "create " + m_LastInstance.name); } private static void CreateCanvasIfNeeded() { if (Selection.activeObject != null && Selection.activeObject.GetType() == (typeof(GameObject))) { m_SelectedObject = (GameObject)Selection.activeObject; } if (m_SelectedObject) { if (GameObject.Find(m_SelectedObject.name)) { m_NotCanvas = m_SelectedObject.GetComponentInParent<Canvas>() == null; } else { m_NotCanvas = true; } } else { m_NotCanvas = true; } if (m_NotCanvas) { if (!Object.FindObjectOfType<UnityEngine.EventSystems.EventSystem>()) { Object.Instantiate(AssetDatabase.LoadAssetAtPath("Assets/MaterialUI/Prefabs/Common/EventSystem.prefab", typeof(GameObject))).name = "EventSystem"; } Canvas[] canvases = Object.FindObjectsOfType<Canvas>(); for (int i = 0; i < canvases.Length; i++) { if (canvases[i].isRootCanvas) { m_SelectedObject = canvases[i].gameObject; } } if (!m_SelectedObject) { m_SelectedObject = Object.Instantiate(AssetDatabase.LoadAssetAtPath("Assets/MaterialUI/Prefabs/Common/Canvas.prefab", typeof(GameObject))) as GameObject; m_SelectedObject.name = "Canvas"; } } } #endregion #region CreateObjects [MenuItem("GameObject/MaterialUI/Empty Object/Self Sized/No Layout", false, 000)] private static void CreateEmptyObjectSelfSizedNoLayout() { CreateInstance("Components/Empty Object", "Empty Object", InstantiationHelper.optionNone); } [MenuItem("GameObject/MaterialUI/Empty Object/Self Sized/Horizontal Layout", false, 000)] private static void CreateEmptyObjectSelfSizedHorizontalLayout() { CreateInstance("Components/Empty Object", "Empty Object", EmptyUIObjectInstantiationHelper.optionHasLayoutHorizontal); } [MenuItem("GameObject/MaterialUI/Empty Object/Self Sized/Vertical Layout", false, 000)] private static void CreateEmptyObjectSelfSizedVerticalLayout() { CreateInstance("Components/Empty Object", "Empty Object", EmptyUIObjectInstantiationHelper.optionHasLayoutVertical); } [MenuItem("GameObject/MaterialUI/Empty Object/Stretched/No Layout", false, 000)] private static void CreateEmptyObjectStretchedNoLayout() { CreateInstance("Components/Empty Object", "Empty Object", EmptyUIObjectInstantiationHelper.optionStretched); } [MenuItem("GameObject/MaterialUI/Empty Object/Stretched/Horizontal Layout", false, 000)] private static void CreateEmptyObjectStretchedHorizontalLayout() { CreateInstance("Components/Empty Object", "Empty Object", EmptyUIObjectInstantiationHelper.optionStretched, EmptyUIObjectInstantiationHelper.optionHasLayoutHorizontal); } [MenuItem("GameObject/MaterialUI/Empty Object/Stretched/Vertical Layout", false, 000)] private static void CreateEmptyObjectStretchedVerticalLayout() { CreateInstance("Components/Empty Object", "Empty Object", EmptyUIObjectInstantiationHelper.optionStretched, EmptyUIObjectInstantiationHelper.optionHasLayoutVertical); } [MenuItem("GameObject/MaterialUI/Empty Object/Fitted/Horizontal Layout", false, 000)] private static void CreateEmptyObjectFittedHorizontalLayout() { CreateInstance("Components/Empty Object", "Empty Object", EmptyUIObjectInstantiationHelper.optionFitted, EmptyUIObjectInstantiationHelper.optionHasLayoutHorizontal); } [MenuItem("GameObject/MaterialUI/Empty Object/Fitted/Vertical Layout", false, 000)] private static void CreateEmptyObjectFittedVerticalLayout() { CreateInstance("Components/Empty Object", "Empty Object", EmptyUIObjectInstantiationHelper.optionFitted, EmptyUIObjectInstantiationHelper.optionHasLayoutVertical); } [MenuItem("GameObject/MaterialUI/Panel/Self Sized/No Layout", false, 005)] private static void CreatePanelSelfSizedNoLayout() { CreateInstance("Components/Panel", "Panel", InstantiationHelper.optionNone); } [MenuItem("GameObject/MaterialUI/Panel/Self Sized/Horizontal Layout", false, 001)] private static void CreatePanelSelfSizedHorizontalLayout() { CreateInstance("Components/Panel", "Panel", PanelInstantiationHelper.optionHasLayoutHorizontal); } [MenuItem("GameObject/MaterialUI/Panel/Self Sized/Vertical Layout", false, 001)] private static void CreatePanelSelfSizedVerticalLayout() { CreateInstance("Components/Panel", "Panel", PanelInstantiationHelper.optionHasLayoutVertical); } [MenuItem("GameObject/MaterialUI/Panel/Stretched/No Layout", false, 001)] private static void CreatePanelStretchedNoLayout() { CreateInstance("Components/Panel", "Panel", PanelInstantiationHelper.optionStretched); } [MenuItem("GameObject/MaterialUI/Panel/Stretched/Horizontal Layout", false, 001)] private static void CreatePanelStretchedHorizontalLayout() { CreateInstance("Components/Panel", "Panel", PanelInstantiationHelper.optionStretched, PanelInstantiationHelper.optionHasLayoutHorizontal); } [MenuItem("GameObject/MaterialUI/Panel/Stretched/Vertical Layout", false, 001)] private static void CreatePanelStretchedVerticalLayout() { CreateInstance("Components/Panel", "Panel", PanelInstantiationHelper.optionStretched, PanelInstantiationHelper.optionHasLayoutVertical); } [MenuItem("GameObject/MaterialUI/Panel/Fitted/Horizontal Layout", false, 001)] private static void CreatePanelFittedHorizontalLayout() { CreateInstance("Components/Panel", "Panel", PanelInstantiationHelper.optionFitted, PanelInstantiationHelper.optionHasLayoutHorizontal); } [MenuItem("GameObject/MaterialUI/Panel/Fitted/Vertical Layout", false, 001)] private static void CreatePanelFittedVerticalLayout() { CreateInstance("Components/Panel", "Panel", PanelInstantiationHelper.optionFitted, PanelInstantiationHelper.optionHasLayoutVertical); } [MenuItem("GameObject/MaterialUI/Background Image", false, 010)] private static void CreateBackgroundImage() { CreateInstance("Components/Background Image", "Background Image"); m_LastInstance.GetComponent<RectTransform>().sizeDelta = Vector2.zero; } [MenuItem("GameObject/MaterialUI/Image", false, 010)] private static void CreateImage() { CreateInstance("Components/Image", "Image"); } [MenuItem("GameObject/MaterialUI/Raw Image", false, 010)] private static void CreateRawImage() { CreateInstance("Components/Raw Image", "Raw Image"); } //[MenuItem("GameObject/MaterialUI/Shadow", false, 011)] private static void CreateShadow() { CreateInstance("Components/Shadow", "Shadow"); } [MenuItem("GameObject/MaterialUI/Vector Image", false, 014)] private static void CreateVectorImage() { CreateInstance("Components/VectorImage", "Icon"); } [MenuItem("GameObject/MaterialUI/Text", false, 020)] private static void CreateText() { CreateInstance("Components/Text", "Text"); } [MenuItem("GameObject/MaterialUI/Buttons/Text/Flat", false, 030)] private static void CreateButtonFlat() { CreateInstance("Components/Buttons/Button", "Button - Flat", InstantiationHelper.optionNone); } [MenuItem("GameObject/MaterialUI/Buttons/Text/Raised", false, 030)] private static void CreateButtonRaised() { CreateInstance("Components/Buttons/Button", "Button - Raised", ButtonRectInstantiationHelper.optionRaised); } [MenuItem("GameObject/MaterialUI/Buttons/Multi Content/Flat", false, 030)] private static void CreateButtonMultiFlat() { CreateInstance("Components/Buttons/Button", "Button - Flat", ButtonRectInstantiationHelper.optionHasContent); } [MenuItem("GameObject/MaterialUI/Buttons/Multi Content/Raised", false, 030)] private static void CreateButtonMultiRaised() { CreateInstance("Components/Buttons/Button", "Button - Raised", ButtonRectInstantiationHelper.optionHasContent, ButtonRectInstantiationHelper.optionRaised); } [MenuItem("GameObject/MaterialUI/Buttons/Floating Action Button/Raised", false, 030)] private static void CreateFloatingActionButtonRaised() { CreateInstance("Components/Buttons/Floating Action Button", "Floating Action Button - Raised", ButtonRoundInstantiationHelper.optionRaised); } [MenuItem("GameObject/MaterialUI/Buttons/Floating Action Button/Mini Raised", false, 030)] private static void CreateMiniFloatingActionButtonRaised() { CreateInstance("Components/Buttons/Floating Action Button", "Floating Action Button Mini - Raised", ButtonRoundInstantiationHelper.optionMini, ButtonRoundInstantiationHelper.optionRaised); } [MenuItem("GameObject/MaterialUI/Buttons/Icon Button/Normal", false, 030)] private static void CreateIconButton() { CreateInstance("Components/Buttons/Floating Action Button", "Icon Button - Flat", InstantiationHelper.optionNone); } [MenuItem("GameObject/MaterialUI/Buttons/Icon Button/Mini", false, 030)] private static void CreateMiniIconButton() { CreateInstance("Components/Buttons/Floating Action Button", "Icon Button Mini - Flat", ButtonRoundInstantiationHelper.optionMini); } [MenuItem("GameObject/MaterialUI/Dropdowns/Flat", false, 030)] private static void CreateDropdownFlat() { CreateInstance("Components/Buttons/Button", "Dropdown - Flat", ButtonRectInstantiationHelper.optionHasDropdown, ButtonRectInstantiationHelper.optionHasContent); } [MenuItem("GameObject/MaterialUI/Dropdowns/Raised", false, 030)] private static void CreateDropdownRaised() { CreateInstance("Components/Buttons/Button", "Dropdown - Raised", ButtonRectInstantiationHelper.optionHasDropdown, ButtonRectInstantiationHelper.optionHasContent, ButtonRectInstantiationHelper.optionRaised); } [MenuItem("GameObject/MaterialUI/Dropdowns/Icon Button", false, 030)] private static void CreateIconDropdown() { CreateInstance("Components/Buttons/Floating Action Button", "Dropdown Icon Button", ButtonRoundInstantiationHelper.optionHasDropdown); } [MenuItem("GameObject/MaterialUI/Dropdowns/Mini Icon Button", false, 030)] private static void CreateMiniIconDropdown() { CreateInstance("Components/Buttons/Floating Action Button", "Dropdown Mini Icon Button", ButtonRoundInstantiationHelper.optionHasDropdown, ButtonRoundInstantiationHelper.optionMini); } [MenuItem("GameObject/MaterialUI/Toggles/Checkboxes/Label", false, 040)] private static void CreateCheckboxText() { CreateInstance("Components/Checkbox", "Checkbox", ToggleInstantiationHelper.optionLabel); } [MenuItem("GameObject/MaterialUI/Toggles/Checkboxes/Icon", false, 040)] private static void CreateCheckboxIcon() { CreateInstance("Components/Checkbox", "Checkbox", ToggleInstantiationHelper.optionHasIcon); } [MenuItem("GameObject/MaterialUI/Toggles/Switches/Label", false, 050)] private static void CreateSwitchLabel() { CreateInstance("Components/Switch", "Switch", ToggleInstantiationHelper.optionLabel); } [MenuItem("GameObject/MaterialUI/Toggles/Switches/Icon", false, 050)] private static void CreateSwitchIcon() { CreateInstance("Components/Switch", "Switch", ToggleInstantiationHelper.optionHasIcon); } [MenuItem("GameObject/MaterialUI/Toggles/Radio Buttons/Label", false, 060)] private static void CreateRadioButtonsLabel() { CreateInstance("Components/RadioGroup", "Radio Buttons", ToggleInstantiationHelper.optionLabel); } [MenuItem("GameObject/MaterialUI/Toggles/Radio Buttons/Icon", false, 060)] private static void CreateRadioButtonsIcon() { CreateInstance("Components/RadioGroup", "Radio Buttons", ToggleInstantiationHelper.optionHasIcon); } [MenuItem("GameObject/MaterialUI/Input Fields/Basic", false, 070)] private static void CreateSimpleInputFieldBasic() { CreateInstance("Components/Input Field", "Input Field", InstantiationHelper.optionNone); } [MenuItem("GameObject/MaterialUI/Input Fields/Basic - With Icon", false, 070)] private static void CreateSimpleInputFieldIcon() { CreateInstance("Components/Input Field", "Input Field", InputFieldInstantiationHelper.optionHasIcon); } [MenuItem("GameObject/MaterialUI/Input Fields/Basic - With Clear Button", false, 070)] private static void CreateSimpleInputFieldClearButton() { CreateInstance("Components/Input Field", "Input Field", InputFieldInstantiationHelper.optionHasClearButton); } [MenuItem("GameObject/MaterialUI/Input Fields/Basic - With Icon and Clear Button", false, 070)] private static void CreateSimpleInputFieldIconClearButton() { CreateInstance("Components/Input Field", "Input Field", InputFieldInstantiationHelper.optionHasIcon, InputFieldInstantiationHelper.optionHasClearButton); } [MenuItem("GameObject/MaterialUI/Sliders/Continuous/Simple", false, 080)] private static void CreateSliderContinuousSimple() { CreateInstance("Components/Slider", "Slider - Simple", InstantiationHelper.optionNone); } [MenuItem("GameObject/MaterialUI/Sliders/Continuous/Left label", false, 080)] private static void CreateSliderContinuousLabel() { CreateInstance("Components/Slider", "Slider - Left Label", MaterialSliderInstantiationHelper.optionHasLabel); } [MenuItem("GameObject/MaterialUI/Sliders/Continuous/Left icon", false, 080)] private static void CreateSliderContinuousIcon() { CreateInstance("Components/Slider", "Slider - Left icon", MaterialSliderInstantiationHelper.optionHasIcon); } [MenuItem("GameObject/MaterialUI/Sliders/Continuous/Left and Right labels", false, 080)] private static void CreateSliderContinuousLabels() { CreateInstance("Components/Slider", "Slider - Left and Right labels", MaterialSliderInstantiationHelper.optionHasLabel, MaterialSliderInstantiationHelper.optionHasTextField); } [MenuItem("GameObject/MaterialUI/Sliders/Continuous/Left label and Right inputField", false, 080)] private static void CreateSliderContinuousLabelInputField() { CreateInstance("Components/Slider", "Slider - Left label and Right inputField", MaterialSliderInstantiationHelper.optionHasLabel, MaterialSliderInstantiationHelper.optionHasInputField); } [MenuItem("GameObject/MaterialUI/Sliders/Continuous/Left icon and Right inputField", false, 080)] private static void CreateSliderContinuousIconInputField() { CreateInstance("Components/Slider", "Slider - Left icon and Right inputField", MaterialSliderInstantiationHelper.optionHasIcon, MaterialSliderInstantiationHelper.optionHasInputField); } [MenuItem("GameObject/MaterialUI/Sliders/Discrete/Simple", false, 080)] private static void CreateSliderDiscreteSimple() { CreateInstance("Components/Slider", "Slider - Simple", MaterialSliderInstantiationHelper.optionDiscrete); } [MenuItem("GameObject/MaterialUI/Sliders/Discrete/Left label", false, 080)] private static void CreateSliderDiscreteLabel() { CreateInstance("Components/Slider", "Slider - Left Label", MaterialSliderInstantiationHelper.optionDiscrete, MaterialSliderInstantiationHelper.optionHasLabel); } [MenuItem("GameObject/MaterialUI/Sliders/Discrete/Left icon", false, 080)] private static void CreateSliderDiscreteIcon() { CreateInstance("Components/Slider", "Slider - Left icon", MaterialSliderInstantiationHelper.optionDiscrete, MaterialSliderInstantiationHelper.optionHasIcon); } [MenuItem("GameObject/MaterialUI/Sliders/Discrete/Left and Right labels", false, 080)] private static void CreateSliderDiscreteLabels() { CreateInstance("Components/Slider", "Slider - Left and Right labels", MaterialSliderInstantiationHelper.optionDiscrete, MaterialSliderInstantiationHelper.optionHasLabel, MaterialSliderInstantiationHelper.optionHasTextField); } [MenuItem("GameObject/MaterialUI/Sliders/Discrete/Left label and Right inputField", false, 080)] private static void CreateSliderDiscreteLabelInputField() { CreateInstance("Components/Slider", "Slider - Left label and Right inputField", MaterialSliderInstantiationHelper.optionDiscrete, MaterialSliderInstantiationHelper.optionHasLabel, MaterialSliderInstantiationHelper.optionHasInputField); } [MenuItem("GameObject/MaterialUI/Sliders/Discrete/Left icon and Right inputField", false, 080)] private static void CreateSliderDiscreteIconInputField() { CreateInstance("Components/Slider", "Slider - Left icon and Right inputField", MaterialSliderInstantiationHelper.optionDiscrete, MaterialSliderInstantiationHelper.optionHasIcon, MaterialSliderInstantiationHelper.optionHasInputField); } [MenuItem("GameObject/MaterialUI/Progress Indicators/Simple/Circle - Flat", false, 082)] private static void CreateProgressCircleFlat() { CreateInstance("Resources/Progress Indicators/Circle Progress Indicator", "Circle Progress Indicator - Flat", InstantiationHelper.optionNone); } [MenuItem("GameObject/MaterialUI/Progress Indicators/Simple/Circle - Raised", false, 082)] private static void CreateProgressCircleRaised() { CreateInstance("Resources/Progress Indicators/Circle Progress Indicator", "Circle Progress Indicator - Raised", CircleProgressIndicatorInstantiationHelper.optionRaised); } [MenuItem("GameObject/MaterialUI/Progress Indicators/Simple/Linear", false, 082)] private static void CreateProgressLinear() { CreateInstance("Resources/Progress Indicators/Linear Progress Indicator", "Linear Progress Indicator"); } [MenuItem("GameObject/MaterialUI/Progress Indicators/With label/Horizontal/Circle - Flat", false, 082)] private static void CreateProgressLabelCircleFlatHorizontal() { CreateInstance("Resources/Progress Indicators/Circle Progress Indicator", "Circle Progress Indicator - Flat", CircleProgressIndicatorInstantiationHelper.optionHasLabel, CircleProgressIndicatorInstantiationHelper.optionLayoutHorizontal); } [MenuItem("GameObject/MaterialUI/Progress Indicators/With label/Horizontal/Circle - Raised", false, 082)] private static void CreateProgressLabelCircleRaisedHorizontal() { CreateInstance("Resources/Progress Indicators/Circle Progress Indicator", "Circle Progress Indicator - Raised", CircleProgressIndicatorInstantiationHelper.optionRaised, CircleProgressIndicatorInstantiationHelper.optionHasLabel, CircleProgressIndicatorInstantiationHelper.optionLayoutHorizontal); } [MenuItem("GameObject/MaterialUI/Progress Indicators/With label/Vertical/Circle - Flat", false, 082)] private static void CreateProgressLabelCircleFlatVertical() { CreateInstance("Resources/Progress Indicators/Circle Progress Indicator", "Circle Progress Indicator - Flat", CircleProgressIndicatorInstantiationHelper.optionHasLabel, CircleProgressIndicatorInstantiationHelper.optionLayoutVertical); } [MenuItem("GameObject/MaterialUI/Progress Indicators/With label/Vertical/Circle - Raised", false, 082)] private static void CreateProgressLabelCircleRaisedVertical() { CreateInstance("Resources/Progress Indicators/Circle Progress Indicator", "Circle Progress Indicator - Flat", CircleProgressIndicatorInstantiationHelper.optionRaised, CircleProgressIndicatorInstantiationHelper.optionHasLabel, CircleProgressIndicatorInstantiationHelper.optionLayoutVertical); } [MenuItem("GameObject/MaterialUI/Dividers/Horizontal Light", false, 120)] private static void CreateDividerHorizontalLight() { CreateInstance("Components/Divider", "Divider - Horizontal Light", DividerInstantiationHelper.optionLight); } [MenuItem("GameObject/MaterialUI/Dividers/Horizontal Dark", false, 120)] private static void CreateDividerHorizontalDark() { CreateInstance("Components/Divider", "Divider - Horizontal Dark", InstantiationHelper.optionNone); } [MenuItem("GameObject/MaterialUI/Dividers/Vertical Light", false, 120)] private static void CreateDividerVerticalLight() { CreateInstance("Components/Divider", "Divider - Vertical Light", DividerInstantiationHelper.optionLight, DividerInstantiationHelper.optionVertical); } [MenuItem("GameObject/MaterialUI/Dividers/Vertical Dark", false, 120)] private static void CreateDividerVerticalDark() { CreateInstance("Components/Divider", "Divider - Vertical Dark", DividerInstantiationHelper.optionVertical); } [MenuItem("GameObject/MaterialUI/Nav Drawer", false, 200)] private static void CreateNavDrawer() { CreateInstance("Components/Nav Drawer", "Nav Drawer"); m_LastInstance.GetComponent<RectTransform>().sizeDelta = new Vector2(m_LastInstance.GetComponent<RectTransform>().sizeDelta.x, 8f); m_LastInstance.GetComponent<RectTransform>().anchoredPosition = new Vector2(-m_LastInstance.GetComponent<RectTransform>().sizeDelta.x / 2f, 0f); } [MenuItem("GameObject/MaterialUI/App Bar", false, 210)] private static void CreateAppBar() { CreateInstance("Components/App Bar", "App Bar"); m_LastInstance.GetComponent<RectTransform>().sizeDelta = Vector2.zero; m_LastInstance.GetComponent<RectTransform>().anchoredPosition = Vector2.zero; } [MenuItem("GameObject/MaterialUI/Tab View/Icon", false, 210)] private static void CreateTabViewIcon() { CreateInstance("Components/TabView", "Tab View", TabViewInstantiationHelper.optionHasIcon); } [MenuItem("GameObject/MaterialUI/Tab View/Text", false, 210)] private static void CreateTabViewText() { CreateInstance("Components/TabView", "Tab View", TabViewInstantiationHelper.optionHasLabel); } [MenuItem("GameObject/MaterialUI/Tab View/Icon and Text", false, 210)] private static void CreateTabView() { CreateInstance("Components/TabView", "Tab View", TabViewInstantiationHelper.optionHasIcon, TabViewInstantiationHelper.optionHasLabel); } [MenuItem("GameObject/MaterialUI/Screens/Screen View", false, 220)] private static void CreateScreenView() { CreateInstance("Components/ScreenView", "Screen View"); m_LastInstance.GetComponent<RectTransform>().sizeDelta = Vector2.zero; m_LastInstance.GetComponent<RectTransform>().anchoredPosition = Vector2.zero; } [MenuItem("GameObject/MaterialUI/Screens/Screen", false, 220)] private static void CreateScreen() { CreateInstance("Components/Screen", "Screen"); m_LastInstance.GetComponent<RectTransform>().sizeDelta = Vector2.zero; m_LastInstance.GetComponent<RectTransform>().anchoredPosition = Vector2.zero; } [MenuItem("GameObject/MaterialUI/Managers/Toast Manager", false, 1000)] private static void CreateToastManager() { CreateInstance("Managers/ToastManager", "Toast Manager"); m_LastInstance.GetComponent<RectTransform>().sizeDelta = Vector2.zero; m_LastInstance.GetComponent<RectTransform>().anchoredPosition = Vector2.zero; } [MenuItem("GameObject/MaterialUI/Managers/Snackbar Manager", false, 1000)] private static void CreateSnackbarManager() { CreateInstance("Managers/SnackbarManager", "Snackbar Manager"); m_LastInstance.GetComponent<RectTransform>().sizeDelta = Vector2.zero; m_LastInstance.GetComponent<RectTransform>().anchoredPosition = Vector2.zero; } [MenuItem("GameObject/MaterialUI/Managers/Dialog Manager", false, 1000)] private static void CreateDialogManager() { CreateInstance("Managers/DialogManager", "Dialog Manager"); m_LastInstance.GetComponent<RectTransform>().sizeDelta = Vector2.zero; m_LastInstance.GetComponent<RectTransform>().anchoredPosition = Vector2.zero; } #endregion #region GeneralMenuItems [MenuItem("Help/MaterialUI/Website", false, 200)] private static void Wiki() { Application.OpenURL("https://materialunity.com"); } [MenuItem("Help/MaterialUI/Feedback - Bug Report - Feature Request", false, 200)] private static void Feedback() { Application.OpenURL("http://materialunity.com/support"); } [MenuItem("Help/MaterialUI/Current Version: v" + MaterialUIVersion.currentVersion, true, 200)] private static bool AboutValidate() { return false; } [MenuItem("Help/MaterialUI/Current Version: v" + MaterialUIVersion.currentVersion, false, 200)] private static void About() { } #endregion #region Tools [MenuItem("GameObject/MaterialUI/Tools/Attach and Setup Shadow", true, 3000)] public static bool CheckAttachAndSetupShadow() { if (Selection.activeGameObject != null) { return true; } return false; } [MenuItem("GameObject/MaterialUI/Tools/Attach and Setup Shadow", false, 3000)] public static void AttachAndSetupShadow() { GameObject sourceGameObject = Selection.activeGameObject; Undo.RecordObject(sourceGameObject, sourceGameObject.name); RectTransform sourceRectTransform = sourceGameObject.GetComponent<RectTransform>(); Vector3 sourcePos = sourceRectTransform.position; Vector2 sourceSize = sourceRectTransform.sizeDelta; Vector2 sourceLayoutSize = sourceRectTransform.GetProperSize(); Image sourceImage = sourceGameObject.GetAddComponent<Image>(); CreateShadow(); GameObject shadowGameObject = Selection.activeGameObject; shadowGameObject.name = sourceGameObject.name + " Shadow"; ShadowGenerator shadowGenerator = shadowGameObject.GetAddComponent<ShadowGenerator>(); shadowGenerator.sourceImage = sourceImage; RectTransform shadowTransform = shadowGameObject.GetAddComponent<RectTransform>(); shadowTransform.anchorMin = sourceRectTransform.anchorMin; shadowTransform.anchorMax = sourceRectTransform.anchorMax; shadowTransform.pivot = sourceRectTransform.pivot; bool probablyHasLayout = (sourceGameObject.GetComponent<LayoutGroup>() != null || sourceGameObject.GetComponent<LayoutElement>() != null); GameObject newParentGameObject = new GameObject(sourceGameObject.name); newParentGameObject.transform.SetParent(sourceRectTransform.parent); RectTransform newParentRectTransform = newParentGameObject.GetAddComponent<RectTransform>(); newParentRectTransform.SetSiblingIndex(sourceRectTransform.GetSiblingIndex()); newParentRectTransform.anchorMin = sourceRectTransform.anchorMin; newParentRectTransform.anchorMax = sourceRectTransform.anchorMax; newParentRectTransform.pivot = sourceRectTransform.pivot; newParentRectTransform.position = sourcePos; newParentRectTransform.sizeDelta = sourceSize; LayoutElement layoutElement = null; if (probablyHasLayout) { layoutElement = newParentGameObject.AddComponent<LayoutElement>(); layoutElement.preferredWidth = sourceLayoutSize.x; layoutElement.preferredHeight = sourceLayoutSize.y; } shadowGameObject.GetComponent<RectTransform>().SetParent(newParentRectTransform, true); sourceRectTransform.SetParent(newParentRectTransform, true); sourceGameObject.name = sourceGameObject.name + " Image"; if (probablyHasLayout) { layoutElement.CalculateLayoutInputHorizontal(); layoutElement.CalculateLayoutInputVertical(); } shadowGenerator.GenerateShadowFromImage(); Selection.activeObject = newParentGameObject; Undo.RegisterCreatedObjectUndo(shadowGameObject, shadowGameObject.name); Undo.RegisterCreatedObjectUndo(newParentGameObject, newParentGameObject.name); } #endregion } }
using Lucene.Net.Documents; using NUnit.Framework; using System; using System.Diagnostics; using System.Runtime.CompilerServices; using Assert = Lucene.Net.TestFramework.Assert; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AttributeSource = Lucene.Net.Util.AttributeSource; using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; using DirectoryReader = Lucene.Net.Index.DirectoryReader; using Document = Documents.Document; using Field = Field; using IndexReader = Lucene.Net.Index.IndexReader; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using MultiReader = Lucene.Net.Index.MultiReader; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using Term = Lucene.Net.Index.Term; using Terms = Lucene.Net.Index.Terms; using TermsEnum = Lucene.Net.Index.TermsEnum; [TestFixture] public class TestMultiTermQueryRewrites : LuceneTestCase { private static Directory dir, sdir1, sdir2; private static IndexReader reader, multiReader, multiReaderDupls; private static IndexSearcher searcher, multiSearcher, multiSearcherDupls; /// <summary> /// LUCENENET specific /// Is non-static because Similarity and TimeZone are not static. /// </summary> [OneTimeSetUp] public override void BeforeClass() { base.BeforeClass(); dir = NewDirectory(); sdir1 = NewDirectory(); sdir2 = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir, new MockAnalyzer(Random)); RandomIndexWriter swriter1 = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, sdir1, new MockAnalyzer(Random)); RandomIndexWriter swriter2 = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, sdir2, new MockAnalyzer(Random)); for (int i = 0; i < 10; i++) { Document doc = new Document(); doc.Add(NewStringField("data", Convert.ToString(i), Field.Store.NO)); writer.AddDocument(doc); ((i % 2 == 0) ? swriter1 : swriter2).AddDocument(doc); } writer.ForceMerge(1); swriter1.ForceMerge(1); swriter2.ForceMerge(1); writer.Dispose(); swriter1.Dispose(); swriter2.Dispose(); reader = DirectoryReader.Open(dir); searcher = NewSearcher(reader); multiReader = new MultiReader(new IndexReader[] { DirectoryReader.Open(sdir1), DirectoryReader.Open(sdir2) }, true); multiSearcher = NewSearcher(multiReader); multiReaderDupls = new MultiReader(new IndexReader[] { DirectoryReader.Open(sdir1), DirectoryReader.Open(dir) }, true); multiSearcherDupls = NewSearcher(multiReaderDupls); } [OneTimeTearDown] public override void AfterClass() { reader.Dispose(); multiReader.Dispose(); multiReaderDupls.Dispose(); dir.Dispose(); sdir1.Dispose(); sdir2.Dispose(); reader = multiReader = multiReaderDupls = null; searcher = multiSearcher = multiSearcherDupls = null; dir = sdir1 = sdir2 = null; base.AfterClass(); } private Query ExtractInnerQuery(Query q) { if (q is ConstantScoreQuery) { // wrapped as ConstantScoreQuery q = ((ConstantScoreQuery)q).Query; } return q; } private Term ExtractTerm(Query q) { q = ExtractInnerQuery(q); return ((TermQuery)q).Term; } private void CheckBooleanQueryOrder(Query q) { q = ExtractInnerQuery(q); BooleanQuery bq = (BooleanQuery)q; Term last = null, act; foreach (BooleanClause clause in bq.Clauses) { act = ExtractTerm(clause.Query); if (last != null) { Assert.IsTrue(last.CompareTo(act) < 0, "sort order of terms in BQ violated"); } last = act; } } private void CheckDuplicateTerms(MultiTermQuery.RewriteMethod method) { MultiTermQuery mtq = TermRangeQuery.NewStringRange("data", "2", "7", true, true); mtq.MultiTermRewriteMethod = (method); Query q1 = searcher.Rewrite(mtq); Query q2 = multiSearcher.Rewrite(mtq); Query q3 = multiSearcherDupls.Rewrite(mtq); if (Verbose) { Console.WriteLine(); Console.WriteLine("single segment: " + q1); Console.WriteLine("multi segment: " + q2); Console.WriteLine("multi segment with duplicates: " + q3); } Assert.IsTrue(q1.Equals(q2), "The multi-segment case must produce same rewritten query"); Assert.IsTrue(q1.Equals(q3), "The multi-segment case with duplicates must produce same rewritten query"); CheckBooleanQueryOrder(q1); CheckBooleanQueryOrder(q2); CheckBooleanQueryOrder(q3); } [Test] public virtual void TestRewritesWithDuplicateTerms() { CheckDuplicateTerms(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE); CheckDuplicateTerms(MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE); // use a large PQ here to only test duplicate terms and dont mix up when all scores are equal CheckDuplicateTerms(new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(1024)); CheckDuplicateTerms(new MultiTermQuery.TopTermsBoostOnlyBooleanQueryRewrite(1024)); // Test auto rewrite (but only boolean mode), so we set the limits to large values to always get a BQ ConstantScoreAutoRewrite rewrite = new ConstantScoreAutoRewrite(); rewrite.TermCountCutoff = int.MaxValue; rewrite.DocCountPercent = 100.0; CheckDuplicateTerms(rewrite); } private void CheckBooleanQueryBoosts(BooleanQuery bq) { foreach (BooleanClause clause in bq.Clauses) { TermQuery mtq = (TermQuery)clause.Query; Assert.AreEqual(Convert.ToSingle(mtq.Term.Text()), mtq.Boost, 0, "Parallel sorting of boosts in rewrite mode broken"); } } private void CheckBoosts(MultiTermQuery.RewriteMethod method) { MultiTermQuery mtq = new MultiTermQueryAnonymousInnerClassHelper(this); mtq.MultiTermRewriteMethod = (method); Query q1 = searcher.Rewrite(mtq); Query q2 = multiSearcher.Rewrite(mtq); Query q3 = multiSearcherDupls.Rewrite(mtq); if (Verbose) { Console.WriteLine(); Console.WriteLine("single segment: " + q1); Console.WriteLine("multi segment: " + q2); Console.WriteLine("multi segment with duplicates: " + q3); } Assert.IsTrue(q1.Equals(q2), "The multi-segment case must produce same rewritten query"); Assert.IsTrue(q1.Equals(q3), "The multi-segment case with duplicates must produce same rewritten query"); CheckBooleanQueryBoosts((BooleanQuery)q1); CheckBooleanQueryBoosts((BooleanQuery)q2); CheckBooleanQueryBoosts((BooleanQuery)q3); } private class MultiTermQueryAnonymousInnerClassHelper : MultiTermQuery { private readonly TestMultiTermQueryRewrites outerInstance; public MultiTermQueryAnonymousInnerClassHelper(TestMultiTermQueryRewrites outerInstance) : base("data") { this.outerInstance = outerInstance; } protected override TermsEnum GetTermsEnum(Terms terms, AttributeSource atts) { return new TermRangeTermsEnumAnonymousInnerClassHelper(this, terms.GetEnumerator(), new BytesRef("2"), new BytesRef("7")); } private class TermRangeTermsEnumAnonymousInnerClassHelper : TermRangeTermsEnum { private readonly MultiTermQueryAnonymousInnerClassHelper outerInstance; public TermRangeTermsEnumAnonymousInnerClassHelper(MultiTermQueryAnonymousInnerClassHelper outerInstance, TermsEnum iterator, BytesRef bref1, BytesRef bref2) : base(iterator, bref1, bref2, true, true) { this.outerInstance = outerInstance; boostAtt = Attributes.AddAttribute<IBoostAttribute>(); } internal readonly IBoostAttribute boostAtt; protected override AcceptStatus Accept(BytesRef term) { boostAtt.Boost = Convert.ToSingle(term.Utf8ToString()); return base.Accept(term); } } public override string ToString(string field) { return "dummy"; } } [Test] public virtual void TestBoosts() { CheckBoosts(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE); // use a large PQ here to only test boosts and dont mix up when all scores are equal CheckBoosts(new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(1024)); } private void CheckMaxClauseLimitation(MultiTermQuery.RewriteMethod method, [CallerMemberName] string memberName = "") { int savedMaxClauseCount = BooleanQuery.MaxClauseCount; BooleanQuery.MaxClauseCount = 3; MultiTermQuery mtq = TermRangeQuery.NewStringRange("data", "2", "7", true, true); mtq.MultiTermRewriteMethod = (method); try { multiSearcherDupls.Rewrite(mtq); Assert.Fail("Should throw BooleanQuery.TooManyClauses"); } catch (BooleanQuery.TooManyClausesException e) { // Maybe remove this assert in later versions, when internal API changes: Assert.AreEqual("CheckMaxClauseCount", new StackTrace(e, false).GetFrames()[0].GetMethod().Name); //, "Should throw BooleanQuery.TooManyClauses with a stacktrace containing checkMaxClauseCount()"); } finally { BooleanQuery.MaxClauseCount = savedMaxClauseCount; } } private void CheckNoMaxClauseLimitation(MultiTermQuery.RewriteMethod method) { int savedMaxClauseCount = BooleanQuery.MaxClauseCount; BooleanQuery.MaxClauseCount = 3; MultiTermQuery mtq = TermRangeQuery.NewStringRange("data", "2", "7", true, true); mtq.MultiTermRewriteMethod = (method); try { multiSearcherDupls.Rewrite(mtq); } finally { BooleanQuery.MaxClauseCount = savedMaxClauseCount; } } [Test] public virtual void TestMaxClauseLimitations() { CheckMaxClauseLimitation(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE); CheckMaxClauseLimitation(MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE); CheckNoMaxClauseLimitation(MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE); CheckNoMaxClauseLimitation(MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT); CheckNoMaxClauseLimitation(new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(1024)); CheckNoMaxClauseLimitation(new MultiTermQuery.TopTermsBoostOnlyBooleanQueryRewrite(1024)); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics.Contracts; namespace System.Drawing { /// <summary> /// <para> /// Stores the location and size of a rectangular region. /// </para> /// </summary> public struct RectangleF { /// <summary> /// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/> /// class. /// </summary> public static readonly RectangleF Empty = new RectangleF(); private float _x; private float _y; private float _width; private float _height; /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/> /// class with the specified location and size. /// </para> /// </summary> public RectangleF(float x, float y, float width, float height) { _x = x; _y = y; _width = width; _height = height; } /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/> /// class with the specified location /// and size. /// </para> /// </summary> public RectangleF(PointF location, SizeF size) { _x = location.X; _y = location.Y; _width = size.Width; _height = size.Height; } /// <summary> /// <para> /// Creates a new <see cref='System.Drawing.RectangleF'/> with /// the specified location and size. /// </para> /// </summary> public static RectangleF FromLTRB(float left, float top, float right, float bottom) { return new RectangleF(left, top, right - left, bottom - top); } /// <summary> /// <para> /// Gets or sets the coordinates of the upper-left corner of /// the rectangular region represented by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public PointF Location { get { return new PointF(X, Y); } set { X = value.X; Y = value.Y; } } /// <summary> /// <para> /// Gets or sets the size of this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public SizeF Size { get { return new SizeF(Width, Height); } set { Width = value.Width; Height = value.Height; } } /// <summary> /// <para> /// Gets or sets the x-coordinate of the /// upper-left corner of the rectangular region defined by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public float X { get { return _x; } set { _x = value; } } /// <summary> /// <para> /// Gets or sets the y-coordinate of the /// upper-left corner of the rectangular region defined by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public float Y { get { return _y; } set { _y = value; } } /// <summary> /// <para> /// Gets or sets the width of the rectangular /// region defined by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public float Width { get { return _width; } set { _width = value; } } /// <summary> /// <para> /// Gets or sets the height of the /// rectangular region defined by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public float Height { get { return _height; } set { _height = value; } } /// <summary> /// <para> /// Gets the x-coordinate of the upper-left corner of the /// rectangular region defined by this <see cref='System.Drawing.RectangleF'/> . /// </para> /// </summary> public float Left { get { return X; } } /// <summary> /// <para> /// Gets the y-coordinate of the upper-left corner of the /// rectangular region defined by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public float Top { get { return Y; } } /// <summary> /// <para> /// Gets the x-coordinate of the lower-right corner of the /// rectangular region defined by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public float Right { get { return X + Width; } } /// <summary> /// <para> /// Gets the y-coordinate of the lower-right corner of the /// rectangular region defined by this <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public float Bottom { get { return Y + Height; } } /// <summary> /// <para> /// Tests whether this <see cref='System.Drawing.RectangleF'/> has a <see cref='System.Drawing.RectangleF.Width'/> or a <see cref='System.Drawing.RectangleF.Height'/> of 0. /// </para> /// </summary> public bool IsEmpty { get { return (Width <= 0) || (Height <= 0); } } /// <summary> /// <para> /// Tests whether <paramref name="obj"/> is a <see cref='System.Drawing.RectangleF'/> with the same location and size of this /// <see cref='System.Drawing.RectangleF'/>. /// </para> /// </summary> public override bool Equals(object obj) { if (!(obj is RectangleF)) return false; RectangleF comp = (RectangleF)obj; return (comp.X == X) && (comp.Y == Y) && (comp.Width == Width) && (comp.Height == Height); } /// <summary> /// <para> /// Tests whether two <see cref='System.Drawing.RectangleF'/> /// objects have equal location and size. /// </para> /// </summary> public static bool operator ==(RectangleF left, RectangleF right) { return (left.X == right.X && left.Y == right.Y && left.Width == right.Width && left.Height == right.Height); } /// <summary> /// <para> /// Tests whether two <see cref='System.Drawing.RectangleF'/> /// objects differ in location or size. /// </para> /// </summary> public static bool operator !=(RectangleF left, RectangleF right) { return !(left == right); } /// <summary> /// <para> /// Determines if the specfied point is contained within the /// rectangular region defined by this <see cref='System.Drawing.Rectangle'/> . /// </para> /// </summary> [Pure] public bool Contains(float x, float y) { return X <= x && x < X + Width && Y <= y && y < Y + Height; } /// <summary> /// <para> /// Determines if the specfied point is contained within the /// rectangular region defined by this <see cref='System.Drawing.Rectangle'/> . /// </para> /// </summary> [Pure] public bool Contains(PointF pt) { return Contains(pt.X, pt.Y); } /// <summary> /// <para> /// Determines if the rectangular region represented by /// <paramref name="rect"/> is entirely contained within the rectangular region represented by /// this <see cref='System.Drawing.Rectangle'/> . /// </para> /// </summary> [Pure] public bool Contains(RectangleF rect) { return (X <= rect.X) && ((rect.X + rect.Width) <= (X + Width)) && (Y <= rect.Y) && ((rect.Y + rect.Height) <= (Y + Height)); } /// <summary> /// Gets the hash code for this <see cref='System.Drawing.RectangleF'/>. /// </summary> public override int GetHashCode() { return (int)((uint)X ^ (((uint)Y << 13) | ((uint)Y >> 19)) ^ (((uint)Width << 26) | ((uint)Width >> 6)) ^ (((uint)Height << 7) | ((uint)Height >> 25))); } /// <summary> /// <para> /// Inflates this <see cref='System.Drawing.Rectangle'/> /// by the specified amount. /// </para> /// </summary> public void Inflate(float x, float y) { X -= x; Y -= y; Width += 2 * x; Height += 2 * y; } /// <summary> /// Inflates this <see cref='System.Drawing.Rectangle'/> by the specified amount. /// </summary> public void Inflate(SizeF size) { Inflate(size.Width, size.Height); } /// <summary> /// <para> /// Creates a <see cref='System.Drawing.Rectangle'/> /// that is inflated by the specified amount. /// </para> /// </summary> public static RectangleF Inflate(RectangleF rect, float x, float y) { RectangleF r = rect; r.Inflate(x, y); return r; } /// <summary> Creates a Rectangle that represents the intersection between this Rectangle and rect. /// </summary> public void Intersect(RectangleF rect) { RectangleF result = RectangleF.Intersect(rect, this); X = result.X; Y = result.Y; Width = result.Width; Height = result.Height; } /// <summary> /// Creates a rectangle that represents the intersetion between a and /// b. If there is no intersection, null is returned. /// </summary> [Pure] public static RectangleF Intersect(RectangleF a, RectangleF b) { float x1 = Math.Max(a.X, b.X); float x2 = Math.Min(a.X + a.Width, b.X + b.Width); float y1 = Math.Max(a.Y, b.Y); float y2 = Math.Min(a.Y + a.Height, b.Y + b.Height); if (x2 >= x1 && y2 >= y1) { return new RectangleF(x1, y1, x2 - x1, y2 - y1); } return Empty; } /// <summary> /// Determines if this rectangle intersets with rect. /// </summary> [Pure] public bool IntersectsWith(RectangleF rect) { return (rect.X < X + Width) && (X < (rect.X + rect.Width)) && (rect.Y < Y + Height) && (Y < rect.Y + rect.Height); } /// <summary> /// Creates a rectangle that represents the union between a and /// b. /// </summary> [Pure] public static RectangleF Union(RectangleF a, RectangleF b) { float x1 = Math.Min(a.X, b.X); float x2 = Math.Max(a.X + a.Width, b.X + b.Width); float y1 = Math.Min(a.Y, b.Y); float y2 = Math.Max(a.Y + a.Height, b.Y + b.Height); return new RectangleF(x1, y1, x2 - x1, y2 - y1); } /// <summary> /// Adjusts the location of this rectangle by the specified amount. /// </summary> public void Offset(PointF pos) { Offset(pos.X, pos.Y); } /// <summary> /// Adjusts the location of this rectangle by the specified amount. /// </summary> public void Offset(float x, float y) { X += x; Y += y; } /// <summary> /// Converts the specified <see cref='System.Drawing.Rectangle'/> to a /// <see cref='System.Drawing.RectangleF'/>. /// </summary> public static implicit operator RectangleF(Rectangle r) { return new RectangleF(r.X, r.Y, r.Width, r.Height); } /// <summary> /// Converts the <see cref='System.Drawing.RectangleF.Location'/> and <see cref='System.Drawing.RectangleF.Size'/> of this <see cref='System.Drawing.RectangleF'/> to a /// human-readable string. /// </summary> public override string ToString() { return "{X=" + X.ToString() + ",Y=" + Y.ToString() + ",Width=" + Width.ToString() + ",Height=" + Height.ToString() + "}"; } } }
using System; using System.Collections; using System.Collections.Specialized; using Avalonia.Collections; using Avalonia.Data; using Avalonia.Logging; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Metadata; using Avalonia.Rendering; using Avalonia.Utilities; using Avalonia.VisualTree; #nullable enable namespace Avalonia { /// <summary> /// Base class for controls that provides rendering and related visual properties. /// </summary> /// <remarks> /// The <see cref="Visual"/> class represents elements that have a visual on-screen /// representation and stores all the information needed for an /// <see cref="IRenderer"/> to render the control. To traverse the visual tree, use the /// extension methods defined in <see cref="VisualExtensions"/>. /// </remarks> [UsableDuringInitialization] public class Visual : StyledElement, IVisual { /// <summary> /// Defines the <see cref="Bounds"/> property. /// </summary> public static readonly DirectProperty<Visual, Rect> BoundsProperty = AvaloniaProperty.RegisterDirect<Visual, Rect>(nameof(Bounds), o => o.Bounds); public static readonly DirectProperty<Visual, TransformedBounds?> TransformedBoundsProperty = AvaloniaProperty.RegisterDirect<Visual, TransformedBounds?>( nameof(TransformedBounds), o => o.TransformedBounds); /// <summary> /// Defines the <see cref="ClipToBounds"/> property. /// </summary> public static readonly StyledProperty<bool> ClipToBoundsProperty = AvaloniaProperty.Register<Visual, bool>(nameof(ClipToBounds)); /// <summary> /// Defines the <see cref="Clip"/> property. /// </summary> public static readonly StyledProperty<Geometry?> ClipProperty = AvaloniaProperty.Register<Visual, Geometry?>(nameof(Clip)); /// <summary> /// Defines the <see cref="IsVisibleProperty"/> property. /// </summary> public static readonly StyledProperty<bool> IsVisibleProperty = AvaloniaProperty.Register<Visual, bool>(nameof(IsVisible), true); /// <summary> /// Defines the <see cref="Opacity"/> property. /// </summary> public static readonly StyledProperty<double> OpacityProperty = AvaloniaProperty.Register<Visual, double>(nameof(Opacity), 1); /// <summary> /// Defines the <see cref="OpacityMask"/> property. /// </summary> public static readonly StyledProperty<IBrush?> OpacityMaskProperty = AvaloniaProperty.Register<Visual, IBrush?>(nameof(OpacityMask)); /// <summary> /// Defines the <see cref="RenderTransform"/> property. /// </summary> public static readonly StyledProperty<ITransform?> RenderTransformProperty = AvaloniaProperty.Register<Visual, ITransform?>(nameof(RenderTransform)); /// <summary> /// Defines the <see cref="RenderTransformOrigin"/> property. /// </summary> public static readonly StyledProperty<RelativePoint> RenderTransformOriginProperty = AvaloniaProperty.Register<Visual, RelativePoint>(nameof(RenderTransformOrigin), defaultValue: RelativePoint.Center); /// <summary> /// Defines the <see cref="IVisual.VisualParent"/> property. /// </summary> public static readonly DirectProperty<Visual, IVisual?> VisualParentProperty = AvaloniaProperty.RegisterDirect<Visual, IVisual?>(nameof(IVisual.VisualParent), o => o._visualParent); /// <summary> /// Defines the <see cref="ZIndex"/> property. /// </summary> public static readonly StyledProperty<int> ZIndexProperty = AvaloniaProperty.Register<Visual, int>(nameof(ZIndex)); private Rect _bounds; private TransformedBounds? _transformedBounds; private IRenderRoot? _visualRoot; private IVisual? _visualParent; /// <summary> /// Initializes static members of the <see cref="Visual"/> class. /// </summary> static Visual() { AffectsRender<Visual>( BoundsProperty, ClipProperty, ClipToBoundsProperty, IsVisibleProperty, OpacityProperty); RenderTransformProperty.Changed.Subscribe(RenderTransformChanged); ZIndexProperty.Changed.Subscribe(ZIndexChanged); } /// <summary> /// Initializes a new instance of the <see cref="Visual"/> class. /// </summary> public Visual() { // Disable transitions until we're added to the visual tree. DisableTransitions(); var visualChildren = new AvaloniaList<IVisual>(); visualChildren.ResetBehavior = ResetBehavior.Remove; visualChildren.Validate = visual => ValidateVisualChild(visual); visualChildren.CollectionChanged += VisualChildrenChanged; VisualChildren = visualChildren; } /// <summary> /// Raised when the control is attached to a rooted visual tree. /// </summary> public event EventHandler<VisualTreeAttachmentEventArgs>? AttachedToVisualTree; /// <summary> /// Raised when the control is detached from a rooted visual tree. /// </summary> public event EventHandler<VisualTreeAttachmentEventArgs>? DetachedFromVisualTree; /// <summary> /// Gets the bounds of the control relative to its parent. /// </summary> public Rect Bounds { get { return _bounds; } protected set { SetAndRaise(BoundsProperty, ref _bounds, value); } } /// <summary> /// Gets the bounds of the control relative to the window, accounting for rendering transforms. /// </summary> public TransformedBounds? TransformedBounds => _transformedBounds; /// <summary> /// Gets or sets a value indicating whether the control should be clipped to its bounds. /// </summary> public bool ClipToBounds { get { return GetValue(ClipToBoundsProperty); } set { SetValue(ClipToBoundsProperty, value); } } /// <summary> /// Gets or sets the geometry clip for this visual. /// </summary> public Geometry? Clip { get { return GetValue(ClipProperty); } set { SetValue(ClipProperty, value); } } /// <summary> /// Gets a value indicating whether this control and all its parents are visible. /// </summary> public bool IsEffectivelyVisible { get { IVisual? node = this; while (node != null) { if (!node.IsVisible) { return false; } node = node.VisualParent; } return true; } } /// <summary> /// Gets or sets a value indicating whether this control is visible. /// </summary> public bool IsVisible { get { return GetValue(IsVisibleProperty); } set { SetValue(IsVisibleProperty, value); } } /// <summary> /// Gets or sets the opacity of the control. /// </summary> public double Opacity { get { return GetValue(OpacityProperty); } set { SetValue(OpacityProperty, value); } } /// <summary> /// Gets or sets the opacity mask of the control. /// </summary> public IBrush? OpacityMask { get { return GetValue(OpacityMaskProperty); } set { SetValue(OpacityMaskProperty, value); } } /// <summary> /// Gets or sets the render transform of the control. /// </summary> public ITransform? RenderTransform { get { return GetValue(RenderTransformProperty); } set { SetValue(RenderTransformProperty, value); } } /// <summary> /// Gets or sets the transform origin of the control. /// </summary> public RelativePoint RenderTransformOrigin { get { return GetValue(RenderTransformOriginProperty); } set { SetValue(RenderTransformOriginProperty, value); } } /// <summary> /// Gets or sets the Z index of the control. /// </summary> /// <remarks> /// Controls with a higher <see cref="ZIndex"/> will appear in front of controls with /// a lower ZIndex. If two controls have the same ZIndex then the control that appears /// later in the containing element's children collection will appear on top. /// </remarks> public int ZIndex { get { return GetValue(ZIndexProperty); } set { SetValue(ZIndexProperty, value); } } /// <summary> /// Gets the control's child visuals. /// </summary> protected IAvaloniaList<IVisual> VisualChildren { get; private set; } /// <summary> /// Gets the root of the visual tree, if the control is attached to a visual tree. /// </summary> protected IRenderRoot? VisualRoot => _visualRoot ?? (this as IRenderRoot); /// <summary> /// Gets a value indicating whether this control is attached to a visual root. /// </summary> bool IVisual.IsAttachedToVisualTree => VisualRoot != null; /// <summary> /// Gets the control's child controls. /// </summary> IAvaloniaReadOnlyList<IVisual> IVisual.VisualChildren => VisualChildren; /// <summary> /// Gets the control's parent visual. /// </summary> IVisual? IVisual.VisualParent => _visualParent; /// <summary> /// Gets the root of the visual tree, if the control is attached to a visual tree. /// </summary> IRenderRoot? IVisual.VisualRoot => VisualRoot; TransformedBounds? IVisual.TransformedBounds { get { return _transformedBounds; } set { SetAndRaise(TransformedBoundsProperty, ref _transformedBounds, value); } } /// <summary> /// Invalidates the visual and queues a repaint. /// </summary> public void InvalidateVisual() { VisualRoot?.Renderer?.AddDirty(this); } /// <summary> /// Renders the visual to a <see cref="DrawingContext"/>. /// </summary> /// <param name="context">The drawing context.</param> public virtual void Render(DrawingContext context) { Contract.Requires<ArgumentNullException>(context != null); } /// <summary> /// Indicates that a property change should cause <see cref="InvalidateVisual"/> to be /// called. /// </summary> /// <param name="properties">The properties.</param> /// <remarks> /// This method should be called in a control's static constructor with each property /// on the control which when changed should cause a redraw. This is similar to WPF's /// FrameworkPropertyMetadata.AffectsRender flag. /// </remarks> [Obsolete("Use AffectsRender<T> and specify the control type.")] protected static void AffectsRender(params AvaloniaProperty[] properties) { AffectsRender<Visual>(properties); } /// <summary> /// Indicates that a property change should cause <see cref="InvalidateVisual"/> to be /// called. /// </summary> /// <typeparam name="T">The control which the property affects.</typeparam> /// <param name="properties">The properties.</param> /// <remarks> /// This method should be called in a control's static constructor with each property /// on the control which when changed should cause a redraw. This is similar to WPF's /// FrameworkPropertyMetadata.AffectsRender flag. /// </remarks> protected static void AffectsRender<T>(params AvaloniaProperty[] properties) where T : Visual { static void Invalidate(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is T sender) { sender.InvalidateVisual(); } } static void InvalidateAndSubscribe(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is T sender) { if (e.OldValue is IAffectsRender oldValue) { WeakEventHandlerManager.Unsubscribe<EventArgs, T>(oldValue, nameof(oldValue.Invalidated), sender.AffectsRenderInvalidated); } if (e.NewValue is IAffectsRender newValue) { WeakEventHandlerManager.Subscribe<IAffectsRender, EventArgs, T>(newValue, nameof(newValue.Invalidated), sender.AffectsRenderInvalidated); } sender.InvalidateVisual(); } } foreach (var property in properties) { if (property.CanValueAffectRender()) { property.Changed.Subscribe(e => InvalidateAndSubscribe(e)); } else { property.Changed.Subscribe(e => Invalidate(e)); } } } protected override void LogicalChildrenCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { base.LogicalChildrenCollectionChanged(sender, e); VisualRoot?.Renderer?.RecalculateChildren(this); } /// <summary> /// Calls the <see cref="OnAttachedToVisualTree(VisualTreeAttachmentEventArgs)"/> method /// for this control and all of its visual descendants. /// </summary> /// <param name="e">The event args.</param> protected virtual void OnAttachedToVisualTreeCore(VisualTreeAttachmentEventArgs e) { Logger.TryGet(LogEventLevel.Verbose, LogArea.Visual)?.Log(this, "Attached to visual tree"); _visualRoot = e.Root; if (RenderTransform is IMutableTransform mutableTransform) { mutableTransform.Changed += RenderTransformChanged; } EnableTransitions(); OnAttachedToVisualTree(e); AttachedToVisualTree?.Invoke(this, e); InvalidateVisual(); var visualChildren = VisualChildren; if (visualChildren != null) { var visualChildrenCount = visualChildren.Count; for (var i = 0; i < visualChildrenCount; i++) { if (visualChildren[i] is Visual child) { child.OnAttachedToVisualTreeCore(e); } } } } /// <summary> /// Calls the <see cref="OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs)"/> method /// for this control and all of its visual descendants. /// </summary> /// <param name="e">The event args.</param> protected virtual void OnDetachedFromVisualTreeCore(VisualTreeAttachmentEventArgs e) { Logger.TryGet(LogEventLevel.Verbose, LogArea.Visual)?.Log(this, "Detached from visual tree"); _visualRoot = null; if (RenderTransform is IMutableTransform mutableTransform) { mutableTransform.Changed -= RenderTransformChanged; } DisableTransitions(); OnDetachedFromVisualTree(e); DetachedFromVisualTree?.Invoke(this, e); e.Root?.Renderer?.AddDirty(this); var visualChildren = VisualChildren; if (visualChildren != null) { var visualChildrenCount = visualChildren.Count; for (var i = 0; i < visualChildrenCount; i++) { if (visualChildren[i] is Visual child) { child.OnDetachedFromVisualTreeCore(e); } } } } /// <summary> /// Called when the control is added to a rooted visual tree. /// </summary> /// <param name="e">The event args.</param> protected virtual void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) { } /// <summary> /// Called when the control is removed from a rooted visual tree. /// </summary> /// <param name="e">The event args.</param> protected virtual void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e) { } /// <summary> /// Called when the control's visual parent changes. /// </summary> /// <param name="oldParent">The old visual parent.</param> /// <param name="newParent">The new visual parent.</param> protected virtual void OnVisualParentChanged(IVisual? oldParent, IVisual? newParent) { RaisePropertyChanged( VisualParentProperty, new Optional<IVisual?>(oldParent), new BindingValue<IVisual?>(newParent), BindingPriority.LocalValue); } protected internal sealed override void LogBindingError(AvaloniaProperty property, Exception e) { // Don't log a binding error unless the control is attached to a logical tree. if (((ILogical)this).IsAttachedToLogicalTree) { if (e is BindingChainException b && string.IsNullOrEmpty(b.ExpressionErrorPoint) && DataContext == null) { // The error occurred at the root of the binding chain and DataContext is null; // don't log this - the DataContext probably hasn't been set up yet. return; } Logger.TryGet(LogEventLevel.Warning, LogArea.Binding)?.Log( this, "Error in binding to {Target}.{Property}: {Message}", this, property, e.Message); } } /// <summary> /// Called when a visual's <see cref="RenderTransform"/> changes. /// </summary> /// <param name="e">The event args.</param> private static void RenderTransformChanged(AvaloniaPropertyChangedEventArgs e) { var sender = e.Sender as Visual; if (sender?.VisualRoot != null) { var oldValue = e.OldValue as Transform; var newValue = e.NewValue as Transform; if (oldValue != null) { oldValue.Changed -= sender.RenderTransformChanged; } if (newValue != null) { newValue.Changed += sender.RenderTransformChanged; } sender.InvalidateVisual(); } } /// <summary> /// Ensures a visual child is not null and not already parented. /// </summary> /// <param name="c">The visual child.</param> private static void ValidateVisualChild(IVisual c) { if (c == null) { throw new ArgumentNullException(nameof(c), "Cannot add null to VisualChildren."); } if (c.VisualParent != null) { throw new InvalidOperationException("The control already has a visual parent."); } } /// <summary> /// Called when the <see cref="ZIndex"/> property changes on any control. /// </summary> /// <param name="e">The event args.</param> private static void ZIndexChanged(AvaloniaPropertyChangedEventArgs e) { var sender = e.Sender as IVisual; var parent = sender?.VisualParent; sender?.InvalidateVisual(); parent?.VisualRoot?.Renderer?.RecalculateChildren(parent); } /// <summary> /// Called when the <see cref="RenderTransform"/>'s <see cref="Transform.Changed"/> event /// is fired. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The event args.</param> private void RenderTransformChanged(object? sender, EventArgs e) { InvalidateVisual(); } /// <summary> /// Sets the visual parent of the Visual. /// </summary> /// <param name="value">The visual parent.</param> private void SetVisualParent(Visual? value) { if (_visualParent == value) { return; } var old = _visualParent; _visualParent = value; if (_visualRoot != null) { var e = new VisualTreeAttachmentEventArgs(old!, _visualRoot); OnDetachedFromVisualTreeCore(e); } if (_visualParent is IRenderRoot || _visualParent?.IsAttachedToVisualTree == true) { var root = this.FindAncestorOfType<IRenderRoot>() ?? throw new AvaloniaInternalException("Visual is atached to visual tree but root could not be found."); var e = new VisualTreeAttachmentEventArgs(_visualParent, root); OnAttachedToVisualTreeCore(e); } OnVisualParentChanged(old, value); } private void AffectsRenderInvalidated(object? sender, EventArgs e) => InvalidateVisual(); /// <summary> /// Called when the <see cref="VisualChildren"/> collection changes. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The event args.</param> private void VisualChildrenChanged(object? sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: SetVisualParent(e.NewItems!, this); break; case NotifyCollectionChangedAction.Remove: SetVisualParent(e.OldItems!, null); break; case NotifyCollectionChangedAction.Replace: SetVisualParent(e.OldItems!, null); SetVisualParent(e.NewItems!, this); break; } } private static void SetVisualParent(IList children, Visual? parent) { var count = children.Count; for (var i = 0; i < count; i++) { var visual = (Visual) children[i]!; visual.SetVisualParent(parent); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DotVVM.Framework.Binding; using DotVVM.Framework.Binding.Expressions; using DotVVM.Framework.Runtime; using Newtonsoft.Json; using DotVVM.Framework.Hosting; namespace DotVVM.Framework.Controls { public static class KnockoutHelper { public static void AddKnockoutDataBind(this IHtmlWriter writer, string name, DotvvmControl control, DotvvmProperty property, Action nullBindingAction = null, string valueUpdate = null, bool renderEvenInServerRenderingMode = false, bool setValueBack = false) { var expression = control.GetValueBinding(property); if (expression != null && (!control.RenderOnServer || renderEvenInServerRenderingMode)) { writer.AddAttribute("data-bind", name + ": " + expression.GetKnockoutBindingExpression(), true, ", "); if (valueUpdate != null) { writer.AddAttribute("data-bind", "valueUpdate: '" + valueUpdate + "'", true, ", "); } } else { if (nullBindingAction != null) nullBindingAction(); if (setValueBack && expression != null) control.SetValue(property, expression.Evaluate(control, property)); } } public static void AddKnockoutDataBind(this IHtmlWriter writer, string name, IValueBinding valueBinding) { writer.AddKnockoutDataBind(name, valueBinding.GetKnockoutBindingExpression()); } public static void AddKnockoutDataBind(this IHtmlWriter writer, string name, IEnumerable<KeyValuePair<string, IValueBinding>> expressions, DotvvmControl control, DotvvmProperty property) { writer.AddAttribute("data-bind", name + ": {" + String.Join(",", expressions.Select(e => "'" + e.Key + "': " + e.Value.GetKnockoutBindingExpression())) + "}", true, ", "); } public static void WriteKnockoutForeachComment(this IHtmlWriter writer, string binding) { writer.WriteKnockoutDataBindComment("foreach", binding); } public static void WriteKnockoutWithComment(this IHtmlWriter writer, string binding) { writer.WriteKnockoutDataBindComment("with", binding); } public static void WriteKnockoutDataBindComment(this IHtmlWriter writer, string name, string expression) { writer.WriteUnencodedText($"<!-- ko { name }: { expression } -->"); } public static void WriteKnockoutDataBindComment(this IHtmlWriter writer, string name, DotvvmControl control, DotvvmProperty property) { writer.WriteUnencodedText($"<!-- ko { name }: { control.GetValueBinding(property).GetKnockoutBindingExpression() } -->"); } public static void WriteKnockoutDataBindEndComment(this IHtmlWriter writer) { writer.WriteUnencodedText("<!-- /ko -->"); } public static void AddKnockoutForeachDataBind(this IHtmlWriter writer, string expression) { writer.AddKnockoutDataBind("foreach", expression); } public static string GenerateClientPostBackScript(string propertyName, ICommandBinding expression, DotvvmControl control, bool useWindowSetTimeout = false, bool? returnValue = false, bool isOnChange = false, string elementAccessor = "this") { return GenerateClientPostBackScript(propertyName, expression, control, new PostbackScriptOptions(useWindowSetTimeout, returnValue, isOnChange, elementAccessor)); } public static string GenerateClientPostBackScript(string propertyName, ICommandBinding expression, DotvvmControl control, PostbackScriptOptions options) { object uniqueControlId = null; var target = (DotvvmControl)control.GetClosestControlBindingTarget(); uniqueControlId = target?.GetDotvvmUniqueId(); var arguments = new List<string>() { "'root'", options.ElementAccessor, "[" + String.Join(", ", GetContextPath(control).Reverse().Select(p => '"' + p + '"')) + "]", (uniqueControlId is IValueBinding ? "{ expr: " + JsonConvert.ToString(((IValueBinding)uniqueControlId).GetKnockoutBindingExpression(), '\'', StringEscapeHandling.Default) + "}" : "'" + (string) uniqueControlId + "'"), options.UseWindowSetTimeout ? "true" : "false", JsonConvert.SerializeObject(GetValidationTargetExpression(control)), "null", GetPostBackHandlersScript(control, propertyName) }; // return the script var condition = options.IsOnChange ? "if (!dotvvm.isViewModelUpdating) " : null; var returnStatement = options.ReturnValue != null ? $";return {options.ReturnValue.ToString().ToLower()};" : ""; // call the function returned from binding js with runtime arguments var postBackCall = $"{expression.GetCommandJavascript()}({String.Join(", ", arguments)})"; return condition + postBackCall + returnStatement; } /// <summary> /// Generates a list of postback update handlers. /// </summary> private static string GetPostBackHandlersScript(DotvvmControl control, string eventName) { var handlers = (List<PostBackHandler>)control.GetValue(PostBack.HandlersProperty); if (handlers == null) return "null"; var effectiveHandlers = handlers.Where(h => string.IsNullOrEmpty(h.EventName) || h.EventName == eventName); var sb = new StringBuilder(); sb.Append("["); foreach (var handler in effectiveHandlers) { if (sb.Length > 1) { sb.Append(","); } sb.Append("{name:'"); sb.Append(handler.ClientHandlerName); sb.Append("',options:function(){return {"); var isFirst = true; var options = handler.GetHandlerOptionClientExpressions(); options.Add("enabled", handler.TranslateValueOrBinding(PostBackHandler.EnabledProperty)); foreach (var option in options) { if (!isFirst) { sb.Append(','); } isFirst = false; sb.Append(option.Key); sb.Append(":"); sb.Append(option.Value); } sb.Append("};}}"); } sb.Append("]"); return sb.ToString(); } public static IEnumerable<string> GetContextPath(DotvvmControl control) { while (control != null) { var pathFragment = control.GetValue(Internal.PathFragmentProperty, false) as string; if (pathFragment != null) { yield return pathFragment; } else { var dataContextBinding = control.GetBinding(DotvvmBindableObject.DataContextProperty, false) as IValueBinding; if (dataContextBinding != null) { yield return dataContextBinding.GetKnockoutBindingExpression(); } } control = control.Parent; } } /// <summary> /// Gets the validation target expression. /// </summary> public static string GetValidationTargetExpression(DotvvmBindableObject control) { if (!(bool)control.GetValue(Validation.EnabledProperty)) { return null; } // find the closest control int dataSourceChanges; var validationTargetControl = control.GetClosestControlValidationTarget(out dataSourceChanges); if (validationTargetControl == null) { return "$root"; } // reparent the expression to work in current DataContext var validationBindingExpression = validationTargetControl.GetValueBinding(Validation.TargetProperty); string validationExpression = validationBindingExpression.GetKnockoutBindingExpression(); validationExpression = string.Join("", Enumerable.Range(0, dataSourceChanges).Select(i => "$parentContext.")) + validationExpression; return validationExpression; } /// <summary> /// Add knockout data bind comment dotvvm_withControlProperties with the specified properties /// </summary> public static void AddCommentAliasBinding(IHtmlWriter writer, IDictionary<string, string> properties) { writer.WriteKnockoutDataBindComment("dotvvm_introduceAlias", "{" + string.Join(", ", properties.Select(p => JsonConvert.ToString(p.Key) + ":" + properties.Values)) + "}"); } /// <summary> /// Writes text iff the property contains hard-coded value OR /// writes knockout text binding iff the property contains binding /// </summary> /// <param name="writer">HTML output writer</param> /// <param name="obj">Dotvvm control which contains the <see cref="DotvvmProperty"/> with value to be written</param> /// <param name="property">Value of this property will be written</param> /// <param name="wrapperTag">Name of wrapper tag, null => knockout binding comment</param> public static void WriteTextOrBinding(this IHtmlWriter writer, DotvvmBindableObject obj, DotvvmProperty property, string wrapperTag = null) { var valueBinding = obj.GetValueBinding(property); if (valueBinding != null) { if (wrapperTag == null) { writer.WriteKnockoutDataBindComment("text", valueBinding.GetKnockoutBindingExpression()); writer.WriteKnockoutDataBindEndComment(); } else { writer.AddKnockoutDataBind("text", valueBinding.GetKnockoutBindingExpression()); writer.RenderBeginTag(wrapperTag); writer.RenderEndTag(); } } else { if (wrapperTag != null) writer.RenderBeginTag(wrapperTag); writer.WriteText(obj.GetValue(property).ToString()); if (wrapperTag != null) writer.RenderEndTag(); } } /// <summary> /// Returns Javascript expression that represents the property value (even if the property contains hardcoded value) /// </summary> public static string GetKnockoutBindingExpression(this DotvvmBindableObject obj, DotvvmProperty property) { var binding = obj.GetValueBinding(property); if (binding != null) return binding.GetKnockoutBindingExpression(); return JsonConvert.SerializeObject(obj.GetValue(property)); } /// <summary> /// Encodes the string so it can be used in Javascript code. /// </summary> public static string MakeStringLiteral(string value, bool useApos = true) { return JsonConvert.ToString(value, useApos ? '\'' : '"', StringEscapeHandling.Default); } public static string ConvertToCamelCase(string name) { return name.Substring(0, 1).ToLower() + name.Substring(1); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Data.Common; using System.Data.SqlTypes; using System.Diagnostics; using System.Globalization; using System.Xml; using System.IO; using MSS = Microsoft.SqlServer.Server; namespace System.Data.SqlClient { internal sealed class MetaType { internal readonly Type ClassType; // com+ type internal readonly Type SqlType; internal readonly int FixedLength; // fixed length size in bytes (-1 for variable) internal readonly bool IsFixed; // true if fixed length, note that sqlchar and sqlbinary are not considered fixed length internal readonly bool IsLong; // true if long internal readonly bool IsPlp; // Column is Partially Length Prefixed (MAX) internal readonly byte Precision; // maximum precision for numeric types internal readonly byte Scale; internal readonly byte TDSType; internal readonly byte NullableType; internal readonly string TypeName; // string name of this type internal readonly SqlDbType SqlDbType; internal readonly DbType DbType; // holds count of property bytes expected for a SQLVariant structure internal readonly byte PropBytes; // pre-computed fields internal readonly bool IsAnsiType; internal readonly bool IsBinType; internal readonly bool IsCharType; internal readonly bool IsNCharType; internal readonly bool IsSizeInCharacters; internal readonly bool IsNewKatmaiType; internal readonly bool IsVarTime; internal readonly bool Is70Supported; internal readonly bool Is80Supported; internal readonly bool Is90Supported; internal readonly bool Is100Supported; public MetaType(byte precision, byte scale, int fixedLength, bool isFixed, bool isLong, bool isPlp, byte tdsType, byte nullableTdsType, string typeName, Type classType, Type sqlType, SqlDbType sqldbType, DbType dbType, byte propBytes) { this.Precision = precision; this.Scale = scale; this.FixedLength = fixedLength; this.IsFixed = isFixed; this.IsLong = isLong; this.IsPlp = isPlp; this.TDSType = tdsType; this.NullableType = nullableTdsType; this.TypeName = typeName; this.SqlDbType = sqldbType; this.DbType = dbType; this.ClassType = classType; this.SqlType = sqlType; this.PropBytes = propBytes; IsAnsiType = _IsAnsiType(sqldbType); IsBinType = _IsBinType(sqldbType); IsCharType = _IsCharType(sqldbType); IsNCharType = _IsNCharType(sqldbType); IsSizeInCharacters = _IsSizeInCharacters(sqldbType); IsNewKatmaiType = _IsNewKatmaiType(sqldbType); IsVarTime = _IsVarTime(sqldbType); Is70Supported = _Is70Supported(SqlDbType); Is80Supported = _Is80Supported(SqlDbType); Is90Supported = _Is90Supported(SqlDbType); Is100Supported = _Is100Supported(SqlDbType); } // properties should be inlined so there should be no perf penalty for using these accessor functions public int TypeId { // partial length prefixed (xml, nvarchar(max),...) get { return 0; } } private static bool _IsAnsiType(SqlDbType type) { return (type == SqlDbType.Char || type == SqlDbType.VarChar || type == SqlDbType.Text); } // is this type size expressed as count of characters or bytes? private static bool _IsSizeInCharacters(SqlDbType type) { return (type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.Xml || type == SqlDbType.NText); } private static bool _IsCharType(SqlDbType type) { return (type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.NText || type == SqlDbType.Char || type == SqlDbType.VarChar || type == SqlDbType.Text || type == SqlDbType.Xml); } private static bool _IsNCharType(SqlDbType type) { return (type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.NText || type == SqlDbType.Xml); } private static bool _IsBinType(SqlDbType type) { return (type == SqlDbType.Image || type == SqlDbType.Binary || type == SqlDbType.VarBinary || type == SqlDbType.Timestamp || type == SqlDbType.Udt || (int)type == 24 /*SqlSmallVarBinary*/); } private static bool _Is70Supported(SqlDbType type) { return ((type != SqlDbType.BigInt) && ((int)type > 0) && ((int)type <= (int)SqlDbType.VarChar)); } private static bool _Is80Supported(SqlDbType type) { return ((int)type >= 0 && ((int)type <= (int)SqlDbType.Variant)); } private static bool _Is90Supported(SqlDbType type) { return _Is80Supported(type) || SqlDbType.Xml == type || SqlDbType.Udt == type; } private static bool _Is100Supported(SqlDbType type) { return _Is90Supported(type) || SqlDbType.Date == type || SqlDbType.Time == type || SqlDbType.DateTime2 == type || SqlDbType.DateTimeOffset == type; } private static bool _IsNewKatmaiType(SqlDbType type) { return SqlDbType.Structured == type; } internal static bool _IsVarTime(SqlDbType type) { return (type == SqlDbType.Time || type == SqlDbType.DateTime2 || type == SqlDbType.DateTimeOffset); } // // map SqlDbType to MetaType class // internal static MetaType GetMetaTypeFromSqlDbType(SqlDbType target, bool isMultiValued) { // WebData 113289 switch (target) { case SqlDbType.BigInt: return s_metaBigInt; case SqlDbType.Binary: return s_metaBinary; case SqlDbType.Bit: return s_metaBit; case SqlDbType.Char: return s_metaChar; case SqlDbType.DateTime: return s_metaDateTime; case SqlDbType.Decimal: return MetaDecimal; case SqlDbType.Float: return s_metaFloat; case SqlDbType.Image: return MetaImage; case SqlDbType.Int: return s_metaInt; case SqlDbType.Money: return s_metaMoney; case SqlDbType.NChar: return s_metaNChar; case SqlDbType.NText: return MetaNText; case SqlDbType.NVarChar: return MetaNVarChar; case SqlDbType.Real: return s_metaReal; case SqlDbType.UniqueIdentifier: return s_metaUniqueId; case SqlDbType.SmallDateTime: return s_metaSmallDateTime; case SqlDbType.SmallInt: return s_metaSmallInt; case SqlDbType.SmallMoney: return s_metaSmallMoney; case SqlDbType.Text: return MetaText; case SqlDbType.Timestamp: return s_metaTimestamp; case SqlDbType.TinyInt: return s_metaTinyInt; case SqlDbType.VarBinary: return MetaVarBinary; case SqlDbType.VarChar: return s_metaVarChar; case SqlDbType.Variant: return s_metaVariant; case (SqlDbType)TdsEnums.SmallVarBinary: return s_metaSmallVarBinary; case SqlDbType.Xml: return MetaXml; case SqlDbType.Udt: return MetaUdt; case SqlDbType.Structured: if (isMultiValued) { return s_metaTable; } else { return s_metaSUDT; } case SqlDbType.Date: return s_metaDate; case SqlDbType.Time: return MetaTime; case SqlDbType.DateTime2: return s_metaDateTime2; case SqlDbType.DateTimeOffset: return MetaDateTimeOffset; default: throw SQL.InvalidSqlDbType(target); } } // // map DbType to MetaType class // internal static MetaType GetMetaTypeFromDbType(DbType target) { // if we can't map it, we need to throw switch (target) { case DbType.AnsiString: return s_metaVarChar; case DbType.AnsiStringFixedLength: return s_metaChar; case DbType.Binary: return MetaVarBinary; case DbType.Byte: return s_metaTinyInt; case DbType.Boolean: return s_metaBit; case DbType.Currency: return s_metaMoney; case DbType.Date: case DbType.DateTime: return s_metaDateTime; case DbType.Decimal: return MetaDecimal; case DbType.Double: return s_metaFloat; case DbType.Guid: return s_metaUniqueId; case DbType.Int16: return s_metaSmallInt; case DbType.Int32: return s_metaInt; case DbType.Int64: return s_metaBigInt; case DbType.Object: return s_metaVariant; case DbType.Single: return s_metaReal; case DbType.String: return MetaNVarChar; case DbType.StringFixedLength: return s_metaNChar; case DbType.Time: return s_metaDateTime; case DbType.Xml: return MetaXml; case DbType.DateTime2: return s_metaDateTime2; case DbType.DateTimeOffset: return MetaDateTimeOffset; case DbType.SByte: // unsupported case DbType.UInt16: case DbType.UInt32: case DbType.UInt64: case DbType.VarNumeric: default: throw ADP.DbTypeNotSupported(target, typeof(SqlDbType)); // no direct mapping, error out } } internal static MetaType GetMaxMetaTypeFromMetaType(MetaType mt) { // if we can't map it, we need to throw switch (mt.SqlDbType) { case SqlDbType.VarBinary: case SqlDbType.Binary: return MetaMaxVarBinary; case SqlDbType.VarChar: case SqlDbType.Char: return MetaMaxVarChar; case SqlDbType.NVarChar: case SqlDbType.NChar: return MetaMaxNVarChar; case SqlDbType.Udt: return s_metaMaxUdt; default: return mt; } } // // map COM+ Type to MetaType class // internal static MetaType GetMetaTypeFromType(Type dataType) { return GetMetaTypeFromValue(dataType, null, false, true); } internal static MetaType GetMetaTypeFromValue(object value, bool streamAllowed = true) { return GetMetaTypeFromValue(value.GetType(), value, true, streamAllowed); } private static MetaType GetMetaTypeFromValue(Type dataType, object value, bool inferLen, bool streamAllowed) { switch (Type.GetTypeCode(dataType)) { case TypeCode.Empty: throw ADP.InvalidDataType(TypeCode.Empty); case TypeCode.Object: if (dataType == typeof(System.Byte[])) { // Must not default to image if inferLen is false if (!inferLen || ((byte[])value).Length <= TdsEnums.TYPE_SIZE_LIMIT) { return MetaVarBinary; } else { return MetaImage; } } else if (dataType == typeof(System.Guid)) { return s_metaUniqueId; } else if (dataType == typeof(System.Object)) { return s_metaVariant; } // check sql types now else if (dataType == typeof(SqlBinary)) return MetaVarBinary; else if (dataType == typeof(SqlBoolean)) return s_metaBit; else if (dataType == typeof(SqlByte)) return s_metaTinyInt; else if (dataType == typeof(SqlBytes)) return MetaVarBinary; else if (dataType == typeof(SqlChars)) return MetaNVarChar; else if (dataType == typeof(SqlDateTime)) return s_metaDateTime; else if (dataType == typeof(SqlDouble)) return s_metaFloat; else if (dataType == typeof(SqlGuid)) return s_metaUniqueId; else if (dataType == typeof(SqlInt16)) return s_metaSmallInt; else if (dataType == typeof(SqlInt32)) return s_metaInt; else if (dataType == typeof(SqlInt64)) return s_metaBigInt; else if (dataType == typeof(SqlMoney)) return s_metaMoney; else if (dataType == typeof(SqlDecimal)) return MetaDecimal; else if (dataType == typeof(SqlSingle)) return s_metaReal; else if (dataType == typeof(SqlXml)) return MetaXml; else if (dataType == typeof(SqlString)) { return ((inferLen && !((SqlString)value).IsNull) ? PromoteStringType(((SqlString)value).Value) : MetaNVarChar); } else if (dataType == typeof(IEnumerable<DbDataRecord>) || dataType == typeof(DataTable)) { return s_metaTable; } else if (dataType == typeof(TimeSpan)) { return MetaTime; } else if (dataType == typeof(DateTimeOffset)) { return MetaDateTimeOffset; } else { // UDT ? SqlUdtInfo attribs = SqlUdtInfo.TryGetFromType(dataType); if (attribs != null) { return MetaUdt; } if (streamAllowed) { // Derived from Stream ? if (typeof(Stream).IsAssignableFrom(dataType)) { return MetaVarBinary; } // Derived from TextReader ? else if (typeof(TextReader).IsAssignableFrom(dataType)) { return MetaNVarChar; } // Derived from XmlReader ? else if (typeof(System.Xml.XmlReader).IsAssignableFrom(dataType)) { return MetaXml; } } } throw ADP.UnknownDataType(dataType); case TypeCode.DBNull: throw ADP.InvalidDataType(TypeCode.DBNull); case TypeCode.Boolean: return s_metaBit; case TypeCode.Char: throw ADP.InvalidDataType(TypeCode.Char); case TypeCode.SByte: throw ADP.InvalidDataType(TypeCode.SByte); case TypeCode.Byte: return s_metaTinyInt; case TypeCode.Int16: return s_metaSmallInt; case TypeCode.UInt16: throw ADP.InvalidDataType(TypeCode.UInt16); case TypeCode.Int32: return s_metaInt; case TypeCode.UInt32: throw ADP.InvalidDataType(TypeCode.UInt32); case TypeCode.Int64: return s_metaBigInt; case TypeCode.UInt64: throw ADP.InvalidDataType(TypeCode.UInt64); case TypeCode.Single: return s_metaReal; case TypeCode.Double: return s_metaFloat; case TypeCode.Decimal: return MetaDecimal; case TypeCode.DateTime: return s_metaDateTime; case TypeCode.String: return (inferLen ? PromoteStringType((string)value) : MetaNVarChar); default: throw ADP.UnknownDataTypeCode(dataType, Type.GetTypeCode(dataType)); } } internal static object GetNullSqlValue(Type sqlType) { if (sqlType == typeof(SqlSingle)) return SqlSingle.Null; else if (sqlType == typeof(SqlString)) return SqlString.Null; else if (sqlType == typeof(SqlDouble)) return SqlDouble.Null; else if (sqlType == typeof(SqlBinary)) return SqlBinary.Null; else if (sqlType == typeof(SqlGuid)) return SqlGuid.Null; else if (sqlType == typeof(SqlBoolean)) return SqlBoolean.Null; else if (sqlType == typeof(SqlByte)) return SqlByte.Null; else if (sqlType == typeof(SqlInt16)) return SqlInt16.Null; else if (sqlType == typeof(SqlInt32)) return SqlInt32.Null; else if (sqlType == typeof(SqlInt64)) return SqlInt64.Null; else if (sqlType == typeof(SqlDecimal)) return SqlDecimal.Null; else if (sqlType == typeof(SqlDateTime)) return SqlDateTime.Null; else if (sqlType == typeof(SqlMoney)) return SqlMoney.Null; else if (sqlType == typeof(SqlXml)) return SqlXml.Null; else if (sqlType == typeof(object)) return DBNull.Value; else if (sqlType == typeof(IEnumerable<DbDataRecord>)) return DBNull.Value; else if (sqlType == typeof(DataTable)) return DBNull.Value; else if (sqlType == typeof(DateTime)) return DBNull.Value; else if (sqlType == typeof(TimeSpan)) return DBNull.Value; else if (sqlType == typeof(DateTimeOffset)) return DBNull.Value; else { Debug.Fail("Unknown SqlType!"); return DBNull.Value; } } internal static MetaType PromoteStringType(string s) { int len = s.Length; if ((len << 1) > TdsEnums.TYPE_SIZE_LIMIT) { return s_metaVarChar; // try as var char since we can send a 8K characters } return MetaNVarChar; // send 4k chars, but send as unicode } internal static object GetComValueFromSqlVariant(object sqlVal) { object comVal = null; if (ADP.IsNull(sqlVal)) return comVal; if (sqlVal is SqlSingle) comVal = ((SqlSingle)sqlVal).Value; else if (sqlVal is SqlString) comVal = ((SqlString)sqlVal).Value; else if (sqlVal is SqlDouble) comVal = ((SqlDouble)sqlVal).Value; else if (sqlVal is SqlBinary) comVal = ((SqlBinary)sqlVal).Value; else if (sqlVal is SqlGuid) comVal = ((SqlGuid)sqlVal).Value; else if (sqlVal is SqlBoolean) comVal = ((SqlBoolean)sqlVal).Value; else if (sqlVal is SqlByte) comVal = ((SqlByte)sqlVal).Value; else if (sqlVal is SqlInt16) comVal = ((SqlInt16)sqlVal).Value; else if (sqlVal is SqlInt32) comVal = ((SqlInt32)sqlVal).Value; else if (sqlVal is SqlInt64) comVal = ((SqlInt64)sqlVal).Value; else if (sqlVal is SqlDecimal) comVal = ((SqlDecimal)sqlVal).Value; else if (sqlVal is SqlDateTime) comVal = ((SqlDateTime)sqlVal).Value; else if (sqlVal is SqlMoney) comVal = ((SqlMoney)sqlVal).Value; else if (sqlVal is SqlXml) comVal = ((SqlXml)sqlVal).Value; else { AssertIsUserDefinedTypeInstance(sqlVal, "unknown SqlType class stored in sqlVal"); } return comVal; } /// <summary> /// Assert that the supplied object is an instance of a SQL User-Defined Type (UDT). /// </summary> /// <param name="sqlValue">Object instance to be tested.</param> /// <remarks> /// This method is only compiled with debug builds, and it a helper method for the GetComValueFromSqlVariant method defined in this class. /// /// The presence of the SqlUserDefinedTypeAttribute on the object's type /// is used to determine if the object is a UDT instance (if present it is a UDT, else it is not). /// </remarks> /// <exception cref="NullReferenceException"> /// If sqlValue is null. Callers must ensure the object is non-null. /// </exception> [Conditional("DEBUG")] private static void AssertIsUserDefinedTypeInstance(object sqlValue, string failedAssertMessage) { Type type = sqlValue.GetType(); Microsoft.SqlServer.Server.SqlUserDefinedTypeAttribute[] attributes = (Microsoft.SqlServer.Server.SqlUserDefinedTypeAttribute[])type.GetCustomAttributes(typeof(Microsoft.SqlServer.Server.SqlUserDefinedTypeAttribute), true); Debug.Assert(attributes.Length > 0, failedAssertMessage); } // devnote: This method should not be used with SqlDbType.Date and SqlDbType.DateTime2. // With these types the values should be used directly as CLR types instead of being converted to a SqlValue internal static object GetSqlValueFromComVariant(object comVal) { object sqlVal = null; if ((null != comVal) && (DBNull.Value != comVal)) { if (comVal is float) sqlVal = new SqlSingle((float)comVal); else if (comVal is string) sqlVal = new SqlString((string)comVal); else if (comVal is double) sqlVal = new SqlDouble((double)comVal); else if (comVal is System.Byte[]) sqlVal = new SqlBinary((byte[])comVal); else if (comVal is System.Char) sqlVal = new SqlString(((char)comVal).ToString()); else if (comVal is System.Char[]) sqlVal = new SqlChars((System.Char[])comVal); else if (comVal is System.Guid) sqlVal = new SqlGuid((Guid)comVal); else if (comVal is bool) sqlVal = new SqlBoolean((bool)comVal); else if (comVal is byte) sqlVal = new SqlByte((byte)comVal); else if (comVal is Int16) sqlVal = new SqlInt16((Int16)comVal); else if (comVal is Int32) sqlVal = new SqlInt32((Int32)comVal); else if (comVal is Int64) sqlVal = new SqlInt64((Int64)comVal); else if (comVal is Decimal) sqlVal = new SqlDecimal((Decimal)comVal); else if (comVal is DateTime) { // devnote: Do not use with SqlDbType.Date and SqlDbType.DateTime2. See comment at top of method. sqlVal = new SqlDateTime((DateTime)comVal); } else if (comVal is XmlReader) sqlVal = new SqlXml((XmlReader)comVal); else if (comVal is TimeSpan || comVal is DateTimeOffset) sqlVal = comVal; #if DEBUG else Debug.Fail("unknown SqlType class stored in sqlVal"); #endif } return sqlVal; } internal static SqlDbType GetSqlDbTypeFromOleDbType(short dbType, string typeName) { // OleDbTypes not supported return SqlDbType.Variant; } internal static MetaType GetSqlDataType(int tdsType, UInt32 userType, int length) { switch (tdsType) { case TdsEnums.SQLMONEYN: return ((4 == length) ? s_metaSmallMoney : s_metaMoney); case TdsEnums.SQLDATETIMN: return ((4 == length) ? s_metaSmallDateTime : s_metaDateTime); case TdsEnums.SQLINTN: return ((4 <= length) ? ((4 == length) ? s_metaInt : s_metaBigInt) : ((2 == length) ? s_metaSmallInt : s_metaTinyInt)); case TdsEnums.SQLFLTN: return ((4 == length) ? s_metaReal : s_metaFloat); case TdsEnums.SQLTEXT: return MetaText; case TdsEnums.SQLVARBINARY: return s_metaSmallVarBinary; case TdsEnums.SQLBIGVARBINARY: return MetaVarBinary; case TdsEnums.SQLVARCHAR: case TdsEnums.SQLBIGVARCHAR: return s_metaVarChar; case TdsEnums.SQLBINARY: case TdsEnums.SQLBIGBINARY: return ((TdsEnums.SQLTIMESTAMP == userType) ? s_metaTimestamp : s_metaBinary); case TdsEnums.SQLIMAGE: return MetaImage; case TdsEnums.SQLCHAR: case TdsEnums.SQLBIGCHAR: return s_metaChar; case TdsEnums.SQLINT1: return s_metaTinyInt; case TdsEnums.SQLBIT: case TdsEnums.SQLBITN: return s_metaBit; case TdsEnums.SQLINT2: return s_metaSmallInt; case TdsEnums.SQLINT4: return s_metaInt; case TdsEnums.SQLINT8: return s_metaBigInt; case TdsEnums.SQLMONEY: return s_metaMoney; case TdsEnums.SQLDATETIME: return s_metaDateTime; case TdsEnums.SQLFLT8: return s_metaFloat; case TdsEnums.SQLFLT4: return s_metaReal; case TdsEnums.SQLMONEY4: return s_metaSmallMoney; case TdsEnums.SQLDATETIM4: return s_metaSmallDateTime; case TdsEnums.SQLDECIMALN: case TdsEnums.SQLNUMERICN: return MetaDecimal; case TdsEnums.SQLUNIQUEID: return s_metaUniqueId; case TdsEnums.SQLNCHAR: return s_metaNChar; case TdsEnums.SQLNVARCHAR: return MetaNVarChar; case TdsEnums.SQLNTEXT: return MetaNText; case TdsEnums.SQLVARIANT: return s_metaVariant; case TdsEnums.SQLUDT: return MetaUdt; case TdsEnums.SQLXMLTYPE: return MetaXml; case TdsEnums.SQLTABLE: return s_metaTable; case TdsEnums.SQLDATE: return s_metaDate; case TdsEnums.SQLTIME: return MetaTime; case TdsEnums.SQLDATETIME2: return s_metaDateTime2; case TdsEnums.SQLDATETIMEOFFSET: return MetaDateTimeOffset; case TdsEnums.SQLVOID: default: Debug.Fail("Unknown type " + tdsType.ToString(CultureInfo.InvariantCulture)); throw SQL.InvalidSqlDbType((SqlDbType)tdsType); } } internal static MetaType GetDefaultMetaType() { return MetaNVarChar; } // Converts an XmlReader into String internal static String GetStringFromXml(XmlReader xmlreader) { SqlXml sxml = new SqlXml(xmlreader); return sxml.Value; } private static readonly MetaType s_metaBigInt = new MetaType (19, 255, 8, true, false, false, TdsEnums.SQLINT8, TdsEnums.SQLINTN, MetaTypeName.BIGINT, typeof(System.Int64), typeof(SqlInt64), SqlDbType.BigInt, DbType.Int64, 0); private static readonly MetaType s_metaFloat = new MetaType (15, 255, 8, true, false, false, TdsEnums.SQLFLT8, TdsEnums.SQLFLTN, MetaTypeName.FLOAT, typeof(System.Double), typeof(SqlDouble), SqlDbType.Float, DbType.Double, 0); private static readonly MetaType s_metaReal = new MetaType (7, 255, 4, true, false, false, TdsEnums.SQLFLT4, TdsEnums.SQLFLTN, MetaTypeName.REAL, typeof(System.Single), typeof(SqlSingle), SqlDbType.Real, DbType.Single, 0); // MetaBinary has two bytes of properties for binary and varbinary // 2 byte maxlen private static readonly MetaType s_metaBinary = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGBINARY, TdsEnums.SQLBIGBINARY, MetaTypeName.BINARY, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.Binary, DbType.Binary, 2); // Syntactic sugar for the user...timestamps are 8-byte fixed length binary columns private static readonly MetaType s_metaTimestamp = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGBINARY, TdsEnums.SQLBIGBINARY, MetaTypeName.TIMESTAMP, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.Timestamp, DbType.Binary, 2); internal static readonly MetaType MetaVarBinary = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGVARBINARY, TdsEnums.SQLBIGVARBINARY, MetaTypeName.VARBINARY, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.VarBinary, DbType.Binary, 2); internal static readonly MetaType MetaMaxVarBinary = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLBIGVARBINARY, TdsEnums.SQLBIGVARBINARY, MetaTypeName.VARBINARY, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.VarBinary, DbType.Binary, 2); // We have an internal type for smallvarbinarys stored on TdsEnums. We // store on TdsEnums instead of SqlDbType because we do not want to expose // this type to the user. private static readonly MetaType s_metaSmallVarBinary = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLVARBINARY, TdsEnums.SQLBIGBINARY, ADP.StrEmpty, typeof(System.Byte[]), typeof(SqlBinary), TdsEnums.SmallVarBinary, DbType.Binary, 2); internal static readonly MetaType MetaImage = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLIMAGE, TdsEnums.SQLIMAGE, MetaTypeName.IMAGE, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.Image, DbType.Binary, 0); private static readonly MetaType s_metaBit = new MetaType (255, 255, 1, true, false, false, TdsEnums.SQLBIT, TdsEnums.SQLBITN, MetaTypeName.BIT, typeof(System.Boolean), typeof(SqlBoolean), SqlDbType.Bit, DbType.Boolean, 0); private static readonly MetaType s_metaTinyInt = new MetaType (3, 255, 1, true, false, false, TdsEnums.SQLINT1, TdsEnums.SQLINTN, MetaTypeName.TINYINT, typeof(System.Byte), typeof(SqlByte), SqlDbType.TinyInt, DbType.Byte, 0); private static readonly MetaType s_metaSmallInt = new MetaType (5, 255, 2, true, false, false, TdsEnums.SQLINT2, TdsEnums.SQLINTN, MetaTypeName.SMALLINT, typeof(System.Int16), typeof(SqlInt16), SqlDbType.SmallInt, DbType.Int16, 0); private static readonly MetaType s_metaInt = new MetaType (10, 255, 4, true, false, false, TdsEnums.SQLINT4, TdsEnums.SQLINTN, MetaTypeName.INT, typeof(System.Int32), typeof(SqlInt32), SqlDbType.Int, DbType.Int32, 0); // MetaVariant has seven bytes of properties for MetaChar and MetaVarChar // 5 byte tds collation // 2 byte maxlen private static readonly MetaType s_metaChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGCHAR, TdsEnums.SQLBIGCHAR, MetaTypeName.CHAR, typeof(System.String), typeof(SqlString), SqlDbType.Char, DbType.AnsiStringFixedLength, 7); private static readonly MetaType s_metaVarChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGVARCHAR, TdsEnums.SQLBIGVARCHAR, MetaTypeName.VARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.VarChar, DbType.AnsiString, 7); internal static readonly MetaType MetaMaxVarChar = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLBIGVARCHAR, TdsEnums.SQLBIGVARCHAR, MetaTypeName.VARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.VarChar, DbType.AnsiString, 7); internal static readonly MetaType MetaText = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLTEXT, TdsEnums.SQLTEXT, MetaTypeName.TEXT, typeof(System.String), typeof(SqlString), SqlDbType.Text, DbType.AnsiString, 0); // MetaVariant has seven bytes of properties for MetaNChar and MetaNVarChar // 5 byte tds collation // 2 byte maxlen private static readonly MetaType s_metaNChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLNCHAR, TdsEnums.SQLNCHAR, MetaTypeName.NCHAR, typeof(System.String), typeof(SqlString), SqlDbType.NChar, DbType.StringFixedLength, 7); internal static readonly MetaType MetaNVarChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLNVARCHAR, TdsEnums.SQLNVARCHAR, MetaTypeName.NVARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.NVarChar, DbType.String, 7); internal static readonly MetaType MetaMaxNVarChar = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLNVARCHAR, TdsEnums.SQLNVARCHAR, MetaTypeName.NVARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.NVarChar, DbType.String, 7); internal static readonly MetaType MetaNText = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLNTEXT, TdsEnums.SQLNTEXT, MetaTypeName.NTEXT, typeof(System.String), typeof(SqlString), SqlDbType.NText, DbType.String, 7); // MetaVariant has two bytes of properties for numeric/decimal types // 1 byte precision // 1 byte scale internal static readonly MetaType MetaDecimal = new MetaType (38, 4, 17, true, false, false, TdsEnums.SQLNUMERICN, TdsEnums.SQLNUMERICN, MetaTypeName.DECIMAL, typeof(System.Decimal), typeof(SqlDecimal), SqlDbType.Decimal, DbType.Decimal, 2); internal static readonly MetaType MetaXml = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLXMLTYPE, TdsEnums.SQLXMLTYPE, MetaTypeName.XML, typeof(System.String), typeof(SqlXml), SqlDbType.Xml, DbType.Xml, 0); private static readonly MetaType s_metaDateTime = new MetaType (23, 3, 8, true, false, false, TdsEnums.SQLDATETIME, TdsEnums.SQLDATETIMN, MetaTypeName.DATETIME, typeof(System.DateTime), typeof(SqlDateTime), SqlDbType.DateTime, DbType.DateTime, 0); private static readonly MetaType s_metaSmallDateTime = new MetaType (16, 0, 4, true, false, false, TdsEnums.SQLDATETIM4, TdsEnums.SQLDATETIMN, MetaTypeName.SMALLDATETIME, typeof(System.DateTime), typeof(SqlDateTime), SqlDbType.SmallDateTime, DbType.DateTime, 0); private static readonly MetaType s_metaMoney = new MetaType (19, 255, 8, true, false, false, TdsEnums.SQLMONEY, TdsEnums.SQLMONEYN, MetaTypeName.MONEY, typeof(System.Decimal), typeof(SqlMoney), SqlDbType.Money, DbType.Currency, 0); private static readonly MetaType s_metaSmallMoney = new MetaType (10, 255, 4, true, false, false, TdsEnums.SQLMONEY4, TdsEnums.SQLMONEYN, MetaTypeName.SMALLMONEY, typeof(System.Decimal), typeof(SqlMoney), SqlDbType.SmallMoney, DbType.Currency, 0); private static readonly MetaType s_metaUniqueId = new MetaType (255, 255, 16, true, false, false, TdsEnums.SQLUNIQUEID, TdsEnums.SQLUNIQUEID, MetaTypeName.ROWGUID, typeof(System.Guid), typeof(SqlGuid), SqlDbType.UniqueIdentifier, DbType.Guid, 0); private static readonly MetaType s_metaVariant = new MetaType (255, 255, -1, true, false, false, TdsEnums.SQLVARIANT, TdsEnums.SQLVARIANT, MetaTypeName.VARIANT, typeof(System.Object), typeof(System.Object), SqlDbType.Variant, DbType.Object, 0); internal static readonly MetaType MetaUdt = new MetaType (255, 255, -1, false, false, true, TdsEnums.SQLUDT, TdsEnums.SQLUDT, MetaTypeName.UDT, typeof(System.Object), typeof(System.Object), SqlDbType.Udt, DbType.Object, 0); private static readonly MetaType s_metaMaxUdt = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLUDT, TdsEnums.SQLUDT, MetaTypeName.UDT, typeof(System.Object), typeof(System.Object), SqlDbType.Udt, DbType.Object, 0); private static readonly MetaType s_metaTable = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLTABLE, TdsEnums.SQLTABLE, MetaTypeName.TABLE, typeof(IEnumerable<DbDataRecord>), typeof(IEnumerable<DbDataRecord>), SqlDbType.Structured, DbType.Object, 0); private static readonly MetaType s_metaSUDT = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLVOID, TdsEnums.SQLVOID, "", typeof(MSS.SqlDataRecord), typeof(MSS.SqlDataRecord), SqlDbType.Structured, DbType.Object, 0); private static readonly MetaType s_metaDate = new MetaType (255, 255, 3, true, false, false, TdsEnums.SQLDATE, TdsEnums.SQLDATE, MetaTypeName.DATE, typeof(System.DateTime), typeof(System.DateTime), SqlDbType.Date, DbType.Date, 0); internal static readonly MetaType MetaTime = new MetaType (255, 7, -1, false, false, false, TdsEnums.SQLTIME, TdsEnums.SQLTIME, MetaTypeName.TIME, typeof(System.TimeSpan), typeof(System.TimeSpan), SqlDbType.Time, DbType.Time, 1); private static readonly MetaType s_metaDateTime2 = new MetaType (255, 7, -1, false, false, false, TdsEnums.SQLDATETIME2, TdsEnums.SQLDATETIME2, MetaTypeName.DATETIME2, typeof(System.DateTime), typeof(System.DateTime), SqlDbType.DateTime2, DbType.DateTime2, 1); internal static readonly MetaType MetaDateTimeOffset = new MetaType (255, 7, -1, false, false, false, TdsEnums.SQLDATETIMEOFFSET, TdsEnums.SQLDATETIMEOFFSET, MetaTypeName.DATETIMEOFFSET, typeof(System.DateTimeOffset), typeof(System.DateTimeOffset), SqlDbType.DateTimeOffset, DbType.DateTimeOffset, 1); public static TdsDateTime FromDateTime(DateTime dateTime, byte cb) { SqlDateTime sqlDateTime; TdsDateTime tdsDateTime = new TdsDateTime(); Debug.Assert(cb == 8 || cb == 4, "Invalid date time size!"); if (cb == 8) { sqlDateTime = new SqlDateTime(dateTime); tdsDateTime.time = sqlDateTime.TimeTicks; } else { // note that smalldatetime is days & minutes. // Adding 30 seconds ensures proper roundup if the seconds are >= 30 // The AddSeconds function handles eventual carryover sqlDateTime = new SqlDateTime(dateTime.AddSeconds(30)); tdsDateTime.time = sqlDateTime.TimeTicks / SqlDateTime.SQLTicksPerMinute; } tdsDateTime.days = sqlDateTime.DayTicks; return tdsDateTime; } public static DateTime ToDateTime(int sqlDays, int sqlTime, int length) { if (length == 4) { return new SqlDateTime(sqlDays, sqlTime * SqlDateTime.SQLTicksPerMinute).Value; } else { Debug.Assert(length == 8, "invalid length for DateTime"); return new SqlDateTime(sqlDays, sqlTime).Value; } } internal static int GetTimeSizeFromScale(byte scale) { if (scale <= 2) return 3; if (scale <= 4) return 4; return 5; } // // please leave string sorted alphabetically // note that these names should only be used in the context of parameters. We always send over BIG* and nullable types for SQL Server // private static class MetaTypeName { public const string BIGINT = "bigint"; public const string BINARY = "binary"; public const string BIT = "bit"; public const string CHAR = "char"; public const string DATETIME = "datetime"; public const string DECIMAL = "decimal"; public const string FLOAT = "float"; public const string IMAGE = "image"; public const string INT = "int"; public const string MONEY = "money"; public const string NCHAR = "nchar"; public const string NTEXT = "ntext"; public const string NVARCHAR = "nvarchar"; public const string REAL = "real"; public const string ROWGUID = "uniqueidentifier"; public const string SMALLDATETIME = "smalldatetime"; public const string SMALLINT = "smallint"; public const string SMALLMONEY = "smallmoney"; public const string TEXT = "text"; public const string TIMESTAMP = "timestamp"; public const string TINYINT = "tinyint"; public const string UDT = "udt"; public const string VARBINARY = "varbinary"; public const string VARCHAR = "varchar"; public const string VARIANT = "sql_variant"; public const string XML = "xml"; public const string TABLE = "table"; public const string DATE = "date"; public const string TIME = "time"; public const string DATETIME2 = "datetime2"; public const string DATETIMEOFFSET = "datetimeoffset"; } } // // note: it is the client's responsibility to know what size date time he is working with // internal struct TdsDateTime { public int days; // offset in days from 1/1/1900 // private UInt32 time; // if smalldatetime, this is # of minutes since midnight // otherwise: # of 1/300th of a second since midnight public int time; } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gagr = Google.Api.Gax.ResourceNames; using gcfv = Google.Cloud.Filestore.V1; using sys = System; namespace Google.Cloud.Filestore.V1 { /// <summary>Resource name for the <c>Instance</c> resource.</summary> public sealed partial class InstanceName : gax::IResourceName, sys::IEquatable<InstanceName> { /// <summary>The possible contents of <see cref="InstanceName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </summary> ProjectLocationInstance = 1, } private static gax::PathTemplate s_projectLocationInstance = new gax::PathTemplate("projects/{project}/locations/{location}/instances/{instance}"); /// <summary>Creates a <see cref="InstanceName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="InstanceName"/> containing the provided <paramref name="unparsedResourceName"/> /// . /// </returns> public static InstanceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new InstanceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="InstanceName"/> with the pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="InstanceName"/> constructed from the provided ids.</returns> public static InstanceName FromProjectLocationInstance(string projectId, string locationId, string instanceId) => new InstanceName(ResourceNameType.ProjectLocationInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="InstanceName"/> with pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="InstanceName"/> with pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </returns> public static string Format(string projectId, string locationId, string instanceId) => FormatProjectLocationInstance(projectId, locationId, instanceId); /// <summary> /// Formats the IDs into the string representation of this <see cref="InstanceName"/> with pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="InstanceName"/> with pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c>. /// </returns> public static string FormatProjectLocationInstance(string projectId, string locationId, string instanceId) => s_projectLocationInstance.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId))); /// <summary>Parses the given resource name string into a new <see cref="InstanceName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item> /// </list> /// </remarks> /// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="InstanceName"/> if successful.</returns> public static InstanceName Parse(string instanceName) => Parse(instanceName, false); /// <summary> /// Parses the given resource name string into a new <see cref="InstanceName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="InstanceName"/> if successful.</returns> public static InstanceName Parse(string instanceName, bool allowUnparsed) => TryParse(instanceName, allowUnparsed, out InstanceName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="InstanceName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item> /// </list> /// </remarks> /// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="InstanceName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string instanceName, out InstanceName result) => TryParse(instanceName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="InstanceName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/instances/{instance}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="InstanceName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string instanceName, bool allowUnparsed, out InstanceName result) { gax::GaxPreconditions.CheckNotNull(instanceName, nameof(instanceName)); gax::TemplatedResourceName resourceName; if (s_projectLocationInstance.TryParseName(instanceName, out resourceName)) { result = FromProjectLocationInstance(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(instanceName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private InstanceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string instanceId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; InstanceId = instanceId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="InstanceName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/instances/{instance}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> public InstanceName(string projectId, string locationId, string instanceId) : this(ResourceNameType.ProjectLocationInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Instance</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string InstanceId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationInstance: return s_projectLocationInstance.Expand(ProjectId, LocationId, InstanceId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as InstanceName); /// <inheritdoc/> public bool Equals(InstanceName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(InstanceName a, InstanceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(InstanceName a, InstanceName b) => !(a == b); } /// <summary>Resource name for the <c>Backup</c> resource.</summary> public sealed partial class BackupName : gax::IResourceName, sys::IEquatable<BackupName> { /// <summary>The possible contents of <see cref="BackupName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/backups/{backup}</c>. /// </summary> ProjectLocationBackup = 1, } private static gax::PathTemplate s_projectLocationBackup = new gax::PathTemplate("projects/{project}/locations/{location}/backups/{backup}"); /// <summary>Creates a <see cref="BackupName"/> 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="BackupName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static BackupName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new BackupName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="BackupName"/> with the pattern /// <c>projects/{project}/locations/{location}/backups/{backup}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="backupId">The <c>Backup</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="BackupName"/> constructed from the provided ids.</returns> public static BackupName FromProjectLocationBackup(string projectId, string locationId, string backupId) => new BackupName(ResourceNameType.ProjectLocationBackup, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), backupId: gax::GaxPreconditions.CheckNotNullOrEmpty(backupId, nameof(backupId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="BackupName"/> with pattern /// <c>projects/{project}/locations/{location}/backups/{backup}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="backupId">The <c>Backup</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="BackupName"/> with pattern /// <c>projects/{project}/locations/{location}/backups/{backup}</c>. /// </returns> public static string Format(string projectId, string locationId, string backupId) => FormatProjectLocationBackup(projectId, locationId, backupId); /// <summary> /// Formats the IDs into the string representation of this <see cref="BackupName"/> with pattern /// <c>projects/{project}/locations/{location}/backups/{backup}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="backupId">The <c>Backup</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="BackupName"/> with pattern /// <c>projects/{project}/locations/{location}/backups/{backup}</c>. /// </returns> public static string FormatProjectLocationBackup(string projectId, string locationId, string backupId) => s_projectLocationBackup.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(backupId, nameof(backupId))); /// <summary>Parses the given resource name string into a new <see cref="BackupName"/> 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}/locations/{location}/backups/{backup}</c></description></item> /// </list> /// </remarks> /// <param name="backupName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="BackupName"/> if successful.</returns> public static BackupName Parse(string backupName) => Parse(backupName, false); /// <summary> /// Parses the given resource name string into a new <see cref="BackupName"/> 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}/locations/{location}/backups/{backup}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="backupName">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="BackupName"/> if successful.</returns> public static BackupName Parse(string backupName, bool allowUnparsed) => TryParse(backupName, allowUnparsed, out BackupName 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="BackupName"/> 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}/locations/{location}/backups/{backup}</c></description></item> /// </list> /// </remarks> /// <param name="backupName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="BackupName"/>, 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 backupName, out BackupName result) => TryParse(backupName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="BackupName"/> 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}/locations/{location}/backups/{backup}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="backupName">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="BackupName"/>, 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 backupName, bool allowUnparsed, out BackupName result) { gax::GaxPreconditions.CheckNotNull(backupName, nameof(backupName)); gax::TemplatedResourceName resourceName; if (s_projectLocationBackup.TryParseName(backupName, out resourceName)) { result = FromProjectLocationBackup(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(backupName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private BackupName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string backupId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; BackupId = backupId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="BackupName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/backups/{backup}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="backupId">The <c>Backup</c> ID. Must not be <c>null</c> or empty.</param> public BackupName(string projectId, string locationId, string backupId) : this(ResourceNameType.ProjectLocationBackup, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), backupId: gax::GaxPreconditions.CheckNotNullOrEmpty(backupId, nameof(backupId))) { } /// <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>Backup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string BackupId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationBackup: return s_projectLocationBackup.Expand(ProjectId, LocationId, BackupId); 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 BackupName); /// <inheritdoc/> public bool Equals(BackupName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(BackupName a, BackupName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(BackupName a, BackupName b) => !(a == b); } public partial class FileShareConfig { /// <summary> /// <see cref="BackupName"/>-typed view over the <see cref="SourceBackup"/> resource name property. /// </summary> public BackupName SourceBackupAsBackupName { get => string.IsNullOrEmpty(SourceBackup) ? null : BackupName.Parse(SourceBackup, allowUnparsed: true); set => SourceBackup = value?.ToString() ?? ""; } } public partial class Instance { /// <summary> /// <see cref="gcfv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcfv::InstanceName InstanceName { get => string.IsNullOrEmpty(Name) ? null : gcfv::InstanceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreateInstanceRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetInstanceRequest { /// <summary> /// <see cref="gcfv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcfv::InstanceName InstanceName { get => string.IsNullOrEmpty(Name) ? null : gcfv::InstanceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class RestoreInstanceRequest { /// <summary> /// <see cref="gcfv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcfv::InstanceName InstanceName { get => string.IsNullOrEmpty(Name) ? null : gcfv::InstanceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="BackupName"/>-typed view over the <see cref="SourceBackup"/> resource name property. /// </summary> public BackupName SourceBackupAsBackupName { get => string.IsNullOrEmpty(SourceBackup) ? null : BackupName.Parse(SourceBackup, allowUnparsed: true); set => SourceBackup = value?.ToString() ?? ""; } } public partial class DeleteInstanceRequest { /// <summary> /// <see cref="gcfv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcfv::InstanceName InstanceName { get => string.IsNullOrEmpty(Name) ? null : gcfv::InstanceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListInstancesRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class Backup { /// <summary> /// <see cref="gcfv::BackupName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcfv::BackupName BackupName { get => string.IsNullOrEmpty(Name) ? null : gcfv::BackupName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="InstanceName"/>-typed view over the <see cref="SourceInstance"/> resource name property. /// </summary> public InstanceName SourceInstanceAsInstanceName { get => string.IsNullOrEmpty(SourceInstance) ? null : InstanceName.Parse(SourceInstance, allowUnparsed: true); set => SourceInstance = value?.ToString() ?? ""; } } public partial class CreateBackupRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class DeleteBackupRequest { /// <summary> /// <see cref="gcfv::BackupName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcfv::BackupName BackupName { get => string.IsNullOrEmpty(Name) ? null : gcfv::BackupName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GetBackupRequest { /// <summary> /// <see cref="gcfv::BackupName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcfv::BackupName BackupName { get => string.IsNullOrEmpty(Name) ? null : gcfv::BackupName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListBackupsRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using Grpc.Core.Internal; using Grpc.Core.Utils; namespace Grpc.Core { /// <summary> /// A collection of metadata entries that can be exchanged during a call. /// gRPC supports these types of metadata: /// <list type="bullet"> /// <item><term>Request headers</term><description>are sent by the client at the beginning of a remote call before any request messages are sent.</description></item> /// <item><term>Response headers</term><description>are sent by the server at the beginning of a remote call handler before any response messages are sent.</description></item> /// <item><term>Response trailers</term><description>are sent by the server at the end of a remote call along with resulting call status.</description></item> /// </list> /// </summary> public sealed class Metadata : IList<Metadata.Entry> { /// <summary> /// All binary headers should have this suffix. /// </summary> public const string BinaryHeaderSuffix = "-bin"; /// <summary> /// An read-only instance of metadata containing no entries. /// </summary> public static readonly Metadata Empty = new Metadata().Freeze(); /// <summary> /// To be used in initial metadata to request specific compression algorithm /// for given call. Direct selection of compression algorithms is an internal /// feature and is not part of public API. /// </summary> internal const string CompressionRequestAlgorithmMetadataKey = "grpc-internal-encoding-request"; readonly List<Entry> entries; bool readOnly; /// <summary> /// Initializes a new instance of <c>Metadata</c>. /// </summary> public Metadata() { this.entries = new List<Entry>(); } /// <summary> /// Makes this object read-only. /// </summary> /// <returns>this object</returns> internal Metadata Freeze() { this.readOnly = true; return this; } // TODO: add support for access by key #region IList members /// <summary> /// <see cref="T:IList`1"/> /// </summary> public int IndexOf(Metadata.Entry item) { return entries.IndexOf(item); } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public void Insert(int index, Metadata.Entry item) { GrpcPreconditions.CheckNotNull(item); CheckWriteable(); entries.Insert(index, item); } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public void RemoveAt(int index) { CheckWriteable(); entries.RemoveAt(index); } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public Metadata.Entry this[int index] { get { return entries[index]; } set { GrpcPreconditions.CheckNotNull(value); CheckWriteable(); entries[index] = value; } } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public void Add(Metadata.Entry item) { GrpcPreconditions.CheckNotNull(item); CheckWriteable(); entries.Add(item); } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public void Add(string key, string value) { Add(new Entry(key, value)); } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public void Add(string key, byte[] valueBytes) { Add(new Entry(key, valueBytes)); } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public void Clear() { CheckWriteable(); entries.Clear(); } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public bool Contains(Metadata.Entry item) { return entries.Contains(item); } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public void CopyTo(Metadata.Entry[] array, int arrayIndex) { entries.CopyTo(array, arrayIndex); } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public int Count { get { return entries.Count; } } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public bool IsReadOnly { get { return readOnly; } } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public bool Remove(Metadata.Entry item) { CheckWriteable(); return entries.Remove(item); } /// <summary> /// <see cref="T:IList`1"/> /// </summary> public IEnumerator<Metadata.Entry> GetEnumerator() { return entries.GetEnumerator(); } IEnumerator System.Collections.IEnumerable.GetEnumerator() { return entries.GetEnumerator(); } private void CheckWriteable() { GrpcPreconditions.CheckState(!readOnly, "Object is read only"); } #endregion /// <summary> /// Metadata entry /// </summary> public class Entry { private static readonly Regex ValidKeyRegex = new Regex("^[a-z0-9_-]+$"); readonly string key; readonly string value; readonly byte[] valueBytes; private Entry(string key, string value, byte[] valueBytes) { this.key = key; this.value = value; this.valueBytes = valueBytes; } /// <summary> /// Initializes a new instance of the <see cref="Grpc.Core.Metadata.Entry"/> struct with a binary value. /// </summary> /// <param name="key">Metadata key, needs to have suffix indicating a binary valued metadata entry.</param> /// <param name="valueBytes">Value bytes.</param> public Entry(string key, byte[] valueBytes) { this.key = NormalizeKey(key); GrpcPreconditions.CheckArgument(HasBinaryHeaderSuffix(this.key), "Key for binary valued metadata entry needs to have suffix indicating binary value."); this.value = null; GrpcPreconditions.CheckNotNull(valueBytes, "valueBytes"); this.valueBytes = new byte[valueBytes.Length]; Buffer.BlockCopy(valueBytes, 0, this.valueBytes, 0, valueBytes.Length); // defensive copy to guarantee immutability } /// <summary> /// Initializes a new instance of the <see cref="Grpc.Core.Metadata.Entry"/> struct holding an ASCII value. /// </summary> /// <param name="key">Metadata key, must not use suffix indicating a binary valued metadata entry.</param> /// <param name="value">Value string. Only ASCII characters are allowed.</param> public Entry(string key, string value) { this.key = NormalizeKey(key); GrpcPreconditions.CheckArgument(!HasBinaryHeaderSuffix(this.key), "Key for ASCII valued metadata entry cannot have suffix indicating binary value."); this.value = GrpcPreconditions.CheckNotNull(value, "value"); this.valueBytes = null; } /// <summary> /// Gets the metadata entry key. /// </summary> public string Key { get { return this.key; } } /// <summary> /// Gets the binary value of this metadata entry. /// </summary> public byte[] ValueBytes { get { if (valueBytes == null) { return MarshalUtils.GetBytesASCII(value); } // defensive copy to guarantee immutability var bytes = new byte[valueBytes.Length]; Buffer.BlockCopy(valueBytes, 0, bytes, 0, valueBytes.Length); return bytes; } } /// <summary> /// Gets the string value of this metadata entry. /// </summary> public string Value { get { GrpcPreconditions.CheckState(!IsBinary, "Cannot access string value of a binary metadata entry"); return value ?? MarshalUtils.GetStringASCII(valueBytes); } } /// <summary> /// Returns <c>true</c> if this entry is a binary-value entry. /// </summary> public bool IsBinary { get { return value == null; } } /// <summary> /// Returns a <see cref="System.String"/> that represents the current <see cref="Grpc.Core.Metadata.Entry"/>. /// </summary> public override string ToString() { if (IsBinary) { return string.Format("[Entry: key={0}, valueBytes={1}]", key, valueBytes); } return string.Format("[Entry: key={0}, value={1}]", key, value); } /// <summary> /// Gets the serialized value for this entry. For binary metadata entries, this leaks /// the internal <c>valueBytes</c> byte array and caller must not change contents of it. /// </summary> internal byte[] GetSerializedValueUnsafe() { return valueBytes ?? MarshalUtils.GetBytesASCII(value); } /// <summary> /// Creates a binary value or ascii value metadata entry from data received from the native layer. /// We trust C core to give us well-formed data, so we don't perform any checks or defensive copying. /// </summary> internal static Entry CreateUnsafe(string key, byte[] valueBytes) { if (HasBinaryHeaderSuffix(key)) { return new Entry(key, null, valueBytes); } return new Entry(key, MarshalUtils.GetStringASCII(valueBytes), null); } private static string NormalizeKey(string key) { var normalized = GrpcPreconditions.CheckNotNull(key, "key").ToLowerInvariant(); GrpcPreconditions.CheckArgument(ValidKeyRegex.IsMatch(normalized), "Metadata entry key not valid. Keys can only contain lowercase alphanumeric characters, underscores and hyphens."); return normalized; } /// <summary> /// Returns <c>true</c> if the key has "-bin" binary header suffix. /// </summary> private static bool HasBinaryHeaderSuffix(string key) { // We don't use just string.EndsWith because its implementation is extremely slow // on CoreCLR and we've seen significant differences in gRPC benchmarks caused by it. // See https://github.com/dotnet/coreclr/issues/5612 int len = key.Length; if (len >= 4 && key[len - 4] == '-' && key[len - 3] == 'b' && key[len - 2] == 'i' && key[len - 1] == 'n') { return true; } return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; using System.Text; internal class Program { private static int Main(string[] args) { Console.WriteLine("this test is designed to hang if jit cse doesnt honor volatile"); if (TestCSE.Test()) return 100; return 1; } } public class TestCSE { private const int VAL1 = 0x404; private const int VAL2 = 0x03; private static volatile bool s_timeUp = false; private volatile int _a; private volatile int _b; private static int[] s_objs; static TestCSE() { s_objs = new int[3]; s_objs[0] = VAL1; s_objs[1] = VAL1; s_objs[2] = VAL2; } public TestCSE() { _a = s_objs[0]; _b = s_objs[1]; } public static bool Equal(int val1, int val2) { if (val1 == val2) return true; return false; } public static bool TestFailed(int result, int expected1, int expected2, string tname) { if (result == expected1) return false; if (result == expected2) return false; Console.WriteLine("this failure may not repro everytime"); Console.WriteLine("ERROR FAILED:" + tname + ",got val1=" + result + " expected value is, either " + expected1 + " or " + expected2); throw new Exception("check failed for " + tname); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public bool TestOp() { long i; Thread.Sleep(0); _a = VAL1; _b = VAL1; for (i = 0; ; i++) { #if OP_ADD if (!Equal(_a + _b, _a + _b)) break; if (!Equal(_a + _b, _a + _b)) break; #elif OP_SUB if (!Equal(_a - _b, _a - _b)) break; if (!Equal(_a - _b, _a - _b)) break; #elif OP_MUL if (!Equal(_a * _b, _a * _b)) break; if (!Equal(_a * _b, _a * _b)) break; #elif OP_DIV if (!Equal(_a / _b, _a / _b)) break; if (!Equal(_a / _b, _a / _b)) break; #elif OP_MOD if (!Equal(_a % _b, _a % _b)) break; if (!Equal(_a % _b, _a % _b)) break; #elif OP_XOR if (!Equal(_a ^ _b, _a ^ _b)) break; if (!Equal(_a ^ _b, _a ^ _b)) break; #elif OP_OR if (!Equal(_a | _b, _a | _b)) break; if (!Equal(_a | _b, _a | _b)) break; #elif OP_AND if (!Equal(_a & _b, _a & _b)) break; if (!Equal(_a & _b, _a & _b)) break; #elif OP_SHR if (!Equal(_a >> _b, _a >> _b)) break; if (!Equal(_a >> _b, _a >> _b)) break; #else #error Please define an operator (e.g. /define:OP_ADD, /define:OP:SUB...) #endif i++; } Console.WriteLine("Test 1 passed after " + i + " tries"); _a = VAL1; _b = VAL1; for (i = 0; ; i++) { #if OP_ADD if (!Equal(_a + _b, VAL1 + VAL1)) break; if (!Equal(_a + _b, VAL1 + VAL1)) break; #elif OP_SUB if (!Equal(_a - _b, VAL1 - VAL2)) break; if (!Equal(_a - _b, VAL1 - VAL2)) break; #elif OP_MUL if (!Equal(_a * _b, VAL1 * VAL2)) break; if (!Equal(_a * _b, VAL1 * VAL2)) break; #elif OP_DIV if (!Equal(_a / _b, VAL1 / VAL2)) break; if (!Equal(_a / _b, VAL1 / VAL2)) break; #elif OP_MOD if (!Equal(_a % _b, VAL1 % VAL2)) break; if (!Equal(_a % _b, VAL1 % VAL2)) break; #elif OP_XOR if (!Equal(_a ^ _b, VAL1 ^ VAL2)) break; if (!Equal(_a ^ _b, VAL1 ^ VAL2)) break; #elif OP_OR if (!Equal(_a | _b, VAL1 | VAL2)) break; if (!Equal(_a | _b, VAL1 | VAL2)) break; #elif OP_AND if (!Equal(_a & _b, VAL1 & VAL2)) break; if (!Equal(_a & _b, VAL1 & VAL2)) break; #elif OP_SHR if (!Equal(_a >> _b, VAL1 >> VAL2)) break; if (!Equal(_a >> _b, VAL1 >> VAL2)) break; #else #error Please define an operator (e.g. /define:OP_ADD, /define:OP:SUB...) #endif } Console.WriteLine("Test 2 passed after " + i + " tries"); bool passed = false; _a = VAL1; _b = VAL1; for (i = 0; ; i++) { #if OP_ADD int ans1 = _a + _b; int ans2 = _a + _b; if (TestFailed(ans1, VAL1 + VAL1, VAL1 + VAL2, "Test 3") || TestFailed(ans2, VAL1 + VAL1, VAL1 + VAL2, "Test 3")) #elif OP_SUB int ans1 = _a - _b; int ans2 = _a - _b; if (TestFailed(ans1, VAL1 - VAL1, VAL1 - VAL2, "Test 3") || TestFailed(ans2, VAL1 - VAL1, VAL1 - VAL2, "Test 3")) #elif OP_MUL int ans1 = _a * _b; int ans2 = _a * _b; if (TestFailed(ans1, VAL1 * VAL1, VAL1 * VAL2, "Test 3") || TestFailed(ans2, VAL1 * VAL1, VAL1 * VAL2, "Test 3")) #elif OP_DIV int ans1 = _a / _b; int ans2 = _a / _b; if (TestFailed(ans1, VAL1 / VAL1, VAL1 / VAL2, "Test 3") || TestFailed(ans2, VAL1 / VAL1, VAL1 / VAL2, "Test 3")) #elif OP_MOD int ans1 = _a % _b; int ans2 = _a % _b; if (TestFailed(ans1, VAL1 % VAL1, VAL1 % VAL2, "Test 3") || TestFailed(ans2, VAL1 % VAL1, VAL1 % VAL2, "Test 3")) #elif OP_XOR int ans1 = _a ^ _b; int ans2 = _a ^ _b; if (TestFailed(ans1, VAL1 ^ VAL1, VAL1 ^ VAL2, "Test 3") || TestFailed(ans2, VAL1 ^ VAL1, VAL1 ^ VAL2, "Test 3")) #elif OP_OR int ans1 = _a | _b; int ans2 = _a | _b; if (TestFailed(ans1, VAL1 | VAL1, VAL1 | VAL2, "Test 3") || TestFailed(ans2, VAL1 | VAL1, VAL1 | VAL2, "Test 3")) #elif OP_AND int ans1 = _a & _b; int ans2 = _a & _b; if (TestFailed(ans1, VAL1 & VAL1, VAL1 & VAL2, "Test 3") || TestFailed(ans2, VAL1 & VAL1, VAL1 & VAL2, "Test 3")) #elif OP_SHR int ans1 = _a >> _b; int ans2 = _a >> _b; if (passed) #else #error Please define an operator (e.g. /define:OP_ADD, /define:OP:SUB...) #endif { passed = false; break; } if (ans1 != ans2) { passed = true; break; } } Console.WriteLine("Test 3 " + (passed ? "passed" : "failed") + " after " + i + " tries"); return passed; } private void Flip() { for (uint i = 0; !s_timeUp; i++) { _a = s_objs[i % 2]; _b = s_objs[(i % 2) + 1]; } } public static bool Test() { TestCSE o = new TestCSE(); Thread t = new Thread(new ThreadStart(o.Flip)); t.Start(); bool ans = o.TestOp(); s_timeUp = true; t.Join(); return ans; } }
#region Copyright /*Copyright (C) 2015 Konstantin Udilovich Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Kodestruct.Analysis.BeamForces.SimpleWithOverhang { public class ConcentratedLoadOverhang : ISingleLoadCaseBeam, ISingleLoadCaseDeflectionBeam { BeamSimpleWithOverhang beam; const string CASE = "C2A_2"; double P, a, L, X1; bool X1Calculated; //note for overhang beam a is the overhang with //1 exception of concentrated load between supports public ConcentratedLoadOverhang(BeamSimpleWithOverhang beam, double P, double a) { this.beam = beam; L = beam.Length; this.P = P; this.a = a; X1Calculated = false; } private void CalculateX1(double X) { X1 = X - L; X1Calculated = true; } public double Moment(double X) { beam.EvaluateX(X); double M; if (X<=L) { M = P * a * X / L; BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mx, 1, new Dictionary<string, double>() { {"L",L }, {"X",X }, {"P",P}, {"a",a }, }, CASE, beam); } else { if (X1Calculated == false) { CalculateX1(X); } M = P * (a - X1); BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mx, 2, new Dictionary<string, double>() { {"X1",X1 }, {"P",P}, {"a",a }, }, CASE, beam); } return M; } public ForceDataPoint MomentMax() { double M; if (P>=0.0) { M = P * a; BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mmax, 1, new Dictionary<string, double>() { {"X",X1 }, {"P",P}, {"a",a }, }, CASE, beam, true); } else { M = 0; BeamEntryFactory.CreateEntry("Mx", 0.0, BeamTemplateType.M_zero, 0, null, CASE, beam, true); } return new ForceDataPoint(L, M); } public ForceDataPoint MomentMin() { double M; if (P < 0.0) { M = P * a; BeamEntryFactory.CreateEntry("Mx", M, BeamTemplateType.Mmax, 1, new Dictionary<string, double>() { {"X",X1 }, {"P",P}, {"a",a }, }, CASE, beam, false, true); } else { M = 0; BeamEntryFactory.CreateEntry("Mx", 0.0, BeamTemplateType.M_zero, 0, null, CASE, beam, false, true); } return new ForceDataPoint(L, M); } public double Shear(double X) { double V1 = GetShearBetweenSupports(); double V2 = GetShearAtOverhang(); Dictionary<string, double> valDic = new Dictionary<string, double>() { {"L",L }, {"X",X }, {"P",P}, {"a",a }, }; if (X<L) { BeamEntryFactory.CreateEntry("Vx", V1, BeamTemplateType.Vx, 1, valDic, CASE, beam); return V1; } else if (X>L) { BeamEntryFactory.CreateEntry("Vx", V2, BeamTemplateType.Vx, 2, valDic, CASE, beam); return V2; } else //right at support point { if (V1>V2) { BeamEntryFactory.CreateEntry("Vx", V1, BeamTemplateType.Vx, 1, valDic, CASE, beam); return V1; } else { BeamEntryFactory.CreateEntry("Vx", V2, BeamTemplateType.Vx, 2, valDic, CASE, beam); return V2; } } } public ForceDataPoint ShearMax() { double V1 = GetShearBetweenSupports(); double V2 = GetShearAtOverhang(); Dictionary<string, double> valDic = new Dictionary<string, double>() { {"L",L }, {"P",P}, {"a",a }, }; if (V1 > V2) { BeamEntryFactory.CreateEntry("Vx", V1, BeamTemplateType.Vmax, 1, valDic, CASE, beam); return new ForceDataPoint(L,V1); } else { BeamEntryFactory.CreateEntry("Vx", V2, BeamTemplateType.Vmax, 2, valDic, CASE, beam); return new ForceDataPoint(L, V2); } } private double GetShearBetweenSupports() { double V = P*a/L; return V; } private double GetShearAtOverhang() { double V = P; return V; } public double MaximumDeflection() { double E = beam.ModulusOfElasticity; double I = beam.MomentOfInertia; double delta_Maximum = ((P * Math.Pow(a, 2)) / (3.0 * E * I)) * (L + a); return delta_Maximum; } } }
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Tests.Serialization { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Xml.Linq; using GreenPipes.Internals.Extensions; using MassTransit.Serialization; using MassTransit.Serialization.JsonConverters; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; using NUnit.Framework; using Shouldly; using Util; public class When_serializing_messages_with_json_dot_net { static Type _proxyType = TypeCache.GetImplementationType(typeof(MessageA)); string _body; JsonSerializer _deserializer; Envelope _envelope; TestMessage _message; JsonSerializer _serializer; XDocument _xml; [SetUp] public void Serializing_messages_with_json_dot_net() { _message = new TestMessage { Name = "Joe", Details = new List<TestMessageDetail> { new TestMessageDetail {Item = "A", Value = 27.5d}, new TestMessageDetail {Item = "B", Value = 13.5d}, }, EnumDetails = new List<TestMessageDetail> { new TestMessageDetail{Item = "1", Value = 42.0d} } }; _envelope = new Envelope { Message = _message, }; _envelope.MessageType.Add(_message.GetType().ToMessageName()); _envelope.MessageType.Add(typeof(MessageA).ToMessageName()); _envelope.MessageType.Add(typeof(MessageB).ToMessageName()); _serializer = JsonMessageSerializer.Serializer; _deserializer = JsonMessageSerializer.Deserializer; using (var memoryStream = new MemoryStream()) using (var writer = new StreamWriter(memoryStream)) using (var jsonWriter = new JsonTextWriter(writer)) { jsonWriter.Formatting = Formatting.Indented; _serializer.Serialize(jsonWriter, _envelope); writer.Flush(); _body = Encoding.UTF8.GetString(memoryStream.ToArray()); } _xml = JsonConvert.DeserializeXNode(_body, "envelope"); } [Test, Explicit] public void Show_me_the_message() { Trace.WriteLine(_body); Trace.WriteLine(_xml.ToString()); } [Test] public void Should_be_able_to_ressurect_the_message() { Envelope result; using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(_body), false)) using (var reader = new StreamReader(memoryStream)) using (var jsonReader = new JsonTextReader(reader)) { result = _deserializer.Deserialize<Envelope>(jsonReader); } result.MessageType.Count.ShouldBe(3); result.MessageType[0].ShouldBe(typeof(TestMessage).ToMessageName()); result.MessageType[1].ShouldBe(typeof(MessageA).ToMessageName()); result.MessageType[2].ShouldBe(typeof(MessageB).ToMessageName()); result.Headers.Count.ShouldBe(0); } [Test] public void Should_be_able_to_suck_out_an_interface() { Envelope result; using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(_body), false)) using (var reader = new StreamReader(memoryStream)) using (var jsonReader = new JsonTextReader(reader)) { result = _deserializer.Deserialize<Envelope>(jsonReader); } using (var jsonReader = new JTokenReader(result.Message as JToken)) { Type proxyType = TypeCache.GetImplementationType(typeof(MessageA)); var message = (MessageA)Activator.CreateInstance(proxyType); _serializer.Populate(jsonReader, message); message.Name.ShouldBe("Joe"); } } [Test] public void Should_be_able_to_suck_out_an_object() { Envelope result; using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(_body), false)) using (var reader = new StreamReader(memoryStream)) using (var jsonReader = new JsonTextReader(reader)) { result = _deserializer.Deserialize<Envelope>(jsonReader); } using (var jsonReader = new JTokenReader(result.Message as JToken)) { var message = (TestMessage)_serializer.Deserialize(jsonReader, typeof(TestMessage)); message.Name.ShouldBe("Joe"); message.Details.Count.ShouldBe(2); message.EnumDetails.Count().ShouldBe(1); } } [Test] public void Should_be_able_to_ressurect_the_message_from_xml() { XDocument document = XDocument.Parse(_xml.ToString()); Trace.WriteLine(_xml.ToString()); string body = JsonConvert.SerializeXNode(document, Formatting.None, true); Trace.WriteLine(body); var result = JsonConvert.DeserializeObject<Envelope>(body, new JsonSerializerSettings { Converters = new List<JsonConverter>(new JsonConverter[] {new ListJsonConverter()}), NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore, MissingMemberHandling = MissingMemberHandling.Ignore, ObjectCreationHandling = ObjectCreationHandling.Auto, ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, ContractResolver = new CamelCasePropertyNamesContractResolver(), }); result.MessageType.Count.ShouldBe(3); result.MessageType[0].ShouldBe(typeof(TestMessage).ToMessageName()); result.MessageType[1].ShouldBe(typeof(MessageA).ToMessageName()); result.MessageType[2].ShouldBe(typeof(MessageB).ToMessageName()); result.Headers.Count.ShouldBe(0); } [Test] public void Serialization_speed() { //warm it up for (int i = 0; i < 10; i++) { DoSerialize(); DoDeserialize(); } Stopwatch timer = Stopwatch.StartNew(); const int iterations = 50000; for (int i = 0; i < iterations; i++) DoSerialize(); timer.Stop(); long perSecond = iterations * 1000 / timer.ElapsedMilliseconds; string msg = string.Format("Serialize: {0}ms, Rate: {1} m/s", timer.ElapsedMilliseconds, perSecond); Trace.WriteLine(msg); timer = Stopwatch.StartNew(); for (int i = 0; i < 50000; i++) DoDeserialize(); timer.Stop(); perSecond = iterations * 1000 / timer.ElapsedMilliseconds; msg = string.Format("Deserialize: {0}ms, Rate: {1} m/s", timer.ElapsedMilliseconds, perSecond); Trace.WriteLine(msg); } void DoSerialize() { using (var memoryStream = new MemoryStream()) using (var writer = new StreamWriter(memoryStream)) using (var jsonWriter = new JsonTextWriter(writer)) { jsonWriter.Formatting = Formatting.Indented; _serializer.Serialize(jsonWriter, _envelope); writer.Flush(); _body = Encoding.UTF8.GetString(memoryStream.ToArray()); } } void DoDeserialize() { Envelope result; using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(_body), false)) using (var reader = new StreamReader(memoryStream)) using (var jsonReader = new JsonTextReader(reader)) { result = _deserializer.Deserialize<Envelope>(jsonReader); } using (var jsonReader = new JTokenReader(result.Message as JToken)) { var message = (MessageA)Activator.CreateInstance(_proxyType); _serializer.Populate(jsonReader, message); } } public static object Convert(string s) { object obj = JsonConvert.DeserializeObject(s); if (obj is string) return obj as string; return ConvertJson((JToken)obj); } static object ConvertJson(JToken token) { var value = token as JValue; if (value != null) return value.Value; if (token is JObject) { IDictionary<string, object> expando = new Dictionary<string, object>(); (from childToken in token where childToken is JProperty select childToken as JProperty).ToList().ForEach( property => { expando.Add(property.Name, ConvertJson(property.Value)); }); return expando; } if (token is JArray) return (token).Select(ConvertJson).ToList(); throw new ArgumentException(string.Format("VisitUnknownFilter token type '{0}'", token.GetType()), "token"); } class Envelope { public Envelope() { Headers = new Dictionary<string, string>(); MessageType = new List<string>(); } public IDictionary<string, string> Headers { get; set; } public object Message { get; set; } public IList<string> MessageType { get; set; } } public interface MessageA { string Name { get; } } public interface MessageB { string Address { get; } string Name { get; } } class TestMessage : MessageA { public string Address { get; set; } public IList<TestMessageDetail> Details { get; set; } public int Level { get; set; } public string Name { get; set; } public IEnumerable<TestMessageDetail> EnumDetails { get; set; } } class TestMessageDetail { public string Item { get; set; } public double Value { get; set; } } } [TestFixture(typeof(JsonMessageSerializer)), TestFixture(typeof(BsonMessageSerializer)), TestFixture(typeof(XmlMessageSerializer))] public class Using_JsonConverterAttribute_on_a_class : SerializationTest { [Test] public void Should_use_converter_for_deserialization() { var obj = new MessageB {Value = "Joe"}; MessageB result = SerializeAndReturn(obj); result.Value.ShouldBe("Monster"); } [Test] public void Should_use_converter_for_serialization() { var obj = new MessageA {Value = "Joe"}; MessageA result = SerializeAndReturn(obj); result.Value.ShouldBe("Monster"); } public class ModifyWhenSerializingConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteStartObject(); writer.WritePropertyName("value"); writer.WriteValue("Monster"); writer.WriteEndObject(); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { reader.Read(); reader.Value.ShouldBe("value"); reader.Read(); var value = (string)reader.Value; return new MessageA {Value = value}; } public override bool CanConvert(Type objectType) { return typeof(MessageA).IsAssignableFrom(objectType); } } public class ModifyWhenDeserializingConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var testMessage = (MessageB)value; writer.WriteStartObject(); writer.WritePropertyName("value"); writer.WriteValue(testMessage.Value); writer.WriteEndObject(); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return new MessageB {Value = "Monster"}; } public override bool CanConvert(Type objectType) { return typeof(MessageB).IsAssignableFrom(objectType); } } [JsonConverter(typeof(ModifyWhenSerializingConverter))] public class MessageA { public string Value { get; set; } } [JsonConverter(typeof(ModifyWhenDeserializingConverter))] public class MessageB { public string Value { get; set; } } public Using_JsonConverterAttribute_on_a_class(Type serializerType) : base(serializerType) { } } [TestFixture(typeof(JsonMessageSerializer)), TestFixture(typeof(BsonMessageSerializer)), TestFixture(typeof(XmlMessageSerializer))] public class Using_JsonConverterAttribute_on_a_property : SerializationTest { [Test] public void Should_use_converter_for_deserialization() { var obj = new SimpleMessage {ValueB = "Joe"}; SimpleMessage result = SerializeAndReturn(obj); result.ValueB.ShouldBe("Monster"); } [Test] public void Should_use_converter_for_serialization() { var obj = new SimpleMessage {ValueA = "Joe"}; SimpleMessage result = SerializeAndReturn(obj); result.ValueA.ShouldBe("Monster"); } public class ModifyWhenSerializingConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue("Monster"); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return reader.Value; } public override bool CanConvert(Type objectType) { return typeof(string).GetTypeInfo().IsAssignableFrom(objectType); } } public class ModifyWhenDeserializingConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue((string)value); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return "Monster"; } public override bool CanConvert(Type objectType) { return typeof(string).IsAssignableFrom(objectType); } } public class SimpleMessage { [JsonConverter(typeof(ModifyWhenSerializingConverter))] public string ValueA { get; set; } [JsonConverter(typeof(ModifyWhenDeserializingConverter))] public string ValueB { get; set; } } public Using_JsonConverterAttribute_on_a_property(Type serializerType) : base(serializerType) { } } }
using System; using System.Collections; using System.Collections.Generic; namespace QuantConnect.Data.Market { /// <summary> /// Provides a base class for types holding base data instances keyed by symbol /// </summary> public class DataDictionary<T> : IDictionary<Symbol, T> { // storage for the data private readonly IDictionary<Symbol, T> _data = new Dictionary<Symbol, T>(); /// <summary> /// Initializes a new instance of the <see cref="QuantConnect.Data.Market.DataDictionary{T}"/> class. /// </summary> public DataDictionary() { } /// <summary> /// Initializes a new instance of the <see cref="QuantConnect.Data.Market.DataDictionary{T}"/> class /// using the specified <paramref name="data"/> as a data source /// </summary> /// <param name="data">The data source for this data dictionary</param> /// <param name="keySelector">Delegate used to select a key from the value</param> public DataDictionary(IEnumerable<T> data, Func<T, Symbol> keySelector) { foreach (var datum in data) { this[keySelector(datum)] = datum; } } /// <summary> /// Initializes a new instance of the <see cref="QuantConnect.Data.Market.DataDictionary{T}"/> class. /// </summary> /// <param name="time">The time this data was emitted.</param> public DataDictionary(DateTime time) { #pragma warning disable 618 // This assignment is left here until the Time property is removed. Time = time; #pragma warning restore 618 } /// <summary> /// Gets or sets the time associated with this collection of data /// </summary> [Obsolete("The DataDictionary<T> Time property is now obsolete. All algorithms should use algorithm.Time instead.")] public DateTime Time { get; set; } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> /// <filterpriority>1</filterpriority> public IEnumerator<KeyValuePair<Symbol, T>> GetEnumerator() { return _data.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> /// <filterpriority>2</filterpriority> IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable) _data).GetEnumerator(); } /// <summary> /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception> public void Add(KeyValuePair<Symbol, T> item) { _data.Add(item); } /// <summary> /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. </exception> public void Clear() { _data.Clear(); } /// <summary> /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value. /// </summary> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. /// </returns> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> public bool Contains(KeyValuePair<Symbol, T> item) { return _data.Contains(item); } /// <summary> /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param><param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param><exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null.</exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0.</exception><exception cref="T:System.ArgumentException">The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.</exception> public void CopyTo(KeyValuePair<Symbol, T>[] array, int arrayIndex) { _data.CopyTo(array, arrayIndex); } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <returns> /// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </returns> /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception> public bool Remove(KeyValuePair<Symbol, T> item) { return _data.Remove(item); } /// <summary> /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <returns> /// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </returns> public int Count { get { return _data.Count; } } /// <summary> /// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. /// </summary> /// <returns> /// true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false. /// </returns> public bool IsReadOnly { get { return _data.IsReadOnly; } } /// <summary> /// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key. /// </summary> /// <returns> /// true if the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the key; otherwise, false. /// </returns> /// <param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.</param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception> public bool ContainsKey(Symbol key) { return _data.ContainsKey(key); } /// <summary> /// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </summary> /// <param name="key">The object to use as the key of the element to add.</param><param name="value">The object to use as the value of the element to add.</param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception><exception cref="T:System.ArgumentException">An element with the same key already exists in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.</exception><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.</exception> public void Add(Symbol key, T value) { _data.Add(key, value); } /// <summary> /// Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </summary> /// <returns> /// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </returns> /// <param name="key">The key of the element to remove.</param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.</exception> public bool Remove(Symbol key) { return _data.Remove(key); } /// <summary> /// Gets the value associated with the specified key. /// </summary> /// <returns> /// true if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key; otherwise, false. /// </returns> /// <param name="key">The key whose value to get.</param><param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value"/> parameter. This parameter is passed uninitialized.</param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception> public bool TryGetValue(Symbol key, out T value) { return _data.TryGetValue(key, out value); } /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <returns> /// The element with the specified key. /// </returns> /// <param name="symbol">The key of the element to get or set.</param> /// <exception cref="T:System.ArgumentNullException"><paramref name="symbol"/> is null.</exception> /// <exception cref="T:System.Collections.Generic.KeyNotFoundException">The property is retrieved and <paramref name="symbol"/> is not found.</exception> /// <exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.</exception> public T this[Symbol symbol] { get { T data; if (TryGetValue(symbol, out data)) { return data; } throw new KeyNotFoundException(string.Format("'{0}' wasn't found in the {1} object, likely because there was no-data at this moment in time and it wasn't possible to fillforward historical data. Please check the data exists before accessing it with data.ContainsKey(\"{0}\")", symbol, GetType().GetBetterTypeName())); } set { _data[symbol] = value; } } /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <returns> /// The element with the specified key. /// </returns> /// <param name="ticker">The key of the element to get or set.</param> /// <exception cref="T:System.ArgumentNullException"><paramref name="ticker"/> is null.</exception> /// <exception cref="T:System.Collections.Generic.KeyNotFoundException">The property is retrieved and <paramref name="ticker"/> is not found.</exception> /// <exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.</exception> public T this[string ticker] { get { Symbol symbol; if (!SymbolCache.TryGetSymbol(ticker, out symbol)) { throw new KeyNotFoundException(string.Format("'{0}' wasn't found in the {1} object, likely because there was no-data at this moment in time and it wasn't possible to fillforward historical data. Please check the data exists before accessing it with data.ContainsKey(\"{0}\")", ticker, GetType().GetBetterTypeName())); } return this[symbol]; } set { Symbol symbol; if (!SymbolCache.TryGetSymbol(ticker, out symbol)) { throw new KeyNotFoundException(string.Format("'{0}' wasn't found in the {1} object, likely because there was no-data at this moment in time and it wasn't possible to fillforward historical data. Please check the data exists before accessing it with data.ContainsKey(\"{0}\")", ticker, GetType().GetBetterTypeName())); } this[symbol] = value; } } /// <summary> /// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </summary> /// <returns> /// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </returns> public ICollection<Symbol> Keys { get { return _data.Keys; } } /// <summary> /// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </summary> /// <returns> /// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </returns> public ICollection<T> Values { get { return _data.Values; } } } /// <summary> /// Provides extension methods for the DataDictionary class /// </summary> public static class DataDictionaryExtensions { /// <summary> /// Provides a convenience method for adding a base data instance to our data dictionary /// </summary> public static void Add<T>(this DataDictionary<T> dictionary, T data) where T : BaseData { dictionary.Add(data.Symbol, data); } } }
// // CalendarMonthView.cs // // Converted to MonoTouch on 1/22/09 - Eduardo Scoz || http://escoz.com // Originally reated by Devin Ross on 7/28/09 - tapku.com || http://github.com/devinross/tapkulibrary // /* 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 Foundation; using UIKit; using System.Collections; using System.Collections.Generic; using System.Drawing; using CoreGraphics; namespace escoz { public delegate void DateSelected(DateTime date); public delegate void MonthChanged(DateTime monthSelected); public class CalendarMonthView : UIView { public int BoxHeight = 30; public int BoxWidth = 46; int headerHeight = 0; public Action<DateTime> OnDateSelected; public Action<DateTime> OnFinishedDateSelection; public Func<DateTime, bool> IsDayMarkedDelegate; public Func<DateTime, bool> IsDateAvailable; public Action<DateTime> MonthChanged; public Action SwipedUp; public DateTime CurrentSelectedDate; public DateTime CurrentMonthYear; protected DateTime CurrentDate { get; set; } private UIScrollView _scrollView; private bool calendarIsLoaded; private MonthGridView _monthGridView; bool _showHeader; public CalendarMonthView(DateTime selectedDate, bool showHeader, float width = 320) { _showHeader = showHeader; if (_showHeader) headerHeight = 20; if (_showHeader) this.Frame = new CGRect(0, 0, width, 218); else this.Frame = new CGRect(0, 0, width, 198); BoxWidth = Convert.ToInt32(Math.Ceiling(width / 7)); BackgroundColor = UIColor.White; ClipsToBounds = true; CurrentSelectedDate = selectedDate; CurrentDate = DateTime.Now.Date; CurrentMonthYear = new DateTime(CurrentSelectedDate.Year, CurrentSelectedDate.Month, 1); var swipeLeft = new UISwipeGestureRecognizer(p_monthViewSwipedLeft); swipeLeft.Direction = UISwipeGestureRecognizerDirection.Left; this.AddGestureRecognizer(swipeLeft); var swipeRight = new UISwipeGestureRecognizer(p_monthViewSwipedRight); swipeRight.Direction = UISwipeGestureRecognizerDirection.Right; this.AddGestureRecognizer(swipeRight); var swipeUp = new UISwipeGestureRecognizer(p_monthViewSwipedUp); swipeUp.Direction = UISwipeGestureRecognizerDirection.Up; this.AddGestureRecognizer(swipeUp); } public void SetDate(DateTime newDate) { bool right = true; CurrentSelectedDate = newDate; var monthsDiff = (newDate.Month - CurrentMonthYear.Month) + 12 * (newDate.Year - CurrentMonthYear.Year); if (monthsDiff != 0) { if (monthsDiff < 0) { right = false; monthsDiff = -monthsDiff; } for (int i = 0; i < monthsDiff; i++) { MoveCalendarMonths(right, true); } } else { RebuildGrid(right, false); } } void p_monthViewSwipedUp(UISwipeGestureRecognizer ges) { if (SwipedUp != null) SwipedUp(); } void p_monthViewSwipedRight(UISwipeGestureRecognizer ges) { MoveCalendarMonths(false, true); } void p_monthViewSwipedLeft(UISwipeGestureRecognizer ges) { MoveCalendarMonths(true, true); } public override void SetNeedsDisplay() { base.SetNeedsDisplay(); if (_monthGridView != null) _monthGridView.Update(); } public override void LayoutSubviews() { if (calendarIsLoaded) return; _scrollView = new UIScrollView() { ContentSize = new CGSize(320, 260), ScrollEnabled = false, Frame = new CGRect(0, 16 + headerHeight, 320, this.Frame.Height - 16), BackgroundColor = UIColor.White }; //_shadow = new UIImageView(UIImage.FromBundle("Images/Calendar/shadow.png")); //LoadButtons(); LoadInitialGrids(); BackgroundColor = UIColor.Clear; AddSubview(_scrollView); //AddSubview(_shadow); _scrollView.AddSubview(_monthGridView); calendarIsLoaded = true; } public void DeselectDate() { if (_monthGridView != null) _monthGridView.DeselectDayView(); } /*private void LoadButtons() { _leftButton = UIButton.FromType(UIButtonType.Custom); _leftButton.TouchUpInside += HandlePreviousMonthTouch; _leftButton.SetImage(UIImage.FromBundle("Images/Calendar/leftarrow.png"), UIControlState.Normal); AddSubview(_leftButton); _leftButton.Frame = new CGRect(10, 0, 44, 42); _rightButton = UIButton.FromType(UIButtonType.Custom); _rightButton.TouchUpInside += HandleNextMonthTouch; _rightButton.SetImage(UIImage.FromBundle("Images/Calendar/rightarrow.png"), UIControlState.Normal); AddSubview(_rightButton); _rightButton.Frame = new CGRect(320 - 56, 0, 44, 42); }*/ private void HandlePreviousMonthTouch(object sender, EventArgs e) { MoveCalendarMonths(false, true); } private void HandleNextMonthTouch(object sender, EventArgs e) { MoveCalendarMonths(true, true); } public void MoveCalendarMonths(bool right, bool animated) { CurrentMonthYear = CurrentMonthYear.AddMonths(right ? 1 : -1); RebuildGrid(right, animated); } public void RebuildGrid(bool right, bool animated) { UserInteractionEnabled = false; var gridToMove = CreateNewGrid(CurrentMonthYear); var pointsToMove = (right ? Frame.Width : -Frame.Width); /*if (left && gridToMove.weekdayOfFirst==0) pointsToMove += 44; if (!left && _monthGridView.weekdayOfFirst==0) pointsToMove -= 44;*/ gridToMove.Frame = new CGRect(new CGPoint(pointsToMove, 0), gridToMove.Frame.Size); _scrollView.AddSubview(gridToMove); if (animated) { UIView.BeginAnimations("changeMonth"); UIView.SetAnimationDuration(0.4); UIView.SetAnimationDelay(0.1); UIView.SetAnimationCurve(UIViewAnimationCurve.EaseInOut); } _monthGridView.Center = new CGPoint(_monthGridView.Center.X - pointsToMove, _monthGridView.Center.Y); gridToMove.Center = new CGPoint(gridToMove.Center.X - pointsToMove, gridToMove.Center.Y); _monthGridView.Alpha = 0; /*_scrollView.Frame = new CGRect( _scrollView.Frame.Location, new CGSize(_scrollView.Frame.Width, this.Frame.Height-16)); _scrollView.ContentSize = _scrollView.Frame.Size;*/ SetNeedsDisplay(); if (animated) UIView.CommitAnimations(); _monthGridView = gridToMove; UserInteractionEnabled = true; if (MonthChanged != null) MonthChanged(CurrentMonthYear); } private MonthGridView CreateNewGrid(DateTime date) { var grid = new MonthGridView(this, date); grid.CurrentDate = CurrentDate; grid.BuildGrid(); grid.Frame = new CGRect(0, 0, 320, this.Frame.Height - 16); return grid; } private void LoadInitialGrids() { _monthGridView = CreateNewGrid(CurrentMonthYear); /*var rect = _scrollView.Frame; rect.Size = new CGSize { Height = (_monthGridView.Lines + 1) * 44, Width = rect.Size.Width }; _scrollView.Frame = rect;*/ //Frame = new CGRect(Frame.X, Frame.Y, _scrollView.Frame.Size.Width, _scrollView.Frame.Size.Height+16); /*var imgRect = _shadow.Frame; imgRect.Y = rect.Size.Height - 132; _shadow.Frame = imgRect;*/ } public override void Draw(CGRect rect) { using (var context = UIGraphics.GetCurrentContext()) { context.SetFillColor(UIColor.LightGray.CGColor); context.FillRect(new CGRect(0, 0, 320, 18 + headerHeight)); } DrawDayLabels(rect); if (_showHeader) DrawMonthLabel(rect); } private void DrawMonthLabel(CGRect rect) { var r = new CGRect(new CGPoint(0, 2), new CGSize { Width = 320, Height = 42 }); UIColor.DarkGray.SetColor(); CurrentMonthYear.ToString("MMMM yyyy").DrawString(r, UIFont.BoldSystemFontOfSize(16), UILineBreakMode.WordWrap, UITextAlignment.Center); } private void DrawDayLabels(CGRect rect) { var font = UIFont.BoldSystemFontOfSize(10); UIColor.DarkGray.SetColor(); var context = UIGraphics.GetCurrentContext(); context.SaveState(); var i = 0; foreach (var d in Enum.GetNames(typeof(DayOfWeek))) { d.Substring(0, 3).DrawString(new CGRect(i * BoxWidth, 2 + headerHeight, BoxWidth, 10), font, UILineBreakMode.WordWrap, UITextAlignment.Center); i++; } context.RestoreState(); } } public class MonthGridView : UIView { private CalendarMonthView _calendarMonthView; public DateTime CurrentDate { get; set; } private DateTime _currentMonth; protected readonly IList<CalendarDayView> _dayTiles = new List<CalendarDayView>(); public int Lines { get; set; } protected CalendarDayView SelectedDayView { get; set; } public int weekdayOfFirst; public IList<DateTime> Marks { get; set; } public MonthGridView(CalendarMonthView calendarMonthView, DateTime month) { _calendarMonthView = calendarMonthView; _currentMonth = month.Date; var tapped = new UITapGestureRecognizer(p_Tapped); this.AddGestureRecognizer(tapped); } void p_Tapped(UITapGestureRecognizer tapRecg) { var loc = tapRecg.LocationInView(this); if (SelectDayView(loc) && _calendarMonthView.OnDateSelected != null) _calendarMonthView.OnDateSelected(new DateTime(_currentMonth.Year, _currentMonth.Month, (int)SelectedDayView.Tag)); } public void Update() { foreach (var v in _dayTiles) updateDayView(v); this.SetNeedsDisplay(); } public void updateDayView(CalendarDayView dayView) { dayView.Marked = _calendarMonthView.IsDayMarkedDelegate == null ? false : _calendarMonthView.IsDayMarkedDelegate(dayView.Date); dayView.Available = _calendarMonthView.IsDateAvailable == null ? true : _calendarMonthView.IsDateAvailable(dayView.Date); } public void BuildGrid() { DateTime previousMonth = _currentMonth.AddMonths(-1); var daysInPreviousMonth = DateTime.DaysInMonth(previousMonth.Year, previousMonth.Month); var daysInMonth = DateTime.DaysInMonth(_currentMonth.Year, _currentMonth.Month); weekdayOfFirst = (int)_currentMonth.DayOfWeek; var lead = daysInPreviousMonth - (weekdayOfFirst - 1); int boxWidth = _calendarMonthView.BoxWidth; int boxHeight = _calendarMonthView.BoxHeight; // build last month's days for (int i = 1; i <= weekdayOfFirst; i++) { var viewDay = new DateTime(_currentMonth.Year, _currentMonth.Month, i); var dayView = new CalendarDayView(_calendarMonthView); dayView.Frame = new CGRect((i - 1) * boxWidth - 1, 0, boxWidth, boxHeight); dayView.Date = viewDay; dayView.Text = lead.ToString(); AddSubview(dayView); _dayTiles.Add(dayView); lead++; } var position = weekdayOfFirst + 1; var line = 0; // current month for (int i = 1; i <= daysInMonth; i++) { var viewDay = new DateTime(_currentMonth.Year, _currentMonth.Month, i); var dayView = new CalendarDayView(_calendarMonthView) { Frame = new CGRect((position - 1) * boxWidth - 1, line * boxHeight, boxWidth, boxHeight), Today = (CurrentDate.Date == viewDay.Date), Text = i.ToString(), Active = true, Tag = i, Selected = (viewDay.Date == _calendarMonthView.CurrentSelectedDate.Date) }; dayView.Date = viewDay; updateDayView(dayView); if (dayView.Selected) SelectedDayView = dayView; AddSubview(dayView); _dayTiles.Add(dayView); position++; if (position > 7) { position = 1; line++; } } //next month int dayCounter = 1; if (position != 1) { for (int i = position; i < 8; i++) { var viewDay = new DateTime(_currentMonth.Year, _currentMonth.Month, i); var dayView = new CalendarDayView(_calendarMonthView) { Frame = new CGRect((i - 1) * boxWidth - 1, line * boxHeight, boxWidth, boxHeight), Text = dayCounter.ToString(), }; dayView.Date = viewDay; updateDayView(dayView); AddSubview(dayView); _dayTiles.Add(dayView); dayCounter++; } } while (line < 6) { line++; for (int i = 1; i < 8; i++) { var viewDay = new DateTime(_currentMonth.Year, _currentMonth.Month, i); var dayView = new CalendarDayView(_calendarMonthView) { Frame = new CGRect((i - 1) * boxWidth - 1, line * boxHeight, boxWidth, boxHeight), Text = dayCounter.ToString(), }; dayView.Date = viewDay; updateDayView(dayView); AddSubview(dayView); _dayTiles.Add(dayView); dayCounter++; } } Frame = new CGRect(Frame.Location, new CGSize(Frame.Width, (line + 1) * boxHeight)); Lines = (position == 1 ? line - 1 : line); if (SelectedDayView != null) this.BringSubviewToFront(SelectedDayView); } /*public override void TouchesBegan (NSSet touches, UIEvent evt) { base.TouchesBegan (touches, evt); if (SelectDayView((UITouch)touches.AnyObject)&& _calendarMonthView.OnDateSelected!=null) _calendarMonthView.OnDateSelected(new DateTime(_currentMonth.Year, _currentMonth.Month, SelectedDayView.Tag)); } public override void TouchesMoved (NSSet touches, UIEvent evt) { base.TouchesMoved (touches, evt); if (SelectDayView((UITouch)touches.AnyObject)&& _calendarMonthView.OnDateSelected!=null) _calendarMonthView.OnDateSelected(new DateTime(_currentMonth.Year, _currentMonth.Month, SelectedDayView.Tag)); } public override void TouchesEnded (NSSet touches, UIEvent evt) { base.TouchesEnded (touches, evt); if (_calendarMonthView.OnFinishedDateSelection==null) return; var date = new DateTime(_currentMonth.Year, _currentMonth.Month, SelectedDayView.Tag); if (_calendarMonthView.IsDateAvailable == null || _calendarMonthView.IsDateAvailable(date)) _calendarMonthView.OnFinishedDateSelection(date); }*/ private bool SelectDayView(CGPoint p) { int index = ((int)p.Y / _calendarMonthView.BoxHeight) * 7 + ((int)p.X / _calendarMonthView.BoxWidth); if (index < 0 || index >= _dayTiles.Count) return false; var newSelectedDayView = _dayTiles[index]; if (newSelectedDayView == SelectedDayView) return false; if (!newSelectedDayView.Active) { var day = int.Parse(newSelectedDayView.Text); if (day > 15) _calendarMonthView.MoveCalendarMonths(false, true); else _calendarMonthView.MoveCalendarMonths(true, true); return false; } else if (!newSelectedDayView.Active && !newSelectedDayView.Available) { return false; } if (SelectedDayView != null) SelectedDayView.Selected = false; this.BringSubviewToFront(newSelectedDayView); newSelectedDayView.Selected = true; SelectedDayView = newSelectedDayView; _calendarMonthView.CurrentSelectedDate = SelectedDayView.Date; SetNeedsDisplay(); return true; } public void DeselectDayView() { if (SelectedDayView == null) return; SelectedDayView.Selected = false; SelectedDayView = null; SetNeedsDisplay(); } } public class CalendarDayView : UIView { string _text; public DateTime Date { get; set; } bool _active, _today, _selected, _marked, _available; public bool Available { get { return _available; } set { _available = value; SetNeedsDisplay(); } } public string Text { get { return _text; } set { _text = value; SetNeedsDisplay(); } } public bool Active { get { return _active; } set { _active = value; SetNeedsDisplay(); } } public bool Today { get { return _today; } set { _today = value; SetNeedsDisplay(); } } public bool Selected { get { return _selected; } set { _selected = value; SetNeedsDisplay(); } } public bool Marked { get { return _marked; } set { _marked = value; SetNeedsDisplay(); } } CalendarMonthView _mv; public CalendarDayView(CalendarMonthView mv) { _mv = mv; BackgroundColor = UIColor.White; } public override void Draw(CGRect rect) { UIImage img = null; UIColor color = UIColor.Gray; if (!Active || !Available) { //color = UIColor.FromRGBA(0.576f, 0.608f, 0.647f, 1f); //img = UIImage.FromBundle("Images/Calendar/datecell.png"); } else if (Today && Selected) { //color = UIColor.White; img = UIImage.FromBundle("Images/Calendar/todayselected.png").CreateResizableImage(new UIEdgeInsets(4, 4, 4, 4)); } else if (Today) { //color = UIColor.White; img = UIImage.FromBundle("Images/Calendar/today.png").CreateResizableImage(new UIEdgeInsets(4, 4, 4, 4)); } else if (Selected || Marked) { //color = UIColor.White; img = UIImage.FromBundle("Images/Calendar/datecellselected.png").CreateResizableImage(new UIEdgeInsets(4, 4, 4, 4)); } else { color = UIColor.FromRGBA(0.275f, 0.341f, 0.412f, 1f); //img = UIImage.FromBundle("Images/Calendar/datecell.png"); } if (img != null) img.Draw(new CGRect(0, 0, _mv.BoxWidth, _mv.BoxHeight)); color.SetColor(); var inflated = new CGRect(0, 5, Bounds.Width, Bounds.Height); Text.DrawString(inflated, UIFont.BoldSystemFontOfSize(16), UILineBreakMode.WordWrap, UITextAlignment.Center); // if (Marked) // { // var context = UIGraphics.GetCurrentContext(); // if (Selected || Today) // context.SetRGBFillColor(1, 1, 1, 1); // else if (!Active || !Available) // UIColor.LightGray.SetColor(); // else // context.SetRGBFillColor(75/255f, 92/255f, 111/255f, 1); // context.SetLineWidth(0); // context.AddEllipseInRect(new CGRect(Frame.Size.Width/2 - 2, 45-10, 4, 4)); // context.FillPath(); // // } } } }
using BeardedManStudios.Forge.Networking.Generated; using System; using UnityEngine; namespace BeardedManStudios.Forge.Networking.Unity { public partial class NetworkManager : MonoBehaviour { public delegate void InstantiateEvent(INetworkBehavior unityGameObject, NetworkObject obj); public event InstantiateEvent objectInitialized; private BMSByte metadata = new BMSByte(); public GameObject[] ChatManagerNetworkObject = null; public GameObject[] CubeForgeGameNetworkObject = null; public GameObject[] GameLogicNetworkObject = null; public GameObject[] GameModeNetworkObject = null; public GameObject[] NetworkCameraNetworkObject = null; public GameObject[] PlayerNetworkObject = null; public GameObject[] NPCNetworkObject = null; private void SetupObjectCreatedEvent() { Networker.objectCreated += CaptureObjects; } private void OnDestroy() { if (Networker != null) Networker.objectCreated -= CaptureObjects; } private void CaptureObjects(NetworkObject obj) { if (obj.CreateCode < 0) return; if (obj is ChatManagerNetworkObject) { MainThreadManager.Run(() => { NetworkBehavior newObj = null; if (!NetworkBehavior.skipAttachIds.TryGetValue(obj.NetworkId, out newObj)) { if (ChatManagerNetworkObject.Length > 0 && ChatManagerNetworkObject[obj.CreateCode] != null) { var go = Instantiate(ChatManagerNetworkObject[obj.CreateCode]); newObj = go.GetComponent<NetworkBehavior>(); } } if (newObj == null) return; newObj.Initialize(obj); if (objectInitialized != null) objectInitialized(newObj, obj); }); } else if (obj is CubeForgeGameNetworkObject) { MainThreadManager.Run(() => { NetworkBehavior newObj = null; if (!NetworkBehavior.skipAttachIds.TryGetValue(obj.NetworkId, out newObj)) { if (CubeForgeGameNetworkObject.Length > 0 && CubeForgeGameNetworkObject[obj.CreateCode] != null) { var go = Instantiate(CubeForgeGameNetworkObject[obj.CreateCode]); newObj = go.GetComponent<NetworkBehavior>(); } } if (newObj == null) return; newObj.Initialize(obj); if (objectInitialized != null) objectInitialized(newObj, obj); }); } else if (obj is GameLogicNetworkObject) { MainThreadManager.Run(() => { NetworkBehavior newObj = null; if (!NetworkBehavior.skipAttachIds.TryGetValue(obj.NetworkId, out newObj)) { if (GameLogicNetworkObject.Length > 0 && GameLogicNetworkObject[obj.CreateCode] != null) { var go = Instantiate(GameLogicNetworkObject[obj.CreateCode]); newObj = go.GetComponent<NetworkBehavior>(); } } if (newObj == null) return; newObj.Initialize(obj); if (objectInitialized != null) objectInitialized(newObj, obj); }); } else if (obj is GameModeNetworkObject) { MainThreadManager.Run(() => { NetworkBehavior newObj = null; if (!NetworkBehavior.skipAttachIds.TryGetValue(obj.NetworkId, out newObj)) { if (GameModeNetworkObject.Length > 0 && GameModeNetworkObject[obj.CreateCode] != null) { var go = Instantiate(GameModeNetworkObject[obj.CreateCode]); newObj = go.GetComponent<NetworkBehavior>(); } } if (newObj == null) return; newObj.Initialize(obj); if (objectInitialized != null) objectInitialized(newObj, obj); }); } else if (obj is NetworkCameraNetworkObject) { MainThreadManager.Run(() => { NetworkBehavior newObj = null; if (!NetworkBehavior.skipAttachIds.TryGetValue(obj.NetworkId, out newObj)) { if (NetworkCameraNetworkObject.Length > 0 && NetworkCameraNetworkObject[obj.CreateCode] != null) { var go = Instantiate(NetworkCameraNetworkObject[obj.CreateCode]); newObj = go.GetComponent<NetworkBehavior>(); } } if (newObj == null) return; newObj.Initialize(obj); if (objectInitialized != null) objectInitialized(newObj, obj); }); } else if (obj is PlayerNetworkObject) { MainThreadManager.Run(() => { NetworkBehavior newObj = null; if (!NetworkBehavior.skipAttachIds.TryGetValue(obj.NetworkId, out newObj)) { if (PlayerNetworkObject.Length > 0 && PlayerNetworkObject[obj.CreateCode] != null) { var go = Instantiate(PlayerNetworkObject[obj.CreateCode]); newObj = go.GetComponent<NetworkBehavior>(); } } if (newObj == null) return; newObj.Initialize(obj); if (objectInitialized != null) objectInitialized(newObj, obj); }); } else if (obj is NPCNetworkObject) { MainThreadManager.Run(() => { NetworkBehavior newObj = null; if (!NetworkBehavior.skipAttachIds.TryGetValue(obj.NetworkId, out newObj)) { if (NPCNetworkObject.Length > 0 && NPCNetworkObject[obj.CreateCode] != null) { var go = Instantiate(NPCNetworkObject[obj.CreateCode]); newObj = go.GetComponent<NetworkBehavior>(); } } if (newObj == null) return; newObj.Initialize(obj); if (objectInitialized != null) objectInitialized(newObj, obj); }); } } private void InitializedObject(INetworkBehavior behavior, NetworkObject obj) { if (objectInitialized != null) objectInitialized(behavior, obj); obj.pendingInitialized -= InitializedObject; } [Obsolete("Use InstantiateChatManager instead, its shorter and easier to type out ;)")] public ChatManagerBehavior InstantiateChatManagerNetworkObject(int index = 0, Vector3? position = null, Quaternion? rotation = null, bool sendTransform = true) { var go = Instantiate(ChatManagerNetworkObject[index]); var netBehavior = go.GetComponent<ChatManagerBehavior>(); var obj = netBehavior.CreateNetworkObject(Networker, index); go.GetComponent<ChatManagerBehavior>().networkObject = (ChatManagerNetworkObject)obj; FinalizeInitialization(go, netBehavior, obj, position, rotation, sendTransform); return netBehavior; } [Obsolete("Use InstantiateCubeForgeGame instead, its shorter and easier to type out ;)")] public CubeForgeGameBehavior InstantiateCubeForgeGameNetworkObject(int index = 0, Vector3? position = null, Quaternion? rotation = null, bool sendTransform = true) { var go = Instantiate(CubeForgeGameNetworkObject[index]); var netBehavior = go.GetComponent<CubeForgeGameBehavior>(); var obj = netBehavior.CreateNetworkObject(Networker, index); go.GetComponent<CubeForgeGameBehavior>().networkObject = (CubeForgeGameNetworkObject)obj; FinalizeInitialization(go, netBehavior, obj, position, rotation, sendTransform); return netBehavior; } [Obsolete("Use InstantiateGameLogic instead, its shorter and easier to type out ;)")] public GameLogicBehavior InstantiateGameLogicNetworkObject(int index = 0, Vector3? position = null, Quaternion? rotation = null, bool sendTransform = true) { var go = Instantiate(GameLogicNetworkObject[index]); var netBehavior = go.GetComponent<GameLogicBehavior>(); var obj = netBehavior.CreateNetworkObject(Networker, index); go.GetComponent<GameLogicBehavior>().networkObject = (GameLogicNetworkObject)obj; FinalizeInitialization(go, netBehavior, obj, position, rotation, sendTransform); return netBehavior; } [Obsolete("Use InstantiateGameMode instead, its shorter and easier to type out ;)")] public GameModeBehavior InstantiateGameModeNetworkObject(int index = 0, Vector3? position = null, Quaternion? rotation = null, bool sendTransform = true) { var go = Instantiate(GameModeNetworkObject[index]); var netBehavior = go.GetComponent<GameModeBehavior>(); var obj = netBehavior.CreateNetworkObject(Networker, index); go.GetComponent<GameModeBehavior>().networkObject = (GameModeNetworkObject)obj; FinalizeInitialization(go, netBehavior, obj, position, rotation, sendTransform); return netBehavior; } [Obsolete("Use InstantiateNetworkCamera instead, its shorter and easier to type out ;)")] public NetworkCameraBehavior InstantiateNetworkCameraNetworkObject(int index = 0, Vector3? position = null, Quaternion? rotation = null, bool sendTransform = true) { var go = Instantiate(NetworkCameraNetworkObject[index]); var netBehavior = go.GetComponent<NetworkCameraBehavior>(); var obj = netBehavior.CreateNetworkObject(Networker, index); go.GetComponent<NetworkCameraBehavior>().networkObject = (NetworkCameraNetworkObject)obj; FinalizeInitialization(go, netBehavior, obj, position, rotation, sendTransform); return netBehavior; } [Obsolete("Use InstantiatePlayer instead, its shorter and easier to type out ;)")] public PlayerBehavior InstantiatePlayerNetworkObject(int index = 0, Vector3? position = null, Quaternion? rotation = null, bool sendTransform = true) { var go = Instantiate(PlayerNetworkObject[index]); var netBehavior = go.GetComponent<PlayerBehavior>(); var obj = netBehavior.CreateNetworkObject(Networker, index); go.GetComponent<PlayerBehavior>().networkObject = (PlayerNetworkObject)obj; FinalizeInitialization(go, netBehavior, obj, position, rotation, sendTransform); return netBehavior; } [Obsolete("Use InstantiateNPC instead, its shorter and easier to type out ;)")] public NPCBehavior InstantiateNPCNetworkObject(int index = 0, Vector3? position = null, Quaternion? rotation = null, bool sendTransform = true) { var go = Instantiate(NPCNetworkObject[index]); var netBehavior = go.GetComponent<NPCBehavior>(); var obj = netBehavior.CreateNetworkObject(Networker, index); go.GetComponent<NPCBehavior>().networkObject = (NPCNetworkObject)obj; FinalizeInitialization(go, netBehavior, obj, position, rotation, sendTransform); return netBehavior; } public ChatManagerBehavior InstantiateChatManager(int index = 0, Vector3? position = null, Quaternion? rotation = null, bool sendTransform = true) { var go = Instantiate(ChatManagerNetworkObject[index]); var netBehavior = go.GetComponent<ChatManagerBehavior>(); NetworkObject obj = null; if (!sendTransform && position == null && rotation == null) obj = netBehavior.CreateNetworkObject(Networker, index); else { metadata.Clear(); if (position == null && rotation == null) { metadata.Clear(); byte transformFlags = 0x1 | 0x2; ObjectMapper.Instance.MapBytes(metadata, transformFlags); ObjectMapper.Instance.MapBytes(metadata, go.transform.position, go.transform.rotation); } else { byte transformFlags = 0x0; transformFlags |= (byte)(position != null ? 0x1 : 0x0); transformFlags |= (byte)(rotation != null ? 0x2 : 0x0); ObjectMapper.Instance.MapBytes(metadata, transformFlags); if (position != null) ObjectMapper.Instance.MapBytes(metadata, position.Value); if (rotation != null) ObjectMapper.Instance.MapBytes(metadata, rotation.Value); } obj = netBehavior.CreateNetworkObject(Networker, index, metadata.CompressBytes()); } go.GetComponent<ChatManagerBehavior>().networkObject = (ChatManagerNetworkObject)obj; FinalizeInitialization(go, netBehavior, obj, position, rotation, sendTransform); return netBehavior; } public CubeForgeGameBehavior InstantiateCubeForgeGame(int index = 0, Vector3? position = null, Quaternion? rotation = null, bool sendTransform = true) { var go = Instantiate(CubeForgeGameNetworkObject[index]); var netBehavior = go.GetComponent<CubeForgeGameBehavior>(); NetworkObject obj = null; if (!sendTransform && position == null && rotation == null) obj = netBehavior.CreateNetworkObject(Networker, index); else { metadata.Clear(); if (position == null && rotation == null) { metadata.Clear(); byte transformFlags = 0x1 | 0x2; ObjectMapper.Instance.MapBytes(metadata, transformFlags); ObjectMapper.Instance.MapBytes(metadata, go.transform.position, go.transform.rotation); } else { byte transformFlags = 0x0; transformFlags |= (byte)(position != null ? 0x1 : 0x0); transformFlags |= (byte)(rotation != null ? 0x2 : 0x0); ObjectMapper.Instance.MapBytes(metadata, transformFlags); if (position != null) ObjectMapper.Instance.MapBytes(metadata, position.Value); if (rotation != null) ObjectMapper.Instance.MapBytes(metadata, rotation.Value); } obj = netBehavior.CreateNetworkObject(Networker, index, metadata.CompressBytes()); } go.GetComponent<CubeForgeGameBehavior>().networkObject = (CubeForgeGameNetworkObject)obj; FinalizeInitialization(go, netBehavior, obj, position, rotation, sendTransform); return netBehavior; } public GameLogicBehavior InstantiateGameLogic(int index = 0, Vector3? position = null, Quaternion? rotation = null, bool sendTransform = true) { var go = Instantiate(GameLogicNetworkObject[index]); var netBehavior = go.GetComponent<GameLogicBehavior>(); NetworkObject obj = null; if (!sendTransform && position == null && rotation == null) obj = netBehavior.CreateNetworkObject(Networker, index); else { metadata.Clear(); if (position == null && rotation == null) { metadata.Clear(); byte transformFlags = 0x1 | 0x2; ObjectMapper.Instance.MapBytes(metadata, transformFlags); ObjectMapper.Instance.MapBytes(metadata, go.transform.position, go.transform.rotation); } else { byte transformFlags = 0x0; transformFlags |= (byte)(position != null ? 0x1 : 0x0); transformFlags |= (byte)(rotation != null ? 0x2 : 0x0); ObjectMapper.Instance.MapBytes(metadata, transformFlags); if (position != null) ObjectMapper.Instance.MapBytes(metadata, position.Value); if (rotation != null) ObjectMapper.Instance.MapBytes(metadata, rotation.Value); } obj = netBehavior.CreateNetworkObject(Networker, index, metadata.CompressBytes()); } go.GetComponent<GameLogicBehavior>().networkObject = (GameLogicNetworkObject)obj; FinalizeInitialization(go, netBehavior, obj, position, rotation, sendTransform); return netBehavior; } public GameModeBehavior InstantiateGameMode(int index = 0, Vector3? position = null, Quaternion? rotation = null, bool sendTransform = true) { var go = Instantiate(GameModeNetworkObject[index]); var netBehavior = go.GetComponent<GameModeBehavior>(); NetworkObject obj = null; if (!sendTransform && position == null && rotation == null) obj = netBehavior.CreateNetworkObject(Networker, index); else { metadata.Clear(); if (position == null && rotation == null) { metadata.Clear(); byte transformFlags = 0x1 | 0x2; ObjectMapper.Instance.MapBytes(metadata, transformFlags); ObjectMapper.Instance.MapBytes(metadata, go.transform.position, go.transform.rotation); } else { byte transformFlags = 0x0; transformFlags |= (byte)(position != null ? 0x1 : 0x0); transformFlags |= (byte)(rotation != null ? 0x2 : 0x0); ObjectMapper.Instance.MapBytes(metadata, transformFlags); if (position != null) ObjectMapper.Instance.MapBytes(metadata, position.Value); if (rotation != null) ObjectMapper.Instance.MapBytes(metadata, rotation.Value); } obj = netBehavior.CreateNetworkObject(Networker, index, metadata.CompressBytes()); } go.GetComponent<GameModeBehavior>().networkObject = (GameModeNetworkObject)obj; FinalizeInitialization(go, netBehavior, obj, position, rotation, sendTransform); return netBehavior; } public NetworkCameraBehavior InstantiateNetworkCamera(int index = 0, Vector3? position = null, Quaternion? rotation = null, bool sendTransform = true) { var go = Instantiate(NetworkCameraNetworkObject[index]); var netBehavior = go.GetComponent<NetworkCameraBehavior>(); NetworkObject obj = null; if (!sendTransform && position == null && rotation == null) obj = netBehavior.CreateNetworkObject(Networker, index); else { metadata.Clear(); if (position == null && rotation == null) { metadata.Clear(); byte transformFlags = 0x1 | 0x2; ObjectMapper.Instance.MapBytes(metadata, transformFlags); ObjectMapper.Instance.MapBytes(metadata, go.transform.position, go.transform.rotation); } else { byte transformFlags = 0x0; transformFlags |= (byte)(position != null ? 0x1 : 0x0); transformFlags |= (byte)(rotation != null ? 0x2 : 0x0); ObjectMapper.Instance.MapBytes(metadata, transformFlags); if (position != null) ObjectMapper.Instance.MapBytes(metadata, position.Value); if (rotation != null) ObjectMapper.Instance.MapBytes(metadata, rotation.Value); } obj = netBehavior.CreateNetworkObject(Networker, index, metadata.CompressBytes()); } go.GetComponent<NetworkCameraBehavior>().networkObject = (NetworkCameraNetworkObject)obj; FinalizeInitialization(go, netBehavior, obj, position, rotation, sendTransform); return netBehavior; } public PlayerBehavior InstantiatePlayer(int index = 0, Vector3? position = null, Quaternion? rotation = null, bool sendTransform = true) { var go = Instantiate(PlayerNetworkObject[index]); var netBehavior = go.GetComponent<PlayerBehavior>(); NetworkObject obj = null; if (!sendTransform && position == null && rotation == null) obj = netBehavior.CreateNetworkObject(Networker, index); else { metadata.Clear(); if (position == null && rotation == null) { metadata.Clear(); byte transformFlags = 0x1 | 0x2; ObjectMapper.Instance.MapBytes(metadata, transformFlags); ObjectMapper.Instance.MapBytes(metadata, go.transform.position, go.transform.rotation); } else { byte transformFlags = 0x0; transformFlags |= (byte)(position != null ? 0x1 : 0x0); transformFlags |= (byte)(rotation != null ? 0x2 : 0x0); ObjectMapper.Instance.MapBytes(metadata, transformFlags); if (position != null) ObjectMapper.Instance.MapBytes(metadata, position.Value); if (rotation != null) ObjectMapper.Instance.MapBytes(metadata, rotation.Value); } obj = netBehavior.CreateNetworkObject(Networker, index, metadata.CompressBytes()); } go.GetComponent<PlayerBehavior>().networkObject = (PlayerNetworkObject)obj; FinalizeInitialization(go, netBehavior, obj, position, rotation, sendTransform); return netBehavior; } public NPCBehavior InstantiateNPC(int index = 0, Vector3? position = null, Quaternion? rotation = null, bool sendTransform = true) { var go = Instantiate(NPCNetworkObject[index]); var netBehavior = go.GetComponent<NPCBehavior>(); NetworkObject obj = null; if (!sendTransform && position == null && rotation == null) obj = netBehavior.CreateNetworkObject(Networker, index); else { metadata.Clear(); if (position == null && rotation == null) { metadata.Clear(); byte transformFlags = 0x1 | 0x2; ObjectMapper.Instance.MapBytes(metadata, transformFlags); ObjectMapper.Instance.MapBytes(metadata, go.transform.position, go.transform.rotation); } else { byte transformFlags = 0x0; transformFlags |= (byte)(position != null ? 0x1 : 0x0); transformFlags |= (byte)(rotation != null ? 0x2 : 0x0); ObjectMapper.Instance.MapBytes(metadata, transformFlags); if (position != null) ObjectMapper.Instance.MapBytes(metadata, position.Value); if (rotation != null) ObjectMapper.Instance.MapBytes(metadata, rotation.Value); } obj = netBehavior.CreateNetworkObject(Networker, index, metadata.CompressBytes()); } go.GetComponent<NPCBehavior>().networkObject = (NPCNetworkObject)obj; FinalizeInitialization(go, netBehavior, obj, position, rotation, sendTransform); return netBehavior; } } }
//! \file ImageBMD.cs //! \date Wed Mar 25 09:35:06 2015 //! \brief Black Rainbow BMD image format implementation. // // Copyright (C) 2015 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics; using System.IO; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using GameRes.Compression; using GameRes.Utility; namespace GameRes.Formats.BlackRainbow { internal class BmdMetaData : ImageMetaData { public uint PackedSize; public int Flag; } [Export(typeof(ImageFormat))] public class BmdFormat : ImageFormat { public override string Tag { get { return "BMD"; } } public override string Description { get { return "Black Rainbow bitmap format"; } } public override uint Signature { get { return 0x444d425fu; } } // '_BMD' public override ImageMetaData ReadMetaData (Stream stream) { var header = new byte[0x14]; if (header.Length != stream.Read (header, 0, header.Length)) return null; return new BmdMetaData { Width = LittleEndian.ToUInt32 (header, 8), Height = LittleEndian.ToUInt32 (header, 12), BPP = 32, PackedSize = LittleEndian.ToUInt32 (header, 4), Flag = LittleEndian.ToInt32 (header, 0x10), }; } public override ImageData Read (Stream stream, ImageMetaData info) { var meta = info as BmdMetaData; if (null == meta) throw new ArgumentException ("BmdFormat.Read should be supplied with BmdMetaData", "info"); stream.Position = 0x14; int image_size = (int)(meta.Width*meta.Height*4); using (var reader = new LzssReader (stream, (int)meta.PackedSize, image_size)) { PixelFormat format = meta.Flag != 0 ? PixelFormats.Bgra32 : PixelFormats.Bgr32; reader.Unpack(); return ImageData.Create (meta, format, null, reader.Data, (int)meta.Width*4); } } public override void Write (Stream file, ImageData image) { using (var output = new BinaryWriter (file, Encoding.ASCII, true)) using (var writer = new Writer (image.Bitmap)) { writer.Pack(); output.Write (Signature); output.Write (writer.Size); output.Write (image.Width); output.Write (image.Height); output.Write (writer.HasAlpha ? 1 : 0); output.Write (writer.Data, 0, (int)writer.Size); } } internal class Writer : IDisposable { const int MinChunkSize = 3; const int MaxChunkSize = MinChunkSize+0xf; const int FrameSize = 0x1000; byte[] m_input; MemoryStream m_output; bool m_has_alpha = false; byte[] m_frame = new byte[FrameSize]; public byte[] Data { get { return m_output.GetBuffer(); } } public uint Size { get { return (uint)m_output.Length; } } public bool HasAlpha { get { return m_has_alpha; } } public Writer (BitmapSource bitmap) { if (bitmap.Format != PixelFormats.Bgra32) bitmap = new FormatConvertedBitmap (bitmap, PixelFormats.Bgra32, null, 0); m_input = new byte[bitmap.PixelWidth*bitmap.PixelHeight*4]; bitmap.CopyPixels (m_input, bitmap.PixelWidth*4, 0); for (int i = 3; i < m_input.Length; i += 4) { if (0xff != m_input[i]) { m_has_alpha = true; break; } } if (!m_has_alpha) for (int i = 3; i < m_input.Length; i += 4) m_input[i] = 0; m_output = new MemoryStream(); } public void Pack () { int frame_pos = 0x1000 - 18; int src = 0; while (src < m_input.Length) { int chunk_size; int offset = FindChunk (src, out chunk_size); if (-1 == offset) { PutByte (m_input[src]); chunk_size = 1; } else PutChunk (offset, chunk_size); for (int i = 0; i < chunk_size; ++i) { m_frame[frame_pos++] = m_input[src++]; frame_pos &= 0xfff; } } Flush(); } struct Chunk { public short Offset; public byte Data; public Chunk (byte b) { Offset = -1; Data = b; } public Chunk (int offset, int count) { Debug.Assert (offset < 0x1000 && count >= MinChunkSize && count <= MaxChunkSize); Offset = (short)offset; Data = (byte)((count - MinChunkSize) & 0x0f); } } List<Chunk> m_queue = new List<Chunk> (8); void PutByte (byte b) { m_queue.Add (new Chunk (b)); if (8 == m_queue.Count) Flush(); } void PutChunk (int offset, int size) { m_queue.Add (new Chunk (offset, size)); if (8 == m_queue.Count) Flush(); } void Flush () { if (0 == m_queue.Count) return; int ctl = 0; int bit = 1; for (int i = 0; i < m_queue.Count; ++i) { if (m_queue[i].Offset < 0) ctl |= bit; bit <<= 1; } m_output.WriteByte ((byte)ctl); for (int i = 0; i < m_queue.Count; ++i) { var chunk = m_queue[i]; if (chunk.Offset >= 0) { byte lo = (byte)(chunk.Offset & 0xff); byte hi = (byte)((chunk.Offset & 0xf00) >> 4); hi |= chunk.Data; m_output.WriteByte (lo); m_output.WriteByte (hi); } else m_output.WriteByte (chunk.Data); } m_queue.Clear(); } private int FindChunk (int pos, out int size) { size = 0; int chunk_limit = Math.Min (MaxChunkSize, m_input.Length-pos); if (chunk_limit < MinChunkSize) return -1; int offset = -1; for (int i = 0; i < m_frame.Length; ) { int first = Array.IndexOf (m_frame, m_input[pos], i); if (-1 == first) break; int j = 1; while (j < chunk_limit && m_frame[(first+j)&0xfff] == m_input[pos+j]) ++j; if (j > size && j >= MinChunkSize) { offset = first; size = j; if (chunk_limit == j) break; } i = first + 1; } return offset; } #region IDisposable Members bool disposed = false; public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } protected virtual void Dispose (bool disposing) { if (!disposed) { if (disposing) { m_output.Dispose(); } disposed = true; } } #endregion } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Windows.Forms; using System.Xml; namespace Krystals4ObjectLibrary { #region helper classes /// <summary> /// The struct returned by the Enumerable property Krystal.LeveledValues. /// Each value in the krystal is returned with its level. /// The first value in each strand has the strand's level. /// All other values have a level equal to the krystal's level + 1. /// </summary> public struct LeveledValue { public int level; public int value; } /// <summary> /// this class contains strand parameters, and is used to build the _strandNodeList for an expansion. /// The _strandNodeList is used as a parameter in the following constructors: /// FieldEditor.Painter /// FieldEditor.ExpansionTreeView /// FieldEditor.Expansion /// </summary> public class StrandNode : TreeNode { public StrandNode(int moment, int level, int density, int point) { strandMoment = moment; strandLevel = level; strandDensity = density; strandPoint = point; } public int strandMoment; public int strandLevel; public int strandDensity; public int strandPoint; } public class ContouredStrandNode : StrandNode { public ContouredStrandNode(int moment, int level, int density, int point, int axis, int contour) : base(moment, level, density, point) { strandAxis = axis; strandContour = contour; } public int strandAxis; public int strandContour; } #endregion helper classes public interface INamedComparable : IComparable { string Name { get; } } public abstract class Krystal : INamedComparable { public Krystal() { } public Krystal(string filepath) { string filename = Path.GetFileName(filepath); try { using(XmlReader r = XmlReader.Create(filepath)) { _name = Path.GetFileName(filepath); _minValue = uint.MaxValue; _maxValue = uint.MinValue; K.ReadToXmlElementTag(r, "krystal"); // check that this is a krystal // ignore the heredity info in the next element (<expansion> etc.) K.ReadToXmlElementTag(r, "strands"); // check that there is a "strands" element // get the strands and their related variables K.ReadToXmlElementTag(r, "s"); while(r.Name == "s") { Strand strand = new Strand(r); _level = (_level < strand.Level) ? strand.Level : _level; foreach(uint value in strand.Values) { _minValue = (_minValue < value) ? _minValue : value; _maxValue = (_maxValue < value) ? value : _maxValue; } _numValues += (uint)strand.Values.Count; _strands.Add(strand); } // r.Name is the end tag "strands" here } } catch(Exception ex) { throw (ex); } } #region public functions /// <summary> /// Updates the strand-related Properties Strands, Level, MinValue, MaxValue and NumValues /// using the given list of strands. /// </summary> /// <param name="strands"></param> public void Update(List<Strand> strands) { _strands = strands; _level = 0; _minValue = uint.MaxValue; _maxValue = uint.MinValue; _numValues = 0; foreach(Strand strand in strands) { _numValues += (uint)strand.Values.Count; _level = (_level < strand.Level) ? strand.Level : _level; foreach(uint value in strand.Values) { _minValue = (_minValue < value) ? _minValue : value; _maxValue = (_maxValue < value) ? value : _maxValue; } } } /// <summary> /// Saves the krystal and any non-krystal associated files (e.g. expander or modulator). /// If overwrite is true, the file(s) are overwritten if they exist. /// </summary> /// <param name="overwrite"></param> public abstract void Save(bool overwrite); /// <summary> /// This function returns 0 if the shape and numeric content are the same, /// Otherwise it compares the two names. /// </summary> /// <param name="otherKrystal"></param> /// <returns></returns> public int CompareTo(object other) { if(!(other is Krystal otherKrystal)) throw new ArgumentException(); bool isEquivalent = false; if(this.Shape == otherKrystal.Shape && this.Strands.Count == otherKrystal.Strands.Count && this.Level == otherKrystal.Level && this.MaxValue == otherKrystal.MaxValue && this.MinValue == otherKrystal.MinValue && this.NumValues == otherKrystal.NumValues && this.MissingValues == otherKrystal.MissingValues) { isEquivalent = true; for(int i = 0; i < this.Strands.Count; i++) { Strand thisStrand = this.Strands[i]; Strand otherStrand = otherKrystal.Strands[i]; if(thisStrand.Values.Count != otherStrand.Values.Count || thisStrand.Level != otherStrand.Level) { isEquivalent = false; break; } for(int j = 0; j < thisStrand.Values.Count; j++) { if(thisStrand.Values[j] != otherStrand.Values[j]) { isEquivalent = false; break; } } } } if(isEquivalent == true) return 0; else return this.Name.CompareTo(otherKrystal.Name); } /// <summary> /// Recreates this krystal using its existing inputs, without opening an editor. /// Used to preserve the integrity of a group of krystals, when one of them has changed. /// </summary> public abstract void Rebuild(); public override string ToString() { return this._name; } /// <summary> /// This krystal can be permuted at the given level if it has less then 7 elements at that level. /// </summary> /// <param name="level"></param> /// <returns></returns> public bool IsPermutableAtLevel(uint level) { bool isPermutableAtLevel = true; int nElements = 0; if(level > this.Level || level < 1) { isPermutableAtLevel = false; } else if(level < this.Level) { foreach(Strand strand in this.Strands) { if(strand.Level <= level) { nElements = 1; } else if(strand.Level == level + 1) { nElements++; if(nElements > 7) { isPermutableAtLevel = false; break; } } } } else // level == this.Level { foreach(Strand strand in this.Strands) { if(strand.Values.Count > 7) { isPermutableAtLevel = false; break; } } } return isPermutableAtLevel; } /// <summary> /// Returns the flat krystal values, spread over the range [minEnvValue..maxEnvValue], /// as an Envelope. /// </summary> /// <param name="minEnvValue"></param> /// <param name="maxEnvValue"></param> /// <returns></returns> public Envelope ToEnvelope(int minEnvValue, int maxEnvValue) { List<int> substituteValues = new List<int>(); double incr = ((double)(maxEnvValue - minEnvValue)) / (MaxValue - MinValue); for(int i = (int)MinValue; i < (MaxValue + 1); i++) { substituteValues.Add((int) Math.Round(minEnvValue + (incr * (i - 1)))); } List<int> kValues = GetValues(1)[0]; for(int i = 0; i < kValues.Count; i++) { kValues[i] = substituteValues[kValues[i] - 1]; } Envelope envelope = new Envelope(kValues, maxEnvValue, maxEnvValue, kValues.Count); return envelope; } #endregion public functions #region protected functions /// <summary> /// Finds an identical, already saved krystal /// </summary> /// <param name="nameIntro">one of "ck", "lk", "mk", "xk", "sk"</param> /// <returns></returns> protected string GetNameOfEquivalentSavedKrystal(string nameIntro) { Debug.Assert(_name == "" || _name == K.UntitledKrystalName); string newName = ""; DirectoryInfo dir = new DirectoryInfo(K.KrystalsFolder); Krystal otherKrystal = null; foreach(FileInfo fileInfo in dir.GetFiles("*.krys")) { if(fileInfo.Name[0] == nameIntro[0]) { switch(fileInfo.Name[0]) { case 'c': otherKrystal = new ConstantKrystal(K.KrystalsFolder + @"\" + fileInfo.Name); break; case 'l': otherKrystal = new LineKrystal(K.KrystalsFolder + @"\" + fileInfo.Name); break; case 'm': otherKrystal = new ModulationKrystal(K.KrystalsFolder + @"\" + fileInfo.Name); break; case 'p': otherKrystal = new PermutationKrystal(K.KrystalsFolder + @"\" + fileInfo.Name); break; case 's': otherKrystal = new ShapedExpansionKrystal(K.KrystalsFolder + @"\" + fileInfo.Name); break; case 'x': otherKrystal = new ExpansionKrystal(K.KrystalsFolder + @"\" + fileInfo.Name); break; } if(this.CompareTo(otherKrystal) == 0) { newName = otherKrystal.Name; break; } } } return newName; } protected XmlWriter BeginSaveKrystal() { XmlWriterSettings settings = new XmlWriterSettings { Indent = true, IndentChars = ("\t"), CloseOutput = true }; string namePath = K.KrystalsFolder + @"\" + _name; XmlWriter w = XmlWriter.Create(namePath, settings); w.WriteStartDocument(); w.WriteComment("created: " + K.Now); w.WriteStartElement("krystal"); // ended in EndSaveKrystal() w.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance"); w.WriteAttributeString("xsi", "noNamespaceSchemaLocation", null, K.MoritzXmlSchemasFolder + @"\krystals.xsd"); return w; } protected void EndSaveKrystal(XmlWriter w) { w.WriteStartElement("strands"); foreach(Strand strand in _strands) { w.WriteStartElement("s"); w.WriteAttributeString("l", strand.Level.ToString()); w.WriteString(K.GetStringOfUnsignedInts(strand.Values)); w.WriteEndElement(); } w.WriteEndElement(); // ends the strands w.WriteEndElement(); // ends the krystal element w.Close(); // closes the stream and (I think) disposes of w } #endregion protected functions #region public properties public string Name { get { return _name; } set { _name = value; } } public uint Level { get { return _level; } set { _level = value; } } public uint MinValue { get { return _minValue; } } public uint MaxValue { get { return _maxValue; } } public uint NumValues { get { return _numValues; } } public List<Strand> Strands { get { return _strands; } } /// <summary> /// A string of comma-separated values not contained in the krystal /// </summary> public string MissingValues { get { int[] nValues = new int[this._maxValue + 1]; foreach(Strand strand in this._strands) foreach(uint value in strand.Values) nValues[value]++; StringBuilder sb = new StringBuilder(); for(uint i = _minValue; i <= this._maxValue; i++) if(nValues[i] == 0) { sb.Append(", "); sb.Append(i.ToString()); } if(sb.Length > 0) sb.Remove(0, 2); else sb.Append("(none)"); return sb.ToString(); } } /// <summary> /// At level 1, length is always 1. /// At level krystal.Level, length is the total number of strands. /// At level krystal.Level + 1, length is the total number of strand values. /// An ArgumentOutOfRangeException is thrown if the argument is outside the range 1..krystal.Level + 1. /// </summary> /// <param name="level">Must be in range 1..krystal.Level+1</param> /// <returns>The number of elements at the given level.</returns> public int GetLength(uint level) { level--; if(level < 0 || level > _level) throw new ArgumentOutOfRangeException("Error in Krystal.GetLength()."); int[] shapeArray = ShapeArray; return shapeArray[level]; } /// <summary> /// At level 1, the single int list contains all the strand values as a single list. /// At level krystal.Level, each internal int list contains the values from a single strand. /// At level krystal.Level + 1, each internal int list contains a single strand value. /// An ArgumentOutOfRangeException is thrown if the argument is outside the range 1..krystal.Level + 1. /// </summary> /// <param name="level">Must be in range 1..krystal.Level+1</param> /// <returns>The values in the krystal as a list of int lists.</returns> public List<List<int>> GetValues(uint level) { if(level < 1 || level > _level + 1) throw new ArgumentOutOfRangeException("Error in Krystal.GetValues()."); List<List<int>> returnList = new List<List<int>>(); int[] shapeArray = ShapeArray; int nInternalLists = shapeArray[level-1]; for(int i = 0; i < nInternalLists; i++) { List<int> internalList = new List<int>(); returnList.Add(internalList); } int returnListIndex = -1; foreach(Strand strand in this._strands) { if(level == _level + 1) { foreach(uint value in strand.Values) { returnListIndex++; returnList[returnListIndex].Add((int)value); } } else { if(strand.Level <= level) returnListIndex++; foreach(uint value in strand.Values) returnList[returnListIndex].Add((int)value); } } return returnList; } /// <summary> /// The total number of values in the returned list of int lists is equal to the number of values in /// the larger krystal. Each inner list corresponds to a value in this krystal, and contains that value /// repeated the appropriate number of times. /// Values in this krystal's strands are repeated according to the shape of the larger krystal. /// Restrictions: /// 1. the level of the largerKrystal must be greater than the level of this krystal. /// 2. the shape of this krystal must be contained in the shape of the larger krystal. /// </summary> /// <param name="largerKrystal"></param> /// <returns></returns> public List<List<int>> GetValuePerValue(Krystal largerKrystal) { Debug.Assert(largerKrystal.Shape.Contains(this.Shape)); Debug.Assert(largerKrystal.Level > this.Level); List<List<int>> returnValue = new List<List<int>>(); List<List<int>> largerValues = largerKrystal.GetValues(this.Level + 1); // each list in largerValues corresponds to a value in this krystal int thisStrandIndex = 0; int thisValueIndex = 0; uint thisValue = this.Strands[thisStrandIndex].Values[thisValueIndex]; foreach(List<int> listInt in largerValues) { List<int> innerList = new List<int>(); returnValue.Add(innerList); foreach(int i in listInt) innerList.Add((int)thisValue); thisValueIndex++; if(thisValueIndex == this.Strands[thisStrandIndex].Values.Count) { thisValueIndex = 0; thisStrandIndex++; } if(thisStrandIndex < this.Strands.Count) thisValue = this.Strands[thisStrandIndex].Values[thisValueIndex]; } return returnValue; } private int[] ShapeArray { get { int[] shapeArray = new int[this._level + 1]; foreach(Strand strand in this._strands) { for(uint i = strand.Level; i <= this._level; i++) shapeArray[i - 1] += 1; shapeArray[this._level] += strand.Values.Count; } return shapeArray; } } /// <summary> /// A string of " : " separated values showing the final clock sizes /// </summary> public string Shape { get { string shapeString = ""; if(this._level > 0) { int[] shapeArray = ShapeArray; StringBuilder shapeStrB = new StringBuilder(); for(int i = 0; i <= this._level; i++) { shapeStrB.Append(" : "); shapeStrB.Append(shapeArray[i].ToString()); } shapeStrB.Remove(0, 3); shapeString = shapeStrB.ToString(); } return shapeString; } } #endregion public properties #region protected variables protected string _name; // Used by status line: changed ONLY when writing a newly created krystal's XML protected uint _level; // the maximum level of any strand in the krystal protected uint _minValue; // the minimum value in the krystal protected uint _maxValue; // the maximum value in the krystal protected uint _numValues; // the number of values in the krystal protected List<Strand> _strands = new List<Strand>(); #endregion protected variables } public sealed class ConstantKrystal : Krystal { /// <summary> /// Constructor used for loading a constant krystal from a file /// </summary> public ConstantKrystal(string filepath) : base(filepath) { string filename = Path.GetFileName(filepath); using(XmlReader r = XmlReader.Create(filepath)) { K.ReadToXmlElementTag(r, "constant"); // check that this is a constant krystal (the other checks have been done in base()) } } /// <summary> /// Constructor used when creating new constants /// </summary> /// <param name="originalName"></param> /// <param name="value"></param> public ConstantKrystal(string originalName, uint value) : base() { _name = originalName; _level = 0; _minValue = _maxValue = value; _numValues = 1; List<uint> valueList = new List<uint> { value }; Strand strand = new Strand(0, valueList); _strands.Add(strand); } #region overridden functions public override void Save(bool overwrite) { _name = String.Format("ck0({0}){1}", this.MaxValue, K.KrystalFilenameSuffix); if(File.Exists(K.KrystalsFolder + @"\" + _name) == false || overwrite) { XmlWriter w = base.BeginSaveKrystal(); // disposed of in EndSaveKrystal #region save heredity info (only that this is a constant...) w.WriteStartElement("constant"); w.WriteEndElement(); // constant #endregion base.EndSaveKrystal(w); // saves the strands, closes the document, disposes of w } string msg = "Constant krystal saved as \r\n\r\n" + " " + _name; MessageBox.Show(msg, "Saved", MessageBoxButtons.OK, MessageBoxIcon.Information); } public override void Rebuild() { // This function does nothing. Constant krystals are not dependent on other krystals! throw new Exception("The method or operation is deliberately not implemented."); } #endregion overridden functions } public sealed class LineKrystal : Krystal { /// <summary> /// Constructor used for loading a line krystal from a file /// </summary> public LineKrystal(string filepath) : base(filepath) { string filename = Path.GetFileName(filepath); using(XmlReader r = XmlReader.Create(filepath)) { K.ReadToXmlElementTag(r, "line"); // check that this is a line krystal (the other checks have been done in base() } } /// <summary> /// Constructor used when creating new line krystals /// </summary> /// <param name="originalName"></param> /// <param name="values"></param> public LineKrystal(string originalName, string values) : base() { _name = originalName; _level = 1; List<uint> valueList = K.GetUIntList(values); _numValues = (uint)valueList.Count; _minValue = uint.MaxValue; _maxValue = uint.MinValue; foreach(uint value in valueList) { _minValue = _minValue < value ? _minValue : value; _maxValue = _maxValue > value ? _maxValue : value; } Strand strand = new Strand(1, valueList); _strands.Add(strand); } #region overridden functions public override void Save(bool overwrite) { string pathname; bool alreadyExisted = true; if(_name != null && _name.Equals(K.UntitledKrystalName)) _name = base.GetNameOfEquivalentSavedKrystal("lk"); if(string.IsNullOrEmpty(_name)) { alreadyExisted = false; int fileIndex = 1; do { _name = String.Format("lk1({0})-{1}{2}", _maxValue, fileIndex, K.KrystalFilenameSuffix); pathname = K.KrystalsFolder + @"\" + _name; fileIndex++; } while(File.Exists(pathname)); } else pathname = K.KrystalsFolder + @"\" + _name; if(File.Exists(pathname) == false || overwrite) { XmlWriter w = base.BeginSaveKrystal(); // disposed of in EndSaveKrystal #region save heredity info (only that this is a line) w.WriteStartElement("line"); w.WriteEndElement(); // line #endregion base.EndSaveKrystal(w); // saves the strands, closes the document, disposes of w } StringBuilder msgSB = new StringBuilder("Line krystal:\r\n\r\n "); foreach(uint value in this.Strands[0].Values) { msgSB.Append(value.ToString() + " "); } msgSB.Append(" \r\n\r\nsaved as:"); msgSB.Append("\r\n\r\n " + _name + " "); if(alreadyExisted) { msgSB.Append("\r\n\r\n(This line krystal already existed.)"); } MessageBox.Show(msgSB.ToString(), "Saved", MessageBoxButtons.OK, MessageBoxIcon.None); } public override void Rebuild() { // This function does nothing. Line krystals are not dependent on other krystals! throw new Exception("The method or operation is deliberately not implemented."); } #endregion overridden functions } /// <summary> /// Krystals used as inputs to expansions, modulations etc. have this class. /// It contains strands, and functions for dealing with them, but no information /// about the krystal's constructor. /// </summary> public abstract class InputKrystal : Krystal { public InputKrystal(string filepath) : base(filepath) { GetAbsoluteValues(); GetMissingAbsoluteValues(); } #region Enumerable Properties // In order to use IEnumerable, include a "using System.Collections" statement. /// <summary> /// Each value in this krystal is returned with its level. /// The first value in each strand has the strand's level. All other values have this krystal's level + 1. /// </summary> public IEnumerable<LeveledValue> LeveledValues { get { LeveledValue leveledValue; int valueLevel = (int)this._level + 1; foreach(Strand strand in _strands) { leveledValue.level = (int)strand.Level; leveledValue.value = (int)strand.Values[0]; yield return leveledValue; if(strand.Values.Count > 1) for(int index = 1; index < strand.Values.Count; index++) { leveledValue.level = valueLevel; leveledValue.value = (int)strand.Values[index]; yield return leveledValue; } } } } #endregion Enumerable Properties #region public functions /// <summary> /// Dummy function. This should never be called. /// </summary> public override void Save(bool overwrite) { throw new ApplicationException("Input krystals cannot be saved (they have already been saved!)"); } /// <summary> /// Dummy function. This should never be called. /// </summary> public override void Rebuild() { throw new Exception("Input krystals are never regenerated (they have been regenerated already!)."); } /// <summary> /// Returns an array containing one value from this krystal per value in the master krystal. /// The master krystal may have the same or more levels than this krystal, but must have the same form /// as this krystal at this krystal's level. /// The master krystal may not have less levels than this krystal. If it has MORE levels, values /// from this krystal are repeated. /// </summary> /// <param name="masterKrystal"></param> public int[] AlignedValues(InputKrystal masterKrystal) { List<int> alignedValues = new List<int>(); int mValueIndex = 0; int mStrandIndex = 0; uint masterLevel = 1; int strandIndex = 0; int valueIndex = 0; while(strandIndex < _strands.Count) { uint valueLevel = _strands[strandIndex].Level; valueIndex = 0; while(valueIndex < _strands[strandIndex].Values.Count && mStrandIndex < masterKrystal.Strands.Count && mValueIndex < masterKrystal.Strands[mStrandIndex].Values.Count) { alignedValues.Add((int)_strands[strandIndex].Values[valueIndex]); mValueIndex++; if(mValueIndex == masterKrystal.Strands[mStrandIndex].Values.Count) { mValueIndex = 0; mStrandIndex++; if(mStrandIndex < masterKrystal.Strands.Count) masterLevel = masterKrystal.Strands[mStrandIndex].Level; } else masterLevel = masterKrystal.Level + 1; valueLevel = this._level + 1; if(valueLevel == masterLevel || (mValueIndex == 0 && valueLevel > masterLevel)) valueIndex++; } strandIndex++; } return alignedValues.ToArray(); } #endregion public functions #region properties public List<int> AbsoluteValues { get { return _absoluteValues; } } public List<int> MissingAbsoluteValues { get { return _missingAbsoluteValues; } } #endregion properties #region private functions /// <summary> /// Sets the AbsoluteValues property for this krystal. The absolute values are a list of the values /// which occur in the strands of this krystal (each value once). /// </summary> private void GetAbsoluteValues() { _absoluteValues = new List<int>(); if(_maxValue == _minValue) _absoluteValues.Add((int)_minValue); else { for(int i = (int)_minValue; i <= (int)_maxValue; i++) { bool found = false; foreach(Strand s in _strands) { foreach(uint value in s.Values) { if(i == (int)value) { found = true; break; } } if(found == true) break; } if(found) _absoluteValues.Add(i); } } } /// <summary> /// Sets the MissingAbsoluteValues property for this krystal. /// The actual values in a krystal need not be the complete set of values between 1 and MaxValue. /// The missing values are the values between 1 and MaxValue which do not occur /// in this krystal's strands. /// </summary> private void GetMissingAbsoluteValues() { _missingAbsoluteValues.Clear(); for(int i = 1; i < (int)MaxValue; i++) if(!_absoluteValues.Contains(i)) _missingAbsoluteValues.Add(i); } #endregion private functions #region private variables private List<int> _absoluteValues = new List<int>(); // set for the input values krystal of an expansion private List<int> _missingAbsoluteValues = new List<int>(); // set for the input values krystal of an expansion #endregion private variables } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.IO.Packaging; using System.Linq; using Microsoft.Internal.Web.Utils; using NuGet.Resources; namespace NuGet { public class ZipPackage : IPackage { private const string AssemblyReferencesDir = "lib"; private const string ResourceAssemblyExtension = ".resources.dll"; private const string CacheKeyFormat = "NUGET_ZIP_PACKAGE_{0}_{1}{2}"; private const string AssembliesCacheKey = "ASSEMBLIES"; private const string FilesCacheKey = "FILES"; private readonly bool _enableCaching; private static readonly string[] AssemblyReferencesExtensions = new[] { ".dll", ".exe", ".winmd" }; private static readonly TimeSpan CacheTimeout = TimeSpan.FromSeconds(15); // paths to exclude private static readonly string[] _excludePaths = new[] { "_rels", "package" }; // We don't store the steam itself, just a way to open the stream on demand // so we don't have to hold on to that resource private Func<Stream> _streamFactory; private HashSet<string> _references; public ZipPackage(string fileName) : this(fileName, enableCaching: false) { } public ZipPackage(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } _enableCaching = false; _streamFactory = stream.ToStreamFactory(); EnsureManifest(); } internal ZipPackage(string fileName, bool enableCaching) { if (String.IsNullOrEmpty(fileName)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "fileName"); } _enableCaching = enableCaching; _streamFactory = () => File.OpenRead(fileName); EnsureManifest(); } internal ZipPackage(Func<Stream> streamFactory, bool enableCaching) { if (streamFactory == null) { throw new ArgumentNullException("streamFactory"); } _enableCaching = enableCaching; _streamFactory = streamFactory; EnsureManifest(); } public string Id { get; set; } public SemanticVersion Version { get; set; } public string Title { get; set; } public IEnumerable<string> Authors { get; set; } public IEnumerable<string> Owners { get; set; } public Uri IconUrl { get; set; } public Uri LicenseUrl { get; set; } public Uri ProjectUrl { get; set; } public Uri ReportAbuseUrl { get { return null; } } public int DownloadCount { get { return -1; } } public bool RequireLicenseAcceptance { get; set; } public string Description { get; set; } public string Summary { get; set; } public string ReleaseNotes { get; set; } public string Language { get; set; } public string Tags { get; set; } public bool IsAbsoluteLatestVersion { get { return true; } } public bool IsLatestVersion { get { return this.IsReleaseVersion(); } } public bool Listed { get { return true; } } public DateTimeOffset? Published { get; set; } public string Copyright { get; set; } public IEnumerable<PackageDependency> Dependencies { get; set; } public IEnumerable<IPackageAssemblyReference> AssemblyReferences { get { if (_enableCaching) { return MemoryCache.Instance.GetOrAdd(GetAssembliesCacheKey(), GetAssembliesNoCache, CacheTimeout); } return GetAssembliesNoCache(); } } public IEnumerable<FrameworkAssemblyReference> FrameworkAssemblies { get; set; } public IEnumerable<IPackageFile> GetFiles() { if (_enableCaching) { return MemoryCache.Instance.GetOrAdd(GetFilesCacheKey(), GetFilesNoCache, CacheTimeout); } return GetFilesNoCache(); } public Stream GetStream() { return _streamFactory(); } private List<IPackageAssemblyReference> GetAssembliesNoCache() { return (from file in GetFiles() where IsAssemblyReference(file, _references) select (IPackageAssemblyReference)new ZipPackageAssemblyReference(file) ).ToList(); } private List<IPackageFile> GetFilesNoCache() { using (Stream stream = _streamFactory()) { Package package = Package.Open(stream); return (from part in package.GetParts() where IsPackageFile(part) select (IPackageFile)new ZipPackageFile(part)).ToList(); } } private void EnsureManifest() { using (Stream stream = _streamFactory()) { Package package = Package.Open(stream); PackageRelationship relationshipType = package.GetRelationshipsByType(Constants.PackageRelationshipNamespace + PackageBuilder.ManifestRelationType).SingleOrDefault(); if (relationshipType == null) { throw new InvalidOperationException(NuGetResources.PackageDoesNotContainManifest); } PackagePart manifestPart = package.GetPart(relationshipType.TargetUri); if (manifestPart == null) { throw new InvalidOperationException(NuGetResources.PackageDoesNotContainManifest); } using (Stream manifestStream = manifestPart.GetStream()) { Manifest manifest = Manifest.ReadFrom(manifestStream); IPackageMetadata metadata = manifest.Metadata; Id = metadata.Id; Version = metadata.Version; Title = metadata.Title; Authors = metadata.Authors; Owners = metadata.Owners; IconUrl = metadata.IconUrl; LicenseUrl = metadata.LicenseUrl; ProjectUrl = metadata.ProjectUrl; RequireLicenseAcceptance = metadata.RequireLicenseAcceptance; Description = metadata.Description; Summary = metadata.Summary; ReleaseNotes = metadata.ReleaseNotes; Language = metadata.Language; Tags = metadata.Tags; Dependencies = metadata.Dependencies; FrameworkAssemblies = metadata.FrameworkAssemblies; Copyright = metadata.Copyright; IEnumerable<string> references = (manifest.Metadata.References ?? Enumerable.Empty<ManifestReference>()).Select(c => c.File); _references = new HashSet<string>(references, StringComparer.OrdinalIgnoreCase); // Ensure tags start and end with an empty " " so we can do contains filtering reliably if (!String.IsNullOrEmpty(Tags)) { Tags = " " + Tags + " "; } } } } internal static bool IsAssemblyReference(IPackageFile file, IEnumerable<string> references) { // Assembly references are in lib/ and have a .dll/.exe/.winmd extension var path = file.Path; var fileName = Path.GetFileName(path); return path.StartsWith(AssemblyReferencesDir, StringComparison.OrdinalIgnoreCase) && // Exclude resource assemblies !path.EndsWith(ResourceAssemblyExtension, StringComparison.OrdinalIgnoreCase) && AssemblyReferencesExtensions.Contains(Path.GetExtension(path), StringComparer.OrdinalIgnoreCase) && // If references are listed, ensure that the file is listed in it. (references.IsEmpty() || references.Contains(fileName)); } private static bool IsPackageFile(PackagePart part) { string path = UriUtility.GetPath(part.Uri); // We exclude any opc files and the manifest file (.nuspec) return !_excludePaths.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase)) && !PackageUtility.IsManifest(path); } public override string ToString() { return this.GetFullName(); } private string GetFilesCacheKey() { return String.Format(CultureInfo.InvariantCulture, CacheKeyFormat, FilesCacheKey, Id, Version); } private string GetAssembliesCacheKey() { return String.Format(CultureInfo.InvariantCulture, CacheKeyFormat, AssembliesCacheKey, Id, Version); } internal static void ClearCache(IPackage package) { var zipPackage = package as ZipPackage; // Remove the cache entries for files and assemblies if (zipPackage != null) { MemoryCache.Instance.Remove(zipPackage.GetAssembliesCacheKey()); MemoryCache.Instance.Remove(zipPackage.GetFilesCacheKey()); } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Media.Animation.Vector3DKeyFrameCollection.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Media.Animation { public partial class Vector3DKeyFrameCollection : System.Windows.Freezable, System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable { #region Methods and constructors public int Add(Vector3DKeyFrame keyFrame) { return default(int); } public void Clear() { } public System.Windows.Media.Animation.Vector3DKeyFrameCollection Clone() { return default(System.Windows.Media.Animation.Vector3DKeyFrameCollection); } protected override void CloneCore(System.Windows.Freezable sourceFreezable) { } protected override void CloneCurrentValueCore(System.Windows.Freezable sourceFreezable) { } public bool Contains(Vector3DKeyFrame keyFrame) { return default(bool); } public void CopyTo(Vector3DKeyFrame[] array, int index) { } protected override System.Windows.Freezable CreateInstanceCore() { return default(System.Windows.Freezable); } protected override bool FreezeCore(bool isChecking) { return default(bool); } protected override void GetAsFrozenCore(System.Windows.Freezable sourceFreezable) { } protected override void GetCurrentValueAsFrozenCore(System.Windows.Freezable sourceFreezable) { } public System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); } public int IndexOf(Vector3DKeyFrame keyFrame) { return default(int); } public void Insert(int index, Vector3DKeyFrame keyFrame) { } public void Remove(Vector3DKeyFrame keyFrame) { } public void RemoveAt(int index) { } void System.Collections.ICollection.CopyTo(Array array, int index) { } int System.Collections.IList.Add(Object keyFrame) { return default(int); } bool System.Collections.IList.Contains(Object keyFrame) { return default(bool); } int System.Collections.IList.IndexOf(Object keyFrame) { return default(int); } void System.Collections.IList.Insert(int index, Object keyFrame) { } void System.Collections.IList.Remove(Object keyFrame) { } public Vector3DKeyFrameCollection() { } #endregion #region Properties and indexers public int Count { get { return default(int); } } public static System.Windows.Media.Animation.Vector3DKeyFrameCollection Empty { get { return default(System.Windows.Media.Animation.Vector3DKeyFrameCollection); } } public bool IsFixedSize { get { return default(bool); } } public bool IsReadOnly { get { return default(bool); } } public bool IsSynchronized { get { return default(bool); } } public Vector3DKeyFrame this [int index] { get { return default(Vector3DKeyFrame); } set { } } public Object SyncRoot { get { return default(Object); } } Object System.Collections.IList.this [int index] { get { return default(Object); } set { } } #endregion } }
//#define CONNECTION //#define STARVE //#define FLIT //#define INEJ //#define INTERCONNECT //#define LOOPS using System; using System.Collections.Generic; using System.Collections; using System.Text; using System.IO; namespace ICSimulator { public abstract class RingRouter : Router { public RingCoord ringCoord; public int ringID { get { return ringCoord.ID; } } public bool clockwise; public RingRouter(Coord myCoord) : base (myCoord) { throw new Exception("You really can't make a ring router with a normal coordinate..., defeats the purpose of ringCoord"); } public RingRouter(RingCoord rc, bool isNode) : base (rc, isNode) { ringCoord = rc; routerName = "RingRouter"; } /******************************************************** * ROUTING HELPERS ********************************************************/ protected override PreferredDirection determineDirection(Flit f) { return determineDirection(f, new RingCoord(0, 0, 0)); } protected PreferredDirection determineDirection(Flit f, RingCoord current) { PreferredDirection pd; pd.xDir = Simulator.DIR_NONE; pd.yDir = Simulator.DIR_NONE; pd.zDir = Simulator.DIR_NONE; if (f.state == Flit.State.Placeholder) return pd; //if (f.packet.ID == 238) // Console.WriteLine("packet 238 at ID ({0},{1}), wants ({2},{3})", current.x, current.y, f.packet.ringdest.x, f.packet.ringdest.y); return determineDirection(f.ringdest); } //TODO: fix for ring coordinates, if I didn't already protected PreferredDirection determineDirection(RingCoord c) { PreferredDirection pd; pd.xDir = Simulator.DIR_NONE; pd.yDir = Simulator.DIR_NONE; pd.zDir = Simulator.DIR_NONE; pd.zDir = ((c.z - ringCoord.z) >= 0) ? 1 : 0; if(Config.torus) { int x_sdistance = Math.Abs(c.x - coord.x); int x_wdistance = Config.network_nrX - Math.Abs(c.x - coord.x); int y_sdistance = Math.Abs(c.y - coord.y); int y_wdistance = Config.network_nrY - Math.Abs(c.y - coord.y); bool x_dright, y_ddown; x_dright = coord.x < c.x; y_ddown = c.y < coord.y; if(c.x == coord.x) pd.xDir = Simulator.DIR_NONE; else if(x_sdistance < x_wdistance) pd.xDir = (x_dright) ? Simulator.DIR_RIGHT : Simulator.DIR_LEFT; else pd.xDir = (x_dright) ? Simulator.DIR_LEFT : Simulator.DIR_RIGHT; if(c.y == coord.y) pd.yDir = Simulator.DIR_NONE; else if(y_sdistance < y_wdistance) pd.yDir = (y_ddown) ? Simulator.DIR_DOWN : Simulator.DIR_UP; else pd.yDir = (y_ddown) ? Simulator.DIR_UP : Simulator.DIR_DOWN; } else { if (c.x > coord.x) pd.xDir = Simulator.DIR_RIGHT; else if (c.x < coord.x) pd.xDir = Simulator.DIR_LEFT; else pd.xDir = Simulator.DIR_NONE; if (c.y > coord.y) pd.yDir = Simulator.DIR_UP; else if (c.y < coord.y) pd.yDir = Simulator.DIR_DOWN; else pd.yDir = Simulator.DIR_NONE; } if (Config.dor_only && pd.xDir != Simulator.DIR_NONE) pd.yDir = Simulator.DIR_NONE; return pd; } protected override int dimension_order_route(Flit f) { if (f.packet.ringdest.x < ringCoord.x) return Simulator.DIR_LEFT; else if (f.packet.ringdest.x > ringCoord.x) return Simulator.DIR_RIGHT; else if (f.packet.ringdest.y < ringCoord.y) return Simulator.DIR_DOWN; else if (f.packet.ringdest.y > ringCoord.y) return Simulator.DIR_UP; else if (f.packet.ringdest.z > ringCoord.z) return Simulator.DIR_CW; else if (f.packet.ringdest.z < ringCoord.z) return Simulator.DIR_CCW; else //if the destination's coordinates are equal to the router's coordinates return Simulator.DIR_CW; } /******************************************************** * STATISTICS ********************************************************/ protected override void statsInput() { int goldenCount = 0; incomingFlits = 0; for (int i = 0; i < 4; i++) { if (linkIn[i] != null && linkIn[i].Out != null) { linkIn[i].Out.Deflected = false; if (Simulator.network.golden.isGolden(linkIn[i].Out)) goldenCount++; incomingFlits++; } } Simulator.stats.golden_pernode.Add(goldenCount); Simulator.stats.golden_bycount[goldenCount].Add(); Simulator.stats.traversals_pernode[incomingFlits].Add(); //Simulator.stats.traversals_pernode_bysrc[ID,incomingFlits].Add(); } protected override void statsOutput() { int deflected = 0; int unproductive = 0; int traversals = 0; for (int i = 0; i < 4; i++) { if (linkOut[i] != null && linkOut[i].In != null) { if (linkOut[i].In.Deflected) { // deflected! (may still be productive, depending on deflection definition/DOR used) deflected++; linkOut[i].In.nrOfDeflections++; Simulator.stats.deflect_flit_byloc[ID].Add(); if (linkOut[i].In.packet != null) { Simulator.stats.total_deflected.Add(); // Golden counters of deflections if(Simulator.network.golden.isGolden(linkOut[i].In)) { Simulator.stats.golden_deflected.Add(); Simulator.stats.golden_deflect_flit_byloc[ID].Add(); Simulator.stats.golden_deflect_flit_bysrc[linkOut[i].In.packet.src.ID].Add(); Simulator.stats.golden_deflect_flit_byreq[linkOut[i].In.packet.requesterID].Add(); } Simulator.stats.deflect_flit_bysrc[linkOut[i].In.packet.src.ID].Add(); Simulator.stats.deflect_flit_byreq[linkOut[i].In.packet.requesterID].Add(); } } traversals++; //linkOut[i].In.deflectTest(); } } Simulator.stats.deflect_flit.Add(deflected); Simulator.stats.deflect_flit_byinc[incomingFlits].Add(deflected); Simulator.stats.unprod_flit.Add(unproductive); Simulator.stats.unprod_flit_byinc[incomingFlits].Add(unproductive); Simulator.stats.flit_traversals.Add(traversals); if(m_n == null) return; int qlen = m_n.RequestQueueLen; qlen_count -= qlen_win[qlen_ptr]; qlen_count += qlen; // Compute the average queue length qlen_win[qlen_ptr] = qlen; if(++qlen_ptr >= AVG_QLEN_WIN) qlen_ptr=0; avg_qlen = (float)qlen_count / (float)AVG_QLEN_WIN; } protected override void statsInjectFlit(Flit f) { //if (f.packet.src.ID == 3) Console.WriteLine("inject flit: packet {0}, seq {1}", // f.packet.ID, f.flitNr); Simulator.stats.inject_flit.Add(); if (f.isHeadFlit) Simulator.stats.inject_flit_head.Add(); if (f.packet != null) { Simulator.stats.inject_flit_bysrc[f.packet.src.ID].Add(); //Simulator.stats.inject_flit_srcdest[f.packet.src.ID, f.packet.ringdest.ID].Add(); } if (f.packet != null && f.packet.injectionTime == ulong.MaxValue) f.packet.injectionTime = Simulator.CurrentRound; f.injectionTime = Simulator.CurrentRound; ulong hoq = Simulator.CurrentRound - m_lastInj; m_lastInj = Simulator.CurrentRound; Simulator.stats.hoq_latency.Add(hoq); Simulator.stats.hoq_latency_bysrc[coord.ID].Add(hoq); } protected override void statsEjectFlit(Flit f) { //if (f.packet.src.ID == 3) Console.WriteLine("eject flit: packet {0}, seq {1}", // f.packet.ID, f.flitNr) // per-flit latency stats ulong net_latency = Simulator.CurrentRound - f.injectionTime; ulong total_latency = Simulator.CurrentRound - f.packet.creationTime; ulong inj_latency = total_latency - net_latency; Simulator.stats.flit_inj_latency.Add(inj_latency); Simulator.stats.flit_net_latency.Add(net_latency); Simulator.stats.flit_total_latency.Add(inj_latency); Simulator.stats.eject_flit.Add(); Simulator.stats.eject_flit_bydest[f.packet.dest.ID].Add(); int minpath = Math.Abs(f.packet.ringdest.x - f.packet.ringsrc.x) + Math.Abs(f.packet.ringdest.y - f.packet.ringsrc.y); Simulator.stats.minpath.Add(minpath); Simulator.stats.minpath_bysrc[f.packet.src.ID].Add(minpath); //f.dumpDeflections(); Simulator.stats.deflect_perdist[f.distance].Add(f.nrOfDeflections); if(f.nrOfDeflections!=0) Simulator.stats.deflect_perflit_byreq[f.packet.requesterID].Add(f.nrOfDeflections); } protected override void statsEjectPacket(Packet p) { ulong net_latency = Simulator.CurrentRound - p.injectionTime; ulong total_latency = Simulator.CurrentRound - p.creationTime; Simulator.stats.net_latency.Add(net_latency); Simulator.stats.total_latency.Add(total_latency); Simulator.stats.net_latency_bysrc[p.src.ID].Add(net_latency); Simulator.stats.net_latency_bydest[p.dest.ID].Add(net_latency); //Simulator.stats.net_latency_srcdest[p.src.ID, p.ringdest.ID].Add(net_latency); Simulator.stats.total_latency_bysrc[p.src.ID].Add(total_latency); Simulator.stats.total_latency_bydest[p.dest.ID].Add(total_latency); //Simulator.stats.total_latency_srcdest[p.src.ID, p.ringdest.ID].Add(total_latency); } public override string ToString() { return routerName + " (" + ringCoord.x + "," + ringCoord.y + "," + ringCoord.z + ")"; } public override void statsStarve(Flit f) { Simulator.stats.starve_flit.Add(); Simulator.stats.starve_flit_bysrc[f.packet.src.ID].Add(); if (last_starve == Simulator.CurrentRound - 1) { starve_interval++; } else { Simulator.stats.starve_interval_bysrc[f.packet.src.ID].Add(starve_interval); starve_interval = 0; } last_starve = Simulator.CurrentRound; } public override int linkUtil() { int count = 0; for (int i = 0; i < 6; i++) if (linkIn[i] != null && linkIn[i].Out != null) count++; return count; } } public class RingRouter_Simple : RingRouter { // injectSlot is from Node; injectSlot2 is higher-priority from // network-level re-injection (e.g., placeholder schemes) protected Flit m_injectSlot, m_injectSlot2; protected int injectedCount; protected int blockCount; public RingRouter_Simple(RingCoord rc, bool isNode) : base(rc, isNode) { routerName = "Simple Ring Router"; m_injectSlot = null; m_injectSlot2 = null; injectedCount = 0; blockCount = 0; } // accept one ejected flit into rxbuf void acceptFlit(Flit f) { statsEjectFlit(f); if (f.packet.nrOfArrivedFlits + 1 == f.packet.nrOfFlits) statsEjectPacket(f.packet); m_n.receiveFlit(f); } Flit ejectLocalNew() { Flit ret = null; int dir = (clockwise) ? Simulator.DIR_CCW : Simulator.DIR_CW; #if CONNECTION if (clockwise) { if(linkIn[Simulator.DIR_CCW] == null || linkOut[Simulator.DIR_CW] == null) throw new Exception(String.Format("{0} has no connection {1} {2} |", this, linkIn[Simulator.DIR_CCW], linkOut[Simulator.DIR_CW])); } else { if(linkOut[Simulator.DIR_CCW] == null || linkIn[Simulator.DIR_CW] == null) throw new Exception(String.Format("{0} has no connection {1} {2} |", this, linkIn[Simulator.DIR_CW], linkOut[Simulator.DIR_CCW])); } #endif // It's a placeholder so don't eject it if (linkIn[dir].Out == null || linkIn[dir].Out.initPrio == -1) { return null; } if(linkIn[dir].Out != null && linkIn[dir].Out.dest.ID == ID) { ret = linkIn[dir].Out; linkIn[dir].Out = null; } #if INEJ if (ret != null) Console.WriteLine("> ejecting flit {0}.{1} at node {2} cyc {3}", ret.packet.ID, ret.flitNr, ringCoord, Simulator.CurrentRound); #endif return ret; } /* * Injects flits */ void inject(out bool injected) { injected = false; int tempDir = (clockwise) ? Simulator.DIR_CCW : Simulator.DIR_CW; if (input[6] != null) { if (input[tempDir] == null) { injected = true; input[tempDir] = input[6]; input[6] = null; } } #if INEJ if (injected) Console.WriteLine("< injecting flit {0}.{1} at node {2} cyc {3}", input[tempDir].packet.ID, input[tempDir].flitNr, ringCoord, Simulator.CurrentRound); #endif } void route() { Flit[] temp = new Flit[7]; for(int i = 4; i < 6; i++) temp[i] = input[i]; int dir = (clockwise) ? Simulator.DIR_CW : Simulator.DIR_CCW; int oppDir = (clockwise) ? Simulator.DIR_CCW : Simulator.DIR_CW; input[dir] = temp[oppDir]; input[oppDir]= null; } Flit[] input = new Flit[7]; // keep this as a member var so we don't // have to allocate on every step (why can't // we have arrays on the stack like in C?) protected override void _doStep() { /* Ejection selection and ejection */ Flit eject = null; eject = ejectLocalNew(); /* Setup the inputs */ for (int dir = 4; dir < 6; dir++) { if (linkIn[dir] != null && linkIn[dir].Out != null) { input[dir] = linkIn[dir].Out; input[dir].inDir = dir; } else input[dir] = null; } for (int dir = 4; dir < 6; dir++) { if (input[dir] != null && ringCoord.Equals(input[dir].packet.ringsrc)) { input[dir].priority += 1; #if LOOPS Console.WriteLine("\t\t{0}.{1} at node {2} cyc {3} dest {4}\tPriority: {5}", input[dir].packet.ID, input[dir].flitNr, ringCoord, Simulator.CurrentRound, input[dir].ringdest, input[dir].priority); #endif } } /* Injection */ Flit inj = null; bool injected = false; /* Pick slot to inject */ if (m_injectSlot2 != null) { inj = m_injectSlot2; m_injectSlot2 = null; } else if (m_injectSlot != null) { inj = m_injectSlot; m_injectSlot = null; } /* Port 4 becomes the injected line */ input[6] = inj; /* If there is data, set the injection direction */ if (inj != null) inj.inDir = -1; /* Inject and route flits in correct directions */ if (injectedCount > Config.injectHoldThreshold) { blockCount = Config.blockInjectCount; injectedCount = 0; } if (blockCount < 1) inject(out injected); else blockCount--; if (injected) injectedCount++; else if (Config.injectedCountReset) injectedCount = 0; #if STARVE if(!injected && input[6] != null) Console.WriteLine("Starved flit {0}.{1} at node {2} cyc {3}", input[6].packet.ID, input[6].flitNr, ringCoord, Simulator.CurrentRound); #endif if (injected && input[6] != null) throw new Exception("Not removing injected flit from slot"); route(); /* If something wasn't injected, move the flit into the injection slots * If it was injected, take stats */ if (!injected) { if (m_injectSlot == null) m_injectSlot = inj; else m_injectSlot2 = inj; } else statsInjectFlit(inj); /* Put ejected flit in reassembly buffer */ if (eject != null) acceptFlit(eject); /* Assign outputs */ for (int dir = 4; dir < 6; dir++) { if (input[dir] != null) { #if FLIT Console.WriteLine("flit {0}.{1} at node {2} cyc {3}", input[dir].packet.ID, input[dir].flitNr, ringCoord, Simulator.CurrentRound); #endif if (linkOut[dir] == null) throw new Exception(String.Format("router {0} does not have link in dir {1}", coord, dir)); linkOut[dir].In = input[dir]; } #if FLIT //else if(dir == Simulator.DIR_LEFT || dir == Simulator.DIR_RIGHT) // Console.WriteLine("no flit at node {0} cyc {1}", coord, Simulator.CurrentRound); #endif } } public override bool canInjectFlit(Flit f) { return m_injectSlot == null; } public override void InjectFlit(Flit f) { if (m_injectSlot != null) throw new Exception("Trying to inject twice in one cycle"); m_injectSlot = f; } public override void visitFlits(Flit.Visitor fv) { if (m_injectSlot != null) fv(m_injectSlot); if (m_injectSlot2 != null) fv(m_injectSlot2); } } public class Connector : RingRouter { public int connectionDirection; public int injectPlaceholder; //public Flit removedFlit; public ResubBuffer rBuf; public Connector(RingCoord rc, bool isNode) : base(rc, isNode) { routerName = "Ring Connector"; ringCoord = rc; connectionDirection = Simulator.DIR_NONE; injectPlaceholder = 0; rBuf = new ResubBuffer(3); } // accept one ejected flit into rxbuf void acceptFlit(Flit f) { statsEjectFlit(f); if (f.packet.nrOfArrivedFlits + 1 == f.packet.nrOfFlits) statsEjectPacket(f.packet); m_n.receiveFlit(f); } bool isRingProductive(Flit f, int dir) { int cols = (Config.network_nrX / Config.ringWidth); int rows = (Config.network_nrY / Config.ringHeight); if(f.initPrio == -1) return true; switch(dir) // TODO: Fix for torus { case Simulator.DIR_UP: if (Config.torus) { int direct = (ringCoord.y - f.ringdest.y); int indirect; if (direct < 0) { indirect = (rows - f.ringdest.y + ringCoord.y); return (Math.Abs(indirect) < Math.Abs(direct)); } else { indirect = (rows - ringCoord.y + f.ringdest.y); return (Math.Abs(indirect) > Math.Abs(direct)); } } else return (ringCoord.y > f.ringdest.y); case Simulator.DIR_DOWN: if (Config.torus) { int direct = (f.ringdest.y - ringCoord.y); int indirect; if (direct < 0) { indirect = (rows - ringCoord.y + f.ringdest.y); return (Math.Abs(indirect) < Math.Abs(direct)); } else { indirect = (rows - f.ringdest.y + ringCoord.y); return (Math.Abs(indirect) > Math.Abs(direct)); } } else return (ringCoord.y < f.ringdest.y); case Simulator.DIR_LEFT: if (Config.torus) { int direct = (f.ringdest.x - ringCoord.x); int indirect; if (direct < 0) { indirect = (cols - ringCoord.x + f.ringdest.x); return (Math.Abs(indirect) < Math.Abs(direct)); } else { indirect = (cols - f.ringdest.x + ringCoord.x); return (Math.Abs(indirect) > Math.Abs(direct)); } } else return (ringCoord.x > f.ringdest.x); case Simulator.DIR_RIGHT: if (Config.torus) { int direct = (ringCoord.x - f.ringdest.x); int indirect; if (direct < 0) { indirect = (cols - f.ringdest.x + ringCoord.x); return (Math.Abs(indirect) > Math.Abs(direct)); } else { indirect = (cols - ringCoord.x + f.ringdest.x); return (Math.Abs(indirect) > Math.Abs(direct)); } } else return (ringCoord.x < f.ringdest.x); case Simulator.DIR_CW: return (ringCoord.y == f.ringdest.y && ringCoord.x == f.ringdest.x && ringCoord.z < f.ringdest.z); case Simulator.DIR_CCW: return (ringCoord.y == f.ringdest.y && ringCoord.x == f.ringdest.x && ringCoord.z > f.ringdest.z); case Simulator.DIR_NONE: return isDestRing(f); default: throw new Exception(" NOT A DIRECTION! "); } } bool isDestRing(Flit f) { if(f.initPrio == -1) return true; return (f.tempX == ringCoord.x && f.tempY == ringCoord.y); } void getNeighborXY(out int xcoord, out int ycoord) { switch (connectionDirection) { case Simulator.DIR_UP: ycoord = ringCoord.y - 1; xcoord = ringCoord.x; break; case Simulator.DIR_DOWN: ycoord = ringCoord.y + 1; xcoord = ringCoord.x; break; case Simulator.DIR_LEFT: ycoord = ringCoord.y; xcoord = ringCoord.x - 1; break; case Simulator.DIR_RIGHT: ycoord = ringCoord.y; xcoord = ringCoord.x + 1; break; default: throw new Exception(" NOT A VALID DIRECTION "); } } void route() { Flit[] temp = new Flit[6]; for (int i = 0; i < 6; i++) temp[i] = input[i]; int dir; if(clockwise) dir = Simulator.DIR_CCW; else dir = Simulator.DIR_CW; if(injectPlaceholder > 0) { injectPlaceholder--; if(temp[connectionDirection] != null) rBuf.addFlit(temp[connectionDirection]); temp[connectionDirection] = null; int tempX = 0; int tempY = 0; switch (injectPlaceholder % 4) { case 0: tempX = 4; tempY = 3; break; case 1: tempX = 0; tempY = 0; break; case 2: tempX = 1; tempY = 2; break; case 3: tempX = 2; tempY = 4; break; } Coord tempCoord = new Coord(tempX, tempY); temp[connectionDirection] = new Flit(new Packet(null, 1337, 1337, tempCoord, tempCoord), 1337); temp[connectionDirection].initPrio = -1; #if INEJ Console.WriteLine("!!!!!!!!!! INJECTING PLACEHOLDER {0}.{1} at node {2} cyc {3} !!!!!!!!!!!", temp[connectionDirection].packet.ID, temp[connectionDirection].flitNr, ringCoord, Simulator.CurrentRound); #endif /*injectPlaceholder--; temp[dir] = new Flit(new Packet(null, 1337, 1337, new Coord(4,4), new Coord(4,4)), 1337); temp[dir].initPrio = -1; */ } if (connectionDirection == dir) throw new Exception("Connection direction should not be clockwise or counter clockwise"); // If there is something coming in, try to pull it in. if (temp[connectionDirection] != null) { if (isDestRing(temp[connectionDirection])) { if(temp[dir] == null) { #if INTERCONNECT Console.WriteLine("|Moving Into Ring| \t \tflit {0}.{1} at node {2} cyc {3} \t | dest: {4}", temp[connectionDirection].packet.ID, temp[connectionDirection].flitNr, ringCoord, Simulator.CurrentRound, temp[connectionDirection].packet.ringdest); #endif temp[dir] = temp[connectionDirection]; temp[connectionDirection] = null; } else { if (isRingProductive(temp[dir], connectionDirection)) { Flit tempFlit; #if INTERCONNECT Console.WriteLine("|Swapping outside-inside|\tflit {0}.{1} && flit {2}.{3} at node {4} cyc {5} \t \n| dest1: {6} dest2: {7}", temp[connectionDirection].packet.ID, temp[connectionDirection].flitNr, temp[dir].packet.ID, temp[dir].flitNr, ringCoord, Simulator.CurrentRound, temp[connectionDirection].packet.ringdest, temp[dir].packet.ringdest); #endif tempFlit = temp[dir]; temp[dir] = temp[connectionDirection]; temp[connectionDirection] = tempFlit; getNeighborXY(out temp[connectionDirection].tempX, out temp[connectionDirection].tempY); } #if INTERCONNECT else { Console.WriteLine("!Deflected outside ring!\tflit {0}.{1} at node{2} cyc {3} \t | dest: {4}", temp[connectionDirection].packet.ID, temp[connectionDirection].flitNr, ringCoord, Simulator.CurrentRound, temp[connectionDirection].packet.ringdest); Console.WriteLine("!!!! DEFLECTED another outside ring!!!\t flit{0}.{1} at node{2} cyc {3} \t | dest: {4}\t Flit {5}.{6} dest:{7}", temp[dir].packet.ID, temp[dir].flitNr, ringCoord, Simulator.CurrentRound, temp[dir].packet.ringdest, temp[connectionDirection].packet.ID, temp[connectionDirection].flitNr, temp[connectionDirection].ringdest); } #endif } } } // Otherwise, try to push something into the connection. else { if(temp[dir] != null && isRingProductive(temp[dir], connectionDirection)) { #if INTERCONNECT Console.WriteLine("|Moving Out of Ring|\t \tflit {0}.{1} at node {2} cyc {3} \t | dest: {4}", temp[dir].packet.ID, temp[dir].flitNr, ringCoord, Simulator.CurrentRound, temp[dir].packet.ringdest); #endif temp[connectionDirection] = temp[dir]; temp[dir] = null; getNeighborXY(out temp[connectionDirection].tempX, out temp[connectionDirection].tempY); } #if INTERCONNECT else if (temp[dir] != null) Console.WriteLine("!Deflected inside ring!\tflit {0}.{1} at node{2} cyc {3}\t | dest: {4}", temp[dir].packet.ID, temp[dir].flitNr, ringCoord, Simulator.CurrentRound, temp[dir].packet.ringdest); #endif } input[connectionDirection] = temp[connectionDirection]; if (clockwise){ input[Simulator.DIR_CW] = temp[Simulator.DIR_CCW]; input[Simulator.DIR_CCW] = null; } else { input[Simulator.DIR_CCW] = temp[Simulator.DIR_CW]; input[Simulator.DIR_CW] = null; } } Flit[] input = new Flit[6]; // keep this as a member var so we don't // have to allocate on every step (why can't // we have arrays on the stack like in C?) // --- because we have a garbage collector instead and want to dynamically allocate everything protected override void _doStep() { int tempCount = 0; /* Setup the inputs */ for (int dir = 0; dir < 6; dir++) { if (linkIn[dir] != null && linkIn[dir].Out != null) { tempCount++; input[dir] = linkIn[dir].Out; input[dir].inDir = dir; } else input[dir] = null; } //To avoid the create / remove counter exception if (injectPlaceholder > 0) tempCount++; /* Only used when forcing a placeholder into the system */ int tempDir = (clockwise) ? Simulator.DIR_CCW : Simulator.DIR_CW; if (input[tempDir] == null && !rBuf.isEmpty()) { input[tempDir] = rBuf.removeFlit(); } else if (input[connectionDirection] == null && !rBuf.isEmpty()) { input[connectionDirection] = rBuf.removeFlit(); } route(); int endCount = 0; /* Assign outputs */ for (int dir = 0; dir < 6; dir++) { if (input[dir] != null) { #if FLIT Console.WriteLine("flit {0}.{1} at node {2} cyc {3} \t | dir:{4} | dest: {5} connectionDir {6} productive: {7} isDest {8}", input[dir].packet.ID, input[dir].flitNr, ringCoord, Simulator.CurrentRound, dir, input[dir].packet.ringdest, connectionDirection, isRingProductive(input[dir], connectionDirection),isDestRing(input[dir])); Console.WriteLine("\tflit {0}.{1} currentRing = {2} destRing = {3},{4}", input[dir].packet.ID, input[dir].flitNr, ringCoord, input[dir].tempX, input[dir].tempY); #endif endCount++; if (linkOut[dir] == null) throw new Exception(String.Format("connector {0} does not have link in dir {1}", ringCoord, dir)); linkOut[dir].In = input[dir]; } } if (endCount != tempCount) throw new Exception(String.Format("connector {0} created or destroyed flits. Before: {1} | After: {2}", ringCoord, tempCount, endCount)); } public override bool canInjectFlit(Flit f) { return false; } public override void InjectFlit(Flit f) { return; } public override void visitFlits(Flit.Visitor fv) { return; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.IO; public class Options : MonoBehaviour { private const string optionsfile = "settings.txt"; private const float ORIGINAL_WIDTH = 1024; private const float ORIGINAL_HEIGHT = 768; private readonly int[] AA_LEVELS = { 0, 2, 4, 8 }; public static bool Networking { get { return networking; } } public static float Sensitivity { get { return sensitivity; } } public static float MasterVolume { get { return mastervolume; } } public static float BGMVolume { get { return bgmvolume; } } public static float SFXVolume { get { return sfxvolume; } } public static bool enableGUI = true; public GUISkin guiSkin; public GUISkin pcSkin; public static bool firstrun = true; private GUISkin skin; private static Resolution current; // Graphics private static int currentResolution = 0; private static int fullscreen = 0; private static int quality = 2; // Advanced private static int aalevel = 2; private static int aniso = 1; private static int vsync = 1; private static int textureres = 2; // Controls private static float sensitivity = 1.0f; // Sound private static float mastervolume = 1.0f; private static float bgmvolume = 1.0f; private static float sfxvolume = 1.0f; // Misc private static bool advanced = false; private static bool networking = true; // Loading private static bool loaded = false; #if UNITY_STANDALONE_WIN [DllImport("user32.dll", EntryPoint="ClipCursor")] static extern bool ClipCursor(ref RECT lpRect); [DllImport("user32.dll", EntryPoint="ClipCursor")] static extern bool ClipCursorNullable(Object obj); public struct RECT { public int Left; public int Top; public int Right; public int Bottom; } #endif public void Awake() { #if UNITY_ANDROID || UNITY_IPHONE skin = (GUISkin)Instantiate(guiSkin); #else skin = (GUISkin)Instantiate(pcSkin); #endif // Load settings Load(); } public void Start() { UpdateSettings(); } public void OnGUI() { float scale = Screen.height / ORIGINAL_HEIGHT; // Center scaled gui float offset = (Screen.width / 2.0f) / scale; Matrix4x4 oldMatrix = GUI.matrix; GUI.matrix = Matrix4x4.identity; GUI.matrix *= Matrix4x4.Scale(new Vector3(scale, scale, 1)); GUI.matrix *= Matrix4x4.TRS(new Vector3(offset, 0, 0), Quaternion.identity, Vector3.one); if (!enableGUI || LevelSelectGUI.menuState != LevelSelectGUI.MenuState.OPTIONS) return; float labelWidth = ORIGINAL_WIDTH * 0.3f; // Save and switch skin GUISkin old = GUI.skin; GUI.skin = skin; #if UNITY_IPHONE || UNITY_ANDROID // Phones GUILayout.BeginArea(new Rect(ORIGINAL_WIDTH * -0.45f, ORIGINAL_HEIGHT * 0.35f, ORIGINAL_WIDTH * 0.8f, ORIGINAL_HEIGHT * 0.6f)); // Networking /* GUILayout.BeginHorizontal(); GUILayout.Label("Networking", GUILayout.Width(labelWidth)); if (GUILayout.SelectionGrid((networking ? 1 : 0), new string[] { "Off", "On" }, 2) == 0) networking = false; else networking = true; GUILayout.EndHorizontal(); */ // Sensitivity slider GUILayout.BeginHorizontal(); //GUI.skin.label.alignment = TextAnchor.UpperLeft; GUILayout.Label("Turning sensitivity", GUILayout.Width(labelWidth)); //GUI.skin.label.alignment = TextAnchor.MiddleCenter; sensitivity = GUILayout.HorizontalSlider(sensitivity, 0.3f, 1.7f); GUILayout.EndHorizontal(); // Audio //GUILayout.Label("Audio"); // Master volume GUILayout.BeginHorizontal(); GUILayout.Label("Master Volume", GUILayout.Width(labelWidth)); mastervolume = GUILayout.HorizontalSlider(mastervolume, 0.0f, 1.0f); GUILayout.EndHorizontal(); // Music volume GUILayout.BeginHorizontal(); GUILayout.Label("BGM Volume", GUILayout.Width(labelWidth)); bgmvolume = GUILayout.HorizontalSlider(bgmvolume, 0.0f, 1.0f); GUILayout.EndHorizontal(); // Sound effect volume GUILayout.BeginHorizontal(); GUILayout.Label("SFX Volume", GUILayout.Width(labelWidth)); sfxvolume = GUILayout.HorizontalSlider(sfxvolume, 0.0f, 1.0f); GUILayout.EndHorizontal(); /*if (GUILayout.Button("WHATEVER YOU DO DONT DO IT")) { current = Screen.resolutions[currentResolution]; Screen.SetResolution(current.width, current.height, false); UpdateSettings(); Save(); }*/ GUILayout.EndArea(); #else #if UNITY_IPHONE || UNITY_ANDROID // Phones GUILayout.BeginArea(new Rect(ORIGINAL_WIDTH * -0.3f, ORIGINAL_HEIGHT * 0.4f, ORIGINAL_WIDTH * 0.6f, ORIGINAL_HEIGHT * 0.6f)); #else current = Screen.resolutions[currentResolution]; // PC GUILayout.BeginArea(new Rect(ORIGINAL_WIDTH * -0.475f, ORIGINAL_HEIGHT * 0.35f, ORIGINAL_WIDTH * 0.425f, ORIGINAL_HEIGHT * 0.65f)); // Resolution GUILayout.BeginHorizontal(); GUILayout.Label("Resolution", GUILayout.Width(180)); // Previous button if (GUILayout.Button("<")) currentResolution = Mathf.Clamp(currentResolution-1, 0, Screen.resolutions.Length-1); // Current selection Font oldfont = GUI.skin.label.font; TextAnchor oldalign = GUI.skin.label.alignment; GUI.skin.label.alignment = TextAnchor.MiddleCenter; GUI.skin.label.font = GUI.skin.button.font; GUILayout.Label(current.width + ", " + current.height); GUI.skin.label.alignment = oldalign; GUI.skin.label.font = oldfont; // Next button if (GUILayout.Button(">")) currentResolution = Mathf.Clamp(currentResolution+1, 0, Screen.resolutions.Length-1); GUILayout.EndHorizontal(); // Whether or not to be fullscreen GUILayout.BeginHorizontal(); GUILayout.Label("Display", GUILayout.Width(180)); fullscreen = GUILayout.SelectionGrid(fullscreen, new string[] { "Windowed", "Fullscreen" }, 2); GUILayout.EndHorizontal(); // Quality GUILayout.BeginHorizontal(); GUILayout.Label("Quality", GUILayout.Width(180)); if (GUILayout.Button("Low")) SetQuality(0); else if (GUILayout.Button("Medium")) SetQuality(1); else if (GUILayout.Button("High")) SetQuality(2); else if (GUILayout.Button("Ultra")) SetQuality(3); GUILayout.EndHorizontal(); // Seperator GUILayout.Label(""); #endif // Networking /* GUILayout.BeginHorizontal(); GUILayout.Label("Networking", GUILayout.Width(260)); if (GUILayout.SelectionGrid((networking ? 1 : 0), new string[] { "Off", "On" }, 2) == 0) networking = false; else networking = true; GUILayout.EndHorizontal(); */ #if UNITY_STANDALONE_WIN || UNITY_STANDALONE_MAC || UNITY_STANDALONE_LINUX || UNITY_WEBPLAYER // Seperator GUILayout.Label(""); #endif // Controls //GUILayout.Label("Controls"); // Sensitivity slider GUILayout.BeginHorizontal(); //GUI.skin.label.alignment = TextAnchor.UpperLeft; GUILayout.Label("Turning sensitivity", GUILayout.Width(260)); //GUI.skin.label.alignment = TextAnchor.MiddleCenter; sensitivity = GUILayout.HorizontalSlider(sensitivity, 0.3f, 1.7f); GUILayout.EndHorizontal(); #if UNITY_STANDALONE_WIN || UNITY_STANDALONE_MAC || UNITY_STANDALONE_LINUX || UNITY_WEBPLAYER // Seperator GUILayout.Label(""); #endif // Audio //GUILayout.Label("Audio"); // Master volume GUILayout.BeginHorizontal(); GUILayout.Label("Master Volume", GUILayout.Width(260)); mastervolume = GUILayout.HorizontalSlider(mastervolume, 0.0f, 1.0f); GUILayout.EndHorizontal(); // Music volume GUILayout.BeginHorizontal(); GUILayout.Label("BGM Volume", GUILayout.Width(260)); bgmvolume = GUILayout.HorizontalSlider(bgmvolume, 0.0f, 1.0f); GUILayout.EndHorizontal(); // Sound effect volume GUILayout.BeginHorizontal(); GUILayout.Label("SFX Volume", GUILayout.Width(260)); sfxvolume = GUILayout.HorizontalSlider(sfxvolume, 0.0f, 1.0f); GUILayout.EndHorizontal(); /*if (GUILayout.Button("WHATEVER YOU DO DONT DO IT")) { current = Screen.resolutions[currentResolution]; Screen.SetResolution(current.width, current.height, false); UpdateSettings(); Save(); }*/ GUILayout.EndArea(); // Only show advanced on PC #if UNITY_STANDALONE_WIN || UNITY_STANDALONE_MAC || UNITY_STANDALONE_LINUX || UNITY_WEBPLAYER // Advanced area GUILayout.BeginArea(new Rect(0.025f * ORIGINAL_WIDTH, 0.35f * ORIGINAL_HEIGHT, 0.425f * ORIGINAL_WIDTH, 0.65f * ORIGINAL_HEIGHT)); GUILayout.BeginHorizontal(); GUILayout.Label("Advanced", GUILayout.Width(160)); if (GUILayout.SelectionGrid((advanced ? 1 : 0), new string[] { "Hide", "Show" }, 2) == 0) advanced = false; else advanced = true; GUILayout.EndHorizontal(); if (advanced) { // Seperator GUILayout.Label(""); // Anti-aliasing level GUILayout.BeginHorizontal(); GUILayout.Label("Anti-aliasing", GUILayout.Width(160)); // Previous button if (GUILayout.Button("<")) aalevel = Mathf.Clamp(aalevel-1, 0, AA_LEVELS.Length-1); // Current selection oldfont = GUI.skin.label.font; oldalign = GUI.skin.label.alignment; GUI.skin.label.alignment = TextAnchor.MiddleCenter; GUI.skin.label.font = GUI.skin.button.font; GUILayout.Label(AA_LEVELS[aalevel] + "x"); GUI.skin.label.alignment = oldalign; GUI.skin.label.font = oldfont; // Next button if (GUILayout.Button(">")) aalevel = Mathf.Clamp(aalevel+1, 0, AA_LEVELS.Length-1); GUILayout.EndHorizontal(); // Anisotropic filtering GUILayout.BeginHorizontal(); GUILayout.Label("Filtering", GUILayout.Width(160)); aniso = GUILayout.SelectionGrid(aniso, new string[] { "Off", "On" }, 2); GUILayout.EndHorizontal(); // Vsync GUILayout.BeginHorizontal(); GUILayout.Label("Vertical Sync", GUILayout.Width(160)); vsync = GUILayout.SelectionGrid(vsync, new string[] { "Off", "On" }, 2); GUILayout.EndHorizontal(); // Texture resolution GUILayout.BeginHorizontal(); GUILayout.Label("Texture Res", GUILayout.Width(160)); textureres = GUILayout.SelectionGrid(textureres, new string[] { "Low", "Medium", "High" }, 3); GUILayout.EndHorizontal(); } // Advanced area GUILayout.EndArea(); #endif #endif // Restore skin GUI.skin = old; // Restore matrix GUI.matrix = oldMatrix; } public static void FirstRun() { Tap.enableTap = false; } public static bool UpdateSettings() { #if UNITY_STANDALONE_WIN || UNITY_STANDALONE_MAC || UNITY_STANDALONE_LINUX || UNITY_WEBPLAYER // Update display mode Resolution current = Screen.resolutions[currentResolution]; // Set display mode if (current.width != Screen.width || current.height != Screen.height || (fullscreen == 1) != Screen.fullScreen) { Screen.SetResolution(current.width, current.height, fullscreen == 1); } // Update quality settings if (textureres > 0) QualitySettings.SetQualityLevel(quality); else QualitySettings.SetQualityLevel(quality); // Custom QualitySettings.antiAliasing = aalevel; QualitySettings.anisotropicFiltering = (aniso > 0 ? AnisotropicFiltering.Enable : AnisotropicFiltering.Disable); QualitySettings.vSyncCount = vsync; #endif return true; } public static void Save() { #if UNITY_WEBPLAYER PlayerPrefs.SetFloat("sensitivity", sensitivity); PlayerPrefs.SetFloat("mastervolume", mastervolume); PlayerPrefs.SetFloat("bgmvolume", bgmvolume); PlayerPrefs.SetFloat("sfxvolume", sfxvolume); PlayerPrefs.SetInt("firstrun", System.Convert.ToInt32(firstrun)); PlayerPrefs.SetString("resolution", Screen.resolutions[currentResolution].width + "x" + Screen.resolutions[currentResolution].height); PlayerPrefs.SetInt("fullscreen", fullscreen); PlayerPrefs.SetInt("quality", quality); PlayerPrefs.SetInt("aalevel", aalevel); PlayerPrefs.SetInt("aniso", aniso); PlayerPrefs.SetInt("vsync", vsync); PlayerPrefs.SetInt("textureres", textureres); PlayerPrefs.SetInt("advanced", System.Convert.ToInt32(advanced)); PlayerPrefs.SetInt("networking", System.Convert.ToInt32(networking)); #else using (StreamWriter w = File.CreateText(Application.persistentDataPath + "/" + optionsfile)) { w.WriteLine("sensitivity=" + sensitivity); w.WriteLine("mastervolume=" + mastervolume); w.WriteLine("bgmvolume=" + bgmvolume); w.WriteLine("sfxvolume=" + sfxvolume); w.WriteLine("firstrun=" + firstrun); # if UNITY_STANDALONE_WIN || UNITY_STANDALONE_MAC || UNITY_STANDALONE_LINUX w.WriteLine("resolution=" + Screen.resolutions[currentResolution].width + "x" + Screen.resolutions[currentResolution].height); w.WriteLine("fullscreen=" + fullscreen); w.WriteLine("quality=" + quality); w.WriteLine("aalevel=" + aalevel); w.WriteLine("aniso=" + aniso); w.WriteLine("vsync=" + vsync); w.WriteLine("textureres=" + textureres); w.WriteLine("advanced=" + advanced); w.WriteLine("networking=" + networking); # endif } #endif } private void SetQuality(int level) { level = Mathf.Clamp(level, 0, 3); quality = level; aalevel = level; aniso = (level > 0 ? 1 : 0); vsync = 1; textureres = Mathf.Clamp(level, 0, 2); } private static void Load() { if (!loaded) { loaded = true; #if UNITY_WEBPLAYER // Load sensitivity = PlayerPrefs.GetFloat("sensitivity", sensitivity); mastervolume = PlayerPrefs.GetFloat("mastervolume", mastervolume); bgmvolume = PlayerPrefs.GetFloat("bgmvolume", bgmvolume); sfxvolume = PlayerPrefs.GetFloat("sfxvolume", sfxvolume); firstrun = System.Convert.ToBoolean(PlayerPrefs.GetInt("firstrun", System.Convert.ToInt32(firstrun))); fullscreen = PlayerPrefs.GetInt("fullscreen", fullscreen); quality = PlayerPrefs.GetInt("quality", quality); aalevel = PlayerPrefs.GetInt("aalevel", aalevel); aniso = PlayerPrefs.GetInt("aniso", aniso); vsync = PlayerPrefs.GetInt("vsync", vsync); textureres = PlayerPrefs.GetInt("textureres", textureres); advanced = System.Convert.ToBoolean(PlayerPrefs.GetInt("advanced", System.Convert.ToInt32(advanced))); networking = System.Convert.ToBoolean(PlayerPrefs.GetInt("networking", System.Convert.ToInt32(networking))); string[] size = PlayerPrefs.GetString("resolution", Screen.resolutions[currentResolution].width + "x" + Screen.resolutions[currentResolution].height).Split('x'); float x, y; if (float.TryParse(size[0], out x) && float.TryParse(size[1], out y)) { currentResolution = 0; for (int i = 0; i < Screen.resolutions.Length; ++i) { Resolution resolution = Screen.resolutions[i]; if (resolution.width == x && resolution.height == y) { currentResolution = i; break; } } } #else if (!File.Exists(Application.persistentDataPath + "/" + optionsfile)) { // Set resolution currentResolution = Screen.resolutions.Length-1; fullscreen = 0; UpdateSettings(); // Create new settings file Save(); } else { string[] allLines = File.ReadAllLines(Application.persistentDataPath + "/" + optionsfile); foreach (string line in allLines) { string[] parts = line.Split('='); if (parts.Length > 1) { // Switch by setting name switch (parts[0]) { case "resolution": string[] size = parts[1].Split('x'); if (size.Length > 1) { float x, y; if (float.TryParse(size[0], out x) && float.TryParse(size[1], out y)) { currentResolution = 0; for (int i = 0; i < Screen.resolutions.Length; ++i) { Resolution resolution = Screen.resolutions[i]; if (resolution.width == x && resolution.height == y) { currentResolution = i; break; } } } } break; case "fullscreen": int.TryParse(parts[1], out fullscreen); break; case "quality": int.TryParse(parts[1], out quality); break; case "aalevel": int.TryParse(parts[1], out aalevel); break; case "aniso": int.TryParse(parts[1], out aniso); break; case "vsync": int.TryParse(parts[1], out vsync); break; case "textureres": int.TryParse(parts[1], out textureres); break; case "sensitivity": float.TryParse(parts[1], out sensitivity); break; case "mastervolume": float.TryParse(parts[1], out mastervolume); break; case "bgmvolume": float.TryParse(parts[1], out bgmvolume); break; case "sfxvolume": float.TryParse(parts[1], out sfxvolume); break; case "advanced": bool.TryParse(parts[1], out advanced); break; case "networking": bool.TryParse(parts[1], out networking); break; case "firstrun": bool.TryParse(parts[1], out firstrun); break; } } } } // Get index of current resolution if it's listed currentResolution = 0; for (int i = 0; i < Screen.resolutions.Length; ++i) { Resolution resolution = Screen.resolutions[i]; if (resolution.width == Screen.width && resolution.height == Screen.height) { currentResolution = i; break; } } #endif UpdateSettings(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Runtime.InteropServices; using Internals = System.Net.Internals; internal static partial class Interop { internal static partial class IpHlpApi { // TODO: #3562 - Replace names with the ones from the Windows SDK. [Flags] internal enum AdapterFlags { DnsEnabled = 0x01, RegisterAdapterSuffix = 0x02, DhcpEnabled = 0x04, ReceiveOnly = 0x08, NoMulticast = 0x10, Ipv6OtherStatefulConfig = 0x20, NetBiosOverTcp = 0x40, IPv4Enabled = 0x80, IPv6Enabled = 0x100, IPv6ManagedAddressConfigurationSupported = 0x200, } [Flags] internal enum AdapterAddressFlags { DnsEligible = 0x1, Transient = 0x2 } internal enum OldOperationalStatus { NonOperational = 0, Unreachable = 1, Disconnected = 2, Connecting = 3, Connected = 4, Operational = 5 } [Flags] internal enum GetAdaptersAddressesFlags { SkipUnicast = 0x0001, SkipAnycast = 0x0002, SkipMulticast = 0x0004, SkipDnsServer = 0x0008, IncludePrefix = 0x0010, SkipFriendlyName = 0x0020, IncludeWins = 0x0040, IncludeGateways = 0x0080, IncludeAllInterfaces = 0x0100, IncludeAllCompartments = 0x0200, IncludeTunnelBindingOrder = 0x0400, } [StructLayout(LayoutKind.Sequential)] internal struct IpSocketAddress { internal IntPtr address; internal int addressLength; internal IPAddress MarshalIPAddress() { // Determine the address family used to create the IPAddress. AddressFamily family = (addressLength > Internals.SocketAddress.IPv4AddressSize) ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork; Internals.SocketAddress sockAddress = new Internals.SocketAddress(family, addressLength); Marshal.Copy(address, sockAddress.Buffer, 0, addressLength); return sockAddress.GetIPAddress(); } } // IP_ADAPTER_ANYCAST_ADDRESS // IP_ADAPTER_MULTICAST_ADDRESS // IP_ADAPTER_DNS_SERVER_ADDRESS // IP_ADAPTER_WINS_SERVER_ADDRESS // IP_ADAPTER_GATEWAY_ADDRESS [StructLayout(LayoutKind.Sequential)] internal struct IpAdapterAddress { internal uint length; internal AdapterAddressFlags flags; internal IntPtr next; internal IpSocketAddress address; internal static InternalIPAddressCollection MarshalIpAddressCollection(IntPtr ptr) { InternalIPAddressCollection addressList = new InternalIPAddressCollection(); while (ptr != IntPtr.Zero) { IpAdapterAddress addressStructure = Marshal.PtrToStructure<IpAdapterAddress>(ptr); IPAddress address = addressStructure.address.MarshalIPAddress(); addressList.InternalAdd(address); ptr = addressStructure.next; } return addressList; } internal static IPAddressInformationCollection MarshalIpAddressInformationCollection(IntPtr ptr) { IPAddressInformationCollection addressList = new IPAddressInformationCollection(); while (ptr != IntPtr.Zero) { IpAdapterAddress addressStructure = Marshal.PtrToStructure<IpAdapterAddress>(ptr); IPAddress address = addressStructure.address.MarshalIPAddress(); addressList.InternalAdd(new SystemIPAddressInformation(address, addressStructure.flags)); ptr = addressStructure.next; } return addressList; } } [StructLayout(LayoutKind.Sequential)] internal struct IpAdapterUnicastAddress { internal uint length; internal AdapterAddressFlags flags; internal IntPtr next; internal IpSocketAddress address; internal PrefixOrigin prefixOrigin; internal SuffixOrigin suffixOrigin; internal DuplicateAddressDetectionState dadState; internal uint validLifetime; internal uint preferredLifetime; internal uint leaseLifetime; internal byte prefixLength; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct IpAdapterAddresses { internal const int MAX_ADAPTER_ADDRESS_LENGTH = 8; internal uint length; internal uint index; internal IntPtr next; // Needs to be ANSI. [MarshalAs(UnmanagedType.LPStr)] internal string AdapterName; internal IntPtr firstUnicastAddress; internal IntPtr firstAnycastAddress; internal IntPtr firstMulticastAddress; internal IntPtr firstDnsServerAddress; internal string dnsSuffix; internal string description; internal string friendlyName; [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_ADAPTER_ADDRESS_LENGTH)] internal byte[] address; internal uint addressLength; internal AdapterFlags flags; internal uint mtu; internal NetworkInterfaceType type; internal OperationalStatus operStatus; internal uint ipv6Index; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] internal uint[] zoneIndices; internal IntPtr firstPrefix; internal ulong transmitLinkSpeed; internal ulong receiveLinkSpeed; internal IntPtr firstWinsServerAddress; internal IntPtr firstGatewayAddress; internal uint ipv4Metric; internal uint ipv6Metric; internal ulong luid; internal IpSocketAddress dhcpv4Server; internal uint compartmentId; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] internal byte[] networkGuid; internal InterfaceConnectionType connectionType; internal InterfaceTunnelType tunnelType; internal IpSocketAddress dhcpv6Server; // Never available in Windows. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 130)] internal byte[] dhcpv6ClientDuid; internal uint dhcpv6ClientDuidLength; internal uint dhcpV6Iaid; /* Windows 2008 + PIP_ADAPTER_DNS_SUFFIX FirstDnsSuffix; * */ } internal enum InterfaceConnectionType : int { Dedicated = 1, Passive = 2, Demand = 3, Maximum = 4, } internal enum InterfaceTunnelType : int { None = 0, Other = 1, Direct = 2, SixToFour = 11, Isatap = 13, Teredo = 14, IpHttps = 15, } /// <summary> /// IP_PER_ADAPTER_INFO - per-adapter IP information such as DNS server list. /// </summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] internal struct IpPerAdapterInfo { internal bool autoconfigEnabled; internal bool autoconfigActive; internal IntPtr currentDnsServer; /* IpAddressList* */ internal IpAddrString dnsServerList; }; /// <summary> /// Store an IP address with its corresponding subnet mask, /// both as dotted decimal strings. /// </summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] internal struct IpAddrString { internal IntPtr Next; /* struct _IpAddressList* */ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] internal string IpAddress; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] internal string IpMask; internal uint Context; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct MibIfRow2 // MIB_IF_ROW2 { private const int GuidLength = 16; private const int IfMaxStringSize = 256; private const int IfMaxPhysAddressLength = 32; internal ulong interfaceLuid; internal uint interfaceIndex; [MarshalAs(UnmanagedType.ByValArray, SizeConst = GuidLength)] internal byte[] interfaceGuid; [MarshalAs(UnmanagedType.ByValArray, SizeConst = IfMaxStringSize + 1)] internal char[] alias; // Null terminated string. [MarshalAs(UnmanagedType.ByValArray, SizeConst = IfMaxStringSize + 1)] internal char[] description; // Null terminated string. internal uint physicalAddressLength; [MarshalAs(UnmanagedType.ByValArray, SizeConst = IfMaxPhysAddressLength)] internal byte[] physicalAddress; // ANSI [MarshalAs(UnmanagedType.ByValArray, SizeConst = IfMaxPhysAddressLength)] internal byte[] permanentPhysicalAddress; // ANSI internal uint mtu; internal NetworkInterfaceType type; internal InterfaceTunnelType tunnelType; internal uint mediaType; // Enum internal uint physicalMediumType; // Enum internal uint accessType; // Enum internal uint directionType; // Enum internal byte interfaceAndOperStatusFlags; // Flags Enum internal OperationalStatus operStatus; internal uint adminStatus; // Enum internal uint mediaConnectState; // Enum [MarshalAs(UnmanagedType.ByValArray, SizeConst = GuidLength)] internal byte[] networkGuid; internal InterfaceConnectionType connectionType; internal ulong transmitLinkSpeed; internal ulong receiveLinkSpeed; internal ulong inOctets; internal ulong inUcastPkts; internal ulong inNUcastPkts; internal ulong inDiscards; internal ulong inErrors; internal ulong inUnknownProtos; internal ulong inUcastOctets; internal ulong inMulticastOctets; internal ulong inBroadcastOctets; internal ulong outOctets; internal ulong outUcastPkts; internal ulong outNUcastPkts; internal ulong outDiscards; internal ulong outErrors; internal ulong outUcastOctets; internal ulong outMulticastOctets; internal ulong outBroadcastOctets; internal ulong outQLen; } [StructLayout(LayoutKind.Sequential)] internal struct MibUdpStats { internal uint datagramsReceived; internal uint incomingDatagramsDiscarded; internal uint incomingDatagramsWithErrors; internal uint datagramsSent; internal uint udpListeners; } [StructLayout(LayoutKind.Sequential)] internal struct MibTcpStats { internal uint reTransmissionAlgorithm; internal uint minimumRetransmissionTimeOut; internal uint maximumRetransmissionTimeOut; internal uint maximumConnections; internal uint activeOpens; internal uint passiveOpens; internal uint failedConnectionAttempts; internal uint resetConnections; internal uint currentConnections; internal uint segmentsReceived; internal uint segmentsSent; internal uint segmentsResent; internal uint errorsReceived; internal uint segmentsSentWithReset; internal uint cumulativeConnections; } [StructLayout(LayoutKind.Sequential)] internal struct MibIpStats { internal bool forwardingEnabled; internal uint defaultTtl; internal uint packetsReceived; internal uint receivedPacketsWithHeaderErrors; internal uint receivedPacketsWithAddressErrors; internal uint packetsForwarded; internal uint receivedPacketsWithUnknownProtocols; internal uint receivedPacketsDiscarded; internal uint receivedPacketsDelivered; internal uint packetOutputRequests; internal uint outputPacketRoutingDiscards; internal uint outputPacketsDiscarded; internal uint outputPacketsWithNoRoute; internal uint packetReassemblyTimeout; internal uint packetsReassemblyRequired; internal uint packetsReassembled; internal uint packetsReassemblyFailed; internal uint packetsFragmented; internal uint packetsFragmentFailed; internal uint packetsFragmentCreated; internal uint interfaces; internal uint ipAddresses; internal uint routes; } [StructLayout(LayoutKind.Sequential)] internal struct MibIcmpInfo { internal MibIcmpStats inStats; internal MibIcmpStats outStats; } [StructLayout(LayoutKind.Sequential)] internal struct MibIcmpStats { internal uint messages; internal uint errors; internal uint destinationUnreachables; internal uint timeExceeds; internal uint parameterProblems; internal uint sourceQuenches; internal uint redirects; internal uint echoRequests; internal uint echoReplies; internal uint timestampRequests; internal uint timestampReplies; internal uint addressMaskRequests; internal uint addressMaskReplies; } [StructLayout(LayoutKind.Sequential)] internal struct MibIcmpInfoEx { internal MibIcmpStatsEx inStats; internal MibIcmpStatsEx outStats; } [StructLayout(LayoutKind.Sequential)] internal struct MibIcmpStatsEx { internal uint dwMsgs; internal uint dwErrors; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)] internal uint[] rgdwTypeCount; } [StructLayout(LayoutKind.Sequential)] internal struct MibTcpTable { internal uint numberOfEntries; } [StructLayout(LayoutKind.Sequential)] internal struct MibTcpRow { internal TcpState state; internal uint localAddr; internal byte localPort1; internal byte localPort2; // Ports are only 16 bit values (in network WORD order, 3,4,1,2). // There are reports where the high order bytes have garbage in them. internal byte ignoreLocalPort3; internal byte ignoreLocalPort4; internal uint remoteAddr; internal byte remotePort1; internal byte remotePort2; // Ports are only 16 bit values (in network WORD order, 3,4,1,2). // There are reports where the high order bytes have garbage in them. internal byte ignoreRemotePort3; internal byte ignoreRemotePort4; } [StructLayout(LayoutKind.Sequential)] internal struct MibTcp6TableOwnerPid { internal uint numberOfEntries; } [StructLayout(LayoutKind.Sequential)] internal struct MibTcp6RowOwnerPid { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] internal byte[] localAddr; internal uint localScopeId; internal byte localPort1; internal byte localPort2; // Ports are only 16 bit values (in network WORD order, 3,4,1,2). // There are reports where the high order bytes have garbage in them. internal byte ignoreLocalPort3; internal byte ignoreLocalPort4; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] internal byte[] remoteAddr; internal uint remoteScopeId; internal byte remotePort1; internal byte remotePort2; // Ports are only 16 bit values (in network WORD order, 3,4,1,2). // There are reports where the high order bytes have garbage in them. internal byte ignoreRemotePort3; internal byte ignoreRemotePort4; internal TcpState state; internal uint owningPid; } internal enum TcpTableClass { TcpTableBasicListener = 0, TcpTableBasicConnections = 1, TcpTableBasicAll = 2, TcpTableOwnerPidListener = 3, TcpTableOwnerPidConnections = 4, TcpTableOwnerPidAll = 5, TcpTableOwnerModuleListener = 6, TcpTableOwnerModuleConnections = 7, TcpTableOwnerModuleAll = 8 } [StructLayout(LayoutKind.Sequential)] internal struct MibUdpTable { internal uint numberOfEntries; } [StructLayout(LayoutKind.Sequential)] internal struct MibUdpRow { internal uint localAddr; internal byte localPort1; internal byte localPort2; // Ports are only 16 bit values (in network WORD order, 3,4,1,2). // There are reports where the high order bytes have garbage in them. internal byte ignoreLocalPort3; internal byte ignoreLocalPort4; } internal enum UdpTableClass { UdpTableBasic = 0, UdpTableOwnerPid = 1, UdpTableOwnerModule = 2 } [StructLayout(LayoutKind.Sequential)] internal struct MibUdp6TableOwnerPid { internal uint numberOfEntries; } [StructLayout(LayoutKind.Sequential)] internal struct MibUdp6RowOwnerPid { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] internal byte[] localAddr; internal uint localScopeId; internal byte localPort1; internal byte localPort2; // Ports are only 16 bit values (in network WORD order, 3,4,1,2). // There are reports where the high order bytes have garbage in them. internal byte ignoreLocalPort3; internal byte ignoreLocalPort4; internal uint owningPid; } internal delegate void StableUnicastIpAddressTableDelegate(IntPtr context, IntPtr table); [DllImport(Interop.Libraries.IpHlpApi)] internal extern static uint GetAdaptersAddresses( AddressFamily family, uint flags, IntPtr pReserved, SafeLocalAllocHandle adapterAddresses, ref uint outBufLen); [DllImport(Interop.Libraries.IpHlpApi)] internal extern static uint GetBestInterfaceEx(byte[] ipAddress, out int index); [DllImport(Interop.Libraries.IpHlpApi)] internal extern static uint GetIfEntry2(ref MibIfRow2 pIfRow); [DllImport(Interop.Libraries.IpHlpApi)] internal extern static uint GetIpStatisticsEx(out MibIpStats statistics, AddressFamily family); [DllImport(Interop.Libraries.IpHlpApi)] internal extern static uint GetTcpStatisticsEx(out MibTcpStats statistics, AddressFamily family); [DllImport(Interop.Libraries.IpHlpApi)] internal extern static uint GetUdpStatisticsEx(out MibUdpStats statistics, AddressFamily family); [DllImport(Interop.Libraries.IpHlpApi)] internal extern static uint GetIcmpStatistics(out MibIcmpInfo statistics); [DllImport(Interop.Libraries.IpHlpApi)] internal extern static uint GetIcmpStatisticsEx(out MibIcmpInfoEx statistics, AddressFamily family); [DllImport(Interop.Libraries.IpHlpApi)] internal extern static uint GetTcpTable(SafeLocalAllocHandle pTcpTable, ref uint dwOutBufLen, bool order); [DllImport(Interop.Libraries.IpHlpApi)] internal extern static uint GetExtendedTcpTable(SafeLocalAllocHandle pTcpTable, ref uint dwOutBufLen, bool order, uint IPVersion, TcpTableClass tableClass, uint reserved); [DllImport(Interop.Libraries.IpHlpApi)] internal extern static uint GetUdpTable(SafeLocalAllocHandle pUdpTable, ref uint dwOutBufLen, bool order); [DllImport(Interop.Libraries.IpHlpApi)] internal extern static uint GetExtendedUdpTable(SafeLocalAllocHandle pUdpTable, ref uint dwOutBufLen, bool order, uint IPVersion, UdpTableClass tableClass, uint reserved); [DllImport(Interop.Libraries.IpHlpApi)] internal extern static uint GetPerAdapterInfo(uint IfIndex, SafeLocalAllocHandle pPerAdapterInfo, ref uint pOutBufLen); [DllImport(Interop.Libraries.IpHlpApi)] internal static extern void FreeMibTable(IntPtr handle); [DllImport(Interop.Libraries.IpHlpApi)] internal static extern uint CancelMibChangeNotify2(IntPtr notificationHandle); [DllImport(Interop.Libraries.IpHlpApi)] internal static extern uint NotifyStableUnicastIpAddressTable( [In] AddressFamily addressFamily, [Out] out SafeFreeMibTable table, [MarshalAs(UnmanagedType.FunctionPtr)][In] StableUnicastIpAddressTableDelegate callback, [In] IntPtr context, [Out] out SafeCancelMibChangeNotify notificationHandle); [DllImport(Interop.Libraries.IpHlpApi, ExactSpelling = true)] internal extern static uint GetNetworkParams(SafeLocalAllocHandle pFixedInfo, ref uint pOutBufLen); } }
// 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.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { public sealed partial class FileCodeModel { private const int ElementAddedDispId = 1; private const int ElementChangedDispId = 2; private const int ElementDeletedDispId = 3; private const int ElementDeletedDispId2 = 4; public bool FireEvents() { var needMoreTime = false; _codeElementTable.CleanUpDeadObjects(); needMoreTime = _codeElementTable.NeedsCleanUp; if (this.IsZombied) { // file is removed from the solution. this can happen if a fireevent is enqueued to foreground notification service // but the file itself is removed from the solution before it has a chance to run return needMoreTime; } Document document; if (!TryGetDocument(out document)) { // file is removed from the solution. this can happen if a fireevent is enqueued to foreground notification service // but the file itself is removed from the solution before it has a chance to run return needMoreTime; } // TODO(DustinCa): Enqueue unknown change event if a file is closed without being saved. var oldTree = _lastSyntaxTree; var newTree = document .GetSyntaxTreeAsync(CancellationToken.None) .WaitAndGetResult_CodeModel(CancellationToken.None); _lastSyntaxTree = newTree; if (oldTree == newTree || oldTree.IsEquivalentTo(newTree, topLevel: true)) { return needMoreTime; } var eventQueue = this.CodeModelService.CollectCodeModelEvents(oldTree, newTree); if (eventQueue.Count == 0) { return needMoreTime; } var provider = GetAbstractProject() as IProjectCodeModelProvider; if (provider == null) { return needMoreTime; } ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> fileCodeModelHandle; if (!provider.ProjectCodeModel.TryGetCachedFileCodeModel(this.Workspace.GetFilePath(GetDocumentId()), out fileCodeModelHandle)) { return needMoreTime; } var extensibility = (EnvDTE80.IVsExtensibility2)this.State.ServiceProvider.GetService(typeof(EnvDTE.IVsExtensibility)); foreach (var codeModelEvent in eventQueue) { EnvDTE.CodeElement element; object parentElement; GetElementsForCodeModelEvent(codeModelEvent, out element, out parentElement); if (codeModelEvent.Type == CodeModelEventType.Add) { extensibility.FireCodeModelEvent(ElementAddedDispId, element, EnvDTE80.vsCMChangeKind.vsCMChangeKindUnknown); } else if (codeModelEvent.Type == CodeModelEventType.Remove) { extensibility.FireCodeModelEvent3(ElementDeletedDispId2, parentElement, element, EnvDTE80.vsCMChangeKind.vsCMChangeKindUnknown); extensibility.FireCodeModelEvent(ElementDeletedDispId, element, EnvDTE80.vsCMChangeKind.vsCMChangeKindUnknown); } else if (codeModelEvent.Type.IsChange()) { extensibility.FireCodeModelEvent(ElementChangedDispId, element, ConvertToChangeKind(codeModelEvent.Type)); } else { Debug.Fail("Invalid event type: " + codeModelEvent.Type); } } return needMoreTime; } private EnvDTE80.vsCMChangeKind ConvertToChangeKind(CodeModelEventType eventType) { EnvDTE80.vsCMChangeKind result = 0; if ((eventType & CodeModelEventType.Rename) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindRename; } if ((eventType & CodeModelEventType.Unknown) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindUnknown; } if ((eventType & CodeModelEventType.BaseChange) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindBaseChange; } if ((eventType & CodeModelEventType.TypeRefChange) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindTypeRefChange; } if ((eventType & CodeModelEventType.SigChange) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindSignatureChange; } if ((eventType & CodeModelEventType.ArgChange) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindArgumentChange; } return result; } // internal for testing internal void GetElementsForCodeModelEvent(CodeModelEvent codeModelEvent, out EnvDTE.CodeElement element, out object parentElement) { parentElement = GetParentElementForCodeModelEvent(codeModelEvent); if (codeModelEvent.Node == null) { element = this.CodeModelService.CreateUnknownRootNamespaceCodeElement(this.State, this); } else if (this.CodeModelService.IsParameterNode(codeModelEvent.Node)) { element = GetParameterElementForCodeModelEvent(codeModelEvent, parentElement); } else if (this.CodeModelService.IsAttributeNode(codeModelEvent.Node)) { element = GetAttributeElementForCodeModelEvent(codeModelEvent, parentElement); } else if (this.CodeModelService.IsAttributeArgumentNode(codeModelEvent.Node)) { element = GetAttributeArgumentElementForCodeModelEvent(codeModelEvent, parentElement); } else { if (codeModelEvent.Type == CodeModelEventType.Remove) { element = this.CodeModelService.CreateUnknownCodeElement(this.State, this, codeModelEvent.Node); } else { element = this.GetOrCreateCodeElement<EnvDTE.CodeElement>(codeModelEvent.Node); } } if (element == null) { Debug.Fail("We should have created an element for this event!"); } Debug.Assert(codeModelEvent.Type != CodeModelEventType.Remove || parentElement != null); } private object GetParentElementForCodeModelEvent(CodeModelEvent codeModelEvent) { if (this.CodeModelService.IsParameterNode(codeModelEvent.Node) || this.CodeModelService.IsAttributeArgumentNode(codeModelEvent.Node)) { if (codeModelEvent.ParentNode != null) { return this.GetOrCreateCodeElement<EnvDTE.CodeElement>(codeModelEvent.ParentNode); } } else if (this.CodeModelService.IsAttributeNode(codeModelEvent.Node)) { if (codeModelEvent.ParentNode != null) { return this.GetOrCreateCodeElement<EnvDTE.CodeElement>(codeModelEvent.ParentNode); } else { return this; } } else if (codeModelEvent.Type == CodeModelEventType.Remove) { if (codeModelEvent.ParentNode != null && codeModelEvent.ParentNode.Parent != null) { return this.GetOrCreateCodeElement<EnvDTE.CodeElement>(codeModelEvent.ParentNode); } else { return this; } } return null; } private EnvDTE.CodeElement GetParameterElementForCodeModelEvent(CodeModelEvent codeModelEvent, object parentElement) { var parentDelegate = parentElement as EnvDTE.CodeDelegate; if (parentDelegate != null) { return GetParameterElementForCodeModelEvent(codeModelEvent, parentDelegate.Parameters, parentElement); } var parentFunction = parentElement as EnvDTE.CodeFunction; if (parentFunction != null) { return GetParameterElementForCodeModelEvent(codeModelEvent, parentFunction.Parameters, parentElement); } var parentProperty = parentElement as EnvDTE80.CodeProperty2; if (parentProperty != null) { return GetParameterElementForCodeModelEvent(codeModelEvent, parentProperty.Parameters, parentElement); } return null; } private EnvDTE.CodeElement GetParameterElementForCodeModelEvent(CodeModelEvent codeModelEvent, EnvDTE.CodeElements parentParameters, object parentElement) { if (parentParameters == null) { return null; } var parameterName = this.CodeModelService.GetName(codeModelEvent.Node); if (codeModelEvent.Type == CodeModelEventType.Remove) { var parentCodeElement = ComAggregate.TryGetManagedObject<AbstractCodeMember>(parentElement); if (parentCodeElement != null) { return (EnvDTE.CodeElement)CodeParameter.Create(this.State, parentCodeElement, parameterName); } } else { return parentParameters.Item(parameterName); } return null; } private EnvDTE.CodeElement GetAttributeElementForCodeModelEvent(CodeModelEvent codeModelEvent, object parentElement) { var node = codeModelEvent.Node; var parentNode = codeModelEvent.ParentNode; var eventType = codeModelEvent.Type; var parentType = parentElement as EnvDTE.CodeType; if (parentType != null) { return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentType.Attributes, parentElement); } var parentFunction = parentElement as EnvDTE.CodeFunction; if (parentFunction != null) { return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentFunction.Attributes, parentElement); } var parentProperty = parentElement as EnvDTE.CodeProperty; if (parentProperty != null) { return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentProperty.Attributes, parentElement); } var parentEvent = parentElement as EnvDTE80.CodeEvent; if (parentEvent != null) { return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentEvent.Attributes, parentElement); } var parentVariable = parentElement as EnvDTE.CodeVariable; if (parentVariable != null) { return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentVariable.Attributes, parentElement); } // In the following case, parentNode is null and the root should be used instead. var parentFileCodeModel = parentElement as EnvDTE.FileCodeModel; if (parentFileCodeModel != null) { var fileCodeModel = ComAggregate.TryGetManagedObject<FileCodeModel>(parentElement); parentNode = fileCodeModel.GetSyntaxRoot(); return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentFileCodeModel.CodeElements, parentElement); } return null; } private EnvDTE.CodeElement GetAttributeElementForCodeModelEvent(SyntaxNode node, SyntaxNode parentNode, CodeModelEventType eventType, EnvDTE.CodeElements elementsToSearch, object parentObject) { if (elementsToSearch == null) { return null; } string name; int ordinal; CodeModelService.GetAttributeNameAndOrdinal(parentNode, node, out name, out ordinal); if (eventType == CodeModelEventType.Remove) { if (parentObject is EnvDTE.CodeElement) { var parentCodeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(parentObject); if (parentCodeElement != null) { return (EnvDTE.CodeElement)CodeAttribute.Create(this.State, this, parentCodeElement, name, ordinal); } } else if (parentObject is EnvDTE.FileCodeModel) { var parentFileCodeModel = ComAggregate.TryGetManagedObject<FileCodeModel>(parentObject); if (parentFileCodeModel != null && parentFileCodeModel == this) { return (EnvDTE.CodeElement)CodeAttribute.Create(this.State, this, null, name, ordinal); } } } else { int testOrdinal = 0; foreach (EnvDTE.CodeElement element in elementsToSearch) { if (element.Kind != EnvDTE.vsCMElement.vsCMElementAttribute) { continue; } if (element.Name == name) { if (ordinal == testOrdinal) { return element; } testOrdinal++; } } } return null; } private EnvDTE.CodeElement GetAttributeArgumentElementForCodeModelEvent(CodeModelEvent codeModelEvent, object parentElement) { var parentAttribute = parentElement as EnvDTE80.CodeAttribute2; if (parentAttribute != null) { return GetAttributeArgumentForCodeModelEvent(codeModelEvent, parentAttribute.Arguments, parentElement); } return null; } private EnvDTE.CodeElement GetAttributeArgumentForCodeModelEvent(CodeModelEvent codeModelEvent, EnvDTE.CodeElements parentAttributeArguments, object parentElement) { if (parentAttributeArguments == null) { return null; } SyntaxNode attributeNode; int ordinal; CodeModelService.GetAttributeArgumentParentAndIndex(codeModelEvent.Node, out attributeNode, out ordinal); if (codeModelEvent.Type == CodeModelEventType.Remove) { var parentCodeElement = ComAggregate.TryGetManagedObject<CodeAttribute>(parentElement); if (parentCodeElement != null) { return (EnvDTE.CodeElement)CodeAttributeArgument.Create(this.State, parentCodeElement, ordinal); } } else { return parentAttributeArguments.Item(ordinal + 1); // Needs to be 1-based to call back into code model } return null; } } }
!# issue 1504 movhps qword ptr !# CS_ARCH_X86, CS_MODE_64, CS_OPT_DETAIL 0x0f,0x16,0x08 == movhps xmm1, qword ptr [rax] ; Opcode:0x0f 0x16 0x00 0x00 !# issue 1505 opcode 0f !# CS_ARCH_X86, CS_MODE_64, CS_OPT_DETAIL 0x0f,0xa5,0xc2 == shld edx, eax, cl ; Opcode:0x0f 0xa5 0x00 0x00 !# issue 1478 tbegin. !# CS_ARCH_PPC, CS_MODE_64 | CS_MODE_BIG_ENDIAN, CS_OPT_DETAIL 0x7c,0x20,0x05,0x1d == tbegin. 1 ; Update-CR0: True !# issue 970 PPC bdnzt lt !# CS_ARCH_PPC, CS_MODE_64 | CS_MODE_BIG_ENDIAN, CS_OPT_DETAIL 0x41,0x00,0xff,0xac == bdnzt lt, 0xffffffffffffffac ; operands[0].type: REG = cr0lt !# issue 970 PPC bdnzt eq !# CS_ARCH_PPC, CS_MODE_64 | CS_MODE_BIG_ENDIAN, CS_OPT_DETAIL 0x41,0x02,0xff,0xac == bdnzt eq, 0xffffffffffffffac ; operands[0].type: REG = cr0eq !# issue 969 PPC bdnzflr operand 2 !# CS_ARCH_PPC, CS_MODE_64 | CS_MODE_BIG_ENDIAN, CS_OPT_DETAIL 0x4c,0x10,0x00,0x20 == bdnzflr 4*cr4+lt ; operands[0].type: REG = cr4lt 0x41,0x82,0x00,0x10 == beq 0x10 ; Groups: jump !# issue 1481 ARM64 LDR operand2 !# CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN, CS_OPT_DETAIL 0xe9,0x03,0x40,0xf9 == ldr x9, [sp] ; operands[1].mem.base: REG = sp !# issue 968 PPC absolute branch: bdnzla !# CS_ARCH_PPC, CS_MODE_64 | CS_MODE_BIG_ENDIAN, None 0x1000: 0x42,0x00,0x12,0x37 == bdnzla 0x1234 !# issue 968 PPC absolute branch: bdzla !# CS_ARCH_PPC, CS_MODE_64 | CS_MODE_BIG_ENDIAN, None 0x1000: 0x42,0x40,0x12,0x37 == bdzla 0x1234 !# issue X86 xrelease xchg !# CS_ARCH_X86, CS_MODE_32, None 0xf3,0x87,0x03 == xrelease xchg dword ptr [ebx], eax !# issue X86 xacquire xchg !# CS_ARCH_X86, CS_MODE_32, None 0xf2,0x87,0x03 == xacquire xchg dword ptr [ebx], eax !# issue X86 xrelease !# CS_ARCH_X86, CS_MODE_64, None 0xf3,0xf0,0x31,0x1f == xrelease lock xor dword ptr [rdi], ebx !# issue 1477 X86 xacquire !# CS_ARCH_X86, CS_MODE_64, None 0xf2,0xf0,0x31,0x1f == xacquire lock xor dword ptr [rdi], ebx !# issue PPC JUMP group !# CS_ARCH_PPC, CS_MODE_64 | CS_MODE_BIG_ENDIAN, CS_OPT_DETAIL 0x41,0x82,0x00,0x10 == beq 0x10 ; Groups: jump !# issue 1468 PPC bdnz !# CS_ARCH_PPC, CS_MODE_64 | CS_MODE_BIG_ENDIAN, None 0x101086c: 0x42,0x00,0xff,0xf8 == bdnz 0x1010864 !# issue PPC bdnzt !# CS_ARCH_PPC, CS_MODE_64 | CS_MODE_BIG_ENDIAN, None 0x1000: 0x41,0x00,0xff,0xac == bdnzt lt, 0xfac !# issue 1469 PPC CRx !# CS_ARCH_PPC, CS_MODE_64 | CS_MODE_BIG_ENDIAN, CS_OPT_DETAIL 0x4c,0x02,0x39,0x82 == crxor cr0lt, cr0eq, cr1un ; operands[0].type: REG = cr0lt !# issue 1468 B target !# CS_ARCH_PPC, CS_MODE_64 | CS_MODE_BIG_ENDIAN, None 0x1000: 0x4b,0xff,0xf8,0x00 == b 0x800 !# issue 1456 test alt 1 !# CS_ARCH_X86, CS_MODE_32, None 0xf6,0x08,0x00 == test byte ptr [eax], 0 !# issue 1456 test alt 2 !# CS_ARCH_X86, CS_MODE_32, None 0xf7,0x08,0x00,0x00,0x00,0x00 == test dword ptr [eax], 0 !# issue 1472 lock sub !# CS_ARCH_X86, CS_MODE_32, None 0xF0,0x2B,0x45,0x08 == lock sub eax, dword ptr [ebp + 8] !# issue 1472 lock or !# CS_ARCH_X86, CS_MODE_32, None 0xF0,0x0B,0x45,0x08 == lock or eax, dword ptr [ebp + 8] !# issue 1472 lock and !# CS_ARCH_X86, CS_MODE_32, None 0xF0,0x23,0x45,0x08 == lock and eax, dword ptr [ebp + 8] !# issue 1472 lock add !# CS_ARCH_X86, CS_MODE_32, None 0xF0,0x03,0x45,0x08 == lock add eax, dword ptr [ebp + 8] !# issue 1456 MOV dr !# CS_ARCH_X86, CS_MODE_32, None 0x0f,0x23,0x00 == mov dr0, eax !# issue 1456 MOV dr !# CS_ARCH_X86, CS_MODE_32, None 0x0f,0x21,0x00 == mov eax, dr0 !# issue 1456 MOV cr !# CS_ARCH_X86, CS_MODE_32, None 0x0f,0x22,0x00 == mov cr0, eax !# issue 1472 lock adc !# CS_ARCH_X86, CS_MODE_32, None 0xf0,0x12,0x45,0x08 == lock adc al, byte ptr [ebp + 8] !# issue 1456 xmmword !# CS_ARCH_X86, CS_MODE_32, None 0x66,0x0f,0x2f,0x00 == comisd xmm0, xmmword ptr [eax] !# issue 1456 ARM printPKHASRShiftImm !# CS_ARCH_ARM, CS_MODE_THUMB, None 0xca,0xea,0x21,0x06 == pkhtb r6, sl, r1, asr #0x20 !# issue 1456 EIZ !# CS_ARCH_X86, CS_MODE_32, None 0x8d,0xb4,0x26,0x00,0x00,0x00,0x00 == lea esi, [esi] !# issue 1456 ARM POP !# CS_ARCH_ARM, CS_MODE_LITTLE_ENDIAN, None 0x04,0x10,0x9d,0xe4 == pop {r1} !# issue 1456 !# CS_ARCH_ARM, CS_MODE_LITTLE_ENDIAN, CS_OPT_DETAIL 0x31,0x02,0xa0,0xe1 == lsr r0, r1, r2 ; operands[2].type: REG = r2 !# issue 1456 !# CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN, CS_OPT_DETAIL 0x0c,0x00,0x80,0x12 == mov w12, #-1 ; operands[1].type: IMM = 0xffffffffffffffff 0xb8,0x00,0x00,0x00,0x00 == movl $0, %eax !# issue 1456 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_SYNTAX_ATT 0xb8,0x00,0x00,0x00,0x00 == movl $0, %eax 0xd1,0x5e,0x48 == rcrl $1, 0x48(%esi) !# issue 1456 !# CS_ARCH_X86, CS_MODE_32, None 0xd1,0x5e,0x48 == rcr dword ptr [esi + 0x48], 1 !# issue 1456 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_SYNTAX_ATT 0xd1,0x5e,0x48 == rcrl $1, 0x48(%esi) !# issue 1456 !# CS_ARCH_X86, CS_MODE_32, None 0x62,0x00 == bound eax, qword ptr [eax] !# issue 1454 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0xf0,0x0f,0xb1,0x1e == lock cmpxchg dword ptr [esi], ebx ; Registers read: eax esi ebx !# issue 1452 !# CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN, CS_OPT_DETAIL 0x20,0x3c,0x0c,0x0e == mov w0, v1.s[1] ; Vector Arrangement Specifier: 0xb !# issue 1452 !# CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN, CS_OPT_DETAIL 0x20,0x3c,0x18,0x4e == mov x0, v1.d[1] ; Vector Arrangement Specifier: 0xd !# issue 1452 !# CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN, CS_OPT_DETAIL 0x20,0x3c,0x03,0x0e == umov w0, v1.b[1] ; Vector Arrangement Specifier: 0x4 !# issue 1452 !# CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN, CS_OPT_DETAIL 0x20,0x3c,0x06,0x0e == umov w0, v1.h[1] ; Vector Arrangement Specifier: 0x8 !# issue 1211 !# CS_ARCH_X86, CS_MODE_64, None 0xc4,0xe1,0xf8,0x90,0xc0 == kmovq k0, k0 !# issue 1211 !# CS_ARCH_X86, CS_MODE_64, None 0xc4,0xe1,0xfb,0x92,0xc3 == kmovq k0, rbx !# issue 1211 !# CS_ARCH_X86, CS_MODE_64, None 0x62,0xf1,0x7d,0x48,0x74,0x83,0x12,0x00,0x00,0x00 == vpcmpeqb k0, zmm0, zmmword ptr [rbx + 0x12] !# issue 1211 !# CS_ARCH_X86, CS_MODE_64, None 0x62,0xf2,0x7d,0x48,0x30,0x43,0x08 == vpmovzxbw zmm0, ymmword ptr [rbx + 0x100] !# issue x86 BND register (OSS-fuzz #13467) !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0f,0x1a,0x1a == bndldx bnd3, [edx] ; operands[0].type: REG = bnd3 !# issue 1335 !# CS_ARCH_X86, CS_MODE_32, None 0x0f,0x1f,0xc0 == nop eax !# issue 1335 !# CS_ARCH_X86, CS_MODE_64, None 0x48,0x0f,0x1f,0x00 == nop qword ptr [rax] !# issue 1259 !# CS_ARCH_X86, CS_MODE_64, None 0x0f,0x0d,0x44,0x11,0x40 == prefetch byte ptr [rcx + rdx + 0x40] !# issue 1259 !# CS_ARCH_X86, CS_MODE_64, None 0x41,0x0f,0x0d,0x44,0x12,0x40 == prefetch byte ptr [r10 + rdx + 0x40] !# issue 1304 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_DETAIL 0x66,0x0f,0x7f,0x4c,0x24,0x40 == movdqa xmmword ptr [rsp + 0x40], xmm1 ; operands[0].access: WRITE !# issue 1304 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_DETAIL 0x66,0x0f,0x7e,0x04,0x24 == movd dword ptr [rsp], xmm0 ; operands[0].access: WRITE !# issue 1304 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_DETAIL 0xf3,0x41,0x0f,0x7f,0x4d,0x00 == movdqu xmmword ptr [r13], xmm1 ; operands[0].access: WRITE !# issue 1346 !# CS_ARCH_X86, CS_MODE_64, None 0xf3,0x48,0x0f,0x1e,0xc8 == rdsspq rax !# issue 1346 !# CS_ARCH_X86, CS_MODE_64, None 0xf3,0x0f,0x1e,0xc8 == rdsspd eax !# issue 1346 !# CS_ARCH_X86, CS_MODE_64, None 0xf3,0x48,0x0f,0xae,0xe8 == incsspq rax !# issue 1346 !# CS_ARCH_X86, CS_MODE_64, None 0xf3,0x0f,0xae,0xe8 == incsspd eax !# issue 1346 !# CS_ARCH_X86, CS_MODE_64, None 0xf3,0x0f,0x01,0xea == saveprevssp !# issue 1346 !# CS_ARCH_X86, CS_MODE_64, None 0xf3,0x0f,0x01,0x28 == rstorssp dword ptr [rax] !# issue 1346 !# CS_ARCH_X86, CS_MODE_64, None 0x67,0xf3,0x0f,0x01,0x28 == rstorssp dword ptr [eax] !# issue 1346 !# CS_ARCH_X86, CS_MODE_64, None 0x48,0x0f,0x38,0xf6,0x00 == wrssq qword ptr [rax], rax !# issue 1346 !# CS_ARCH_X86, CS_MODE_64, None 0x67,0x0f,0x38,0xf6,0x00 == wrssd dword ptr [eax], eax !# issue 1346 !# CS_ARCH_X86, CS_MODE_64, None 0xf3,0x0f,0x01,0xe8 == setssbsy !# issue 1346 !# CS_ARCH_X86, CS_MODE_64, None 0xf3,0x0f,0xae,0x30 == clrssbsy dword ptr [rax] !# issue 1346 !# CS_ARCH_X86, CS_MODE_64, None 0x67,0xf3,0x0f,0xae,0x30 == clrssbsy dword ptr [eax] !# issue 1206 !# CS_ARCH_X86, CS_MODE_64, None 0xc4,0xe2,0x7d,0x5a,0x0c,0x0e == vbroadcasti128 ymm1, xmmword ptr [rsi + rcx] !# issue xchg 16bit !# CS_ARCH_X86, CS_MODE_16, None 0x91 == xchg cx, ax !# issue ROL 1, ATT syntax !# CS_ARCH_X86, CS_MODE_64, CS_OPT_SYNTAX_ATT 0x66,0x48,0xf3,0xd1,0xc0 == rolw $1, %ax !# issue 1129 !# CS_ARCH_X86, CS_MODE_64, None 0xf3,0x0f,0x1e,0xfa == endbr64 !# issue 1129 !# CS_ARCH_X86, CS_MODE_32, None 0xf3,0x0f,0x1e,0xfa == endbr64 !# issue 1129 !# CS_ARCH_X86, CS_MODE_64, None 0xf3,0x0f,0x1e,0xfb == endbr32 !# issue 1129 !# CS_ARCH_X86, CS_MODE_32, None 0xf3,0x0f,0x1e,0xfb == endbr32 !# issue x64 jmp !# CS_ARCH_X86, CS_MODE_64, None 0x1000: 0xeb,0xfe == jmp 0x1000 !# issue x64att jmp !# CS_ARCH_X86, CS_MODE_64, CS_OPT_SYNTAX_ATT 0x1000: 0xeb,0xfe == jmp 0x1000 !# issue x32 jmp !# CS_ARCH_X86, CS_MODE_32, None 0x1000: 0xeb,0xfe == jmp 0x1000 !# issue x32att jmp !# CS_ARCH_X86, CS_MODE_32, CS_OPT_SYNTAX_ATT 0x1000: 0xeb,0xfe == jmp 0x1000 !# issue 1389 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_DETAIL 0x66,0x0f,0x73,0xf9,0x01 == pslldq xmm1, 1 ; operands[1].size: 1 !# issue 1389 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_SYNTAX_ATT | CS_OPT_DETAIL 0x66,0x0f,0x73,0xf9,0x01 == pslldq $1, %xmm1 ; operands[0].size: 1 !# issue x64 unsigned !# CS_ARCH_X86, CS_MODE_64, CS_OPT_UNSIGNED 0x66,0x83,0xc0,0x80 == add ax, 0xff80 !# issue x64att unsigned !# CS_ARCH_X86, CS_MODE_64, CS_OPT_SYNTAX_ATT | CS_OPT_UNSIGNED 0x66,0x83,0xc0,0x80 == addw $0xff80, %ax !# issue 1323 !# CS_ARCH_ARM, CS_MODE_THUMB, CS_OPT_DETAIL 0x0: 0x70,0x47,0x00 == bx lr ; op_count: 1 ; operands[0].type: REG = lr ; operands[0].access: READ ; Registers read: lr ; Registers modified: pc ; Groups: thumb jump !# issue 1317 !# CS_ARCH_ARM, CS_MODE_THUMB, CS_OPT_DETAIL 0x0: 0xd0,0xe8,0x11,0xf0 == tbh [r0, r1, lsl #1] ; op_count: 1 ; operands[0].type: MEM ; operands[0].mem.base: REG = r0 ; operands[0].mem.index: REG = r1 ; operands[0].mem.lshift: 0x1 ; operands[0].access: READ ; Shift: 2 = 1 ; Registers read: r0 r1 ; Groups: thumb2 jump !# issue 1308 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_DETAIL 0x0: 0x83,0x3d,0xa1,0x75,0x21,0x00,0x04 == cmp dword ptr [rip + 0x2175a1], 4 ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0x83 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 8 ; modrm: 0x3d ; disp: 0x2175a1 ; sib: 0x0 ; imm_count: 1 ; imms[1]: 0x4 ; op_count: 2 ; operands[0].type: MEM ; operands[0].mem.base: REG = rip ; operands[0].mem.disp: 0x2175a1 ; operands[0].size: 4 ; operands[0].access: READ ; operands[1].type: IMM = 0x4 ; operands[1].size: 4 ; Registers read: rip ; Registers modified: rflags ; EFLAGS: MOD_AF MOD_CF MOD_SF MOD_ZF MOD_PF MOD_OF !# issue 1262 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_DETAIL 0x0: 0x0f,0x95,0x44,0x24,0x5e == setne byte ptr [rsp + 0x5e] ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0x0f 0x95 0x00 0x00 ; rex: 0x0 ; addr_size: 8 ; modrm: 0x44 ; disp: 0x5e ; sib: 0x24 ; sib_base: rsp ; sib_scale: 1 ; op_count: 1 ; operands[0].type: MEM ; operands[0].mem.base: REG = rsp ; operands[0].mem.disp: 0x5e ; operands[0].size: 1 ; operands[0].access: WRITE ; Registers read: rflags rsp ; EFLAGS: TEST_ZF !# issue 1262 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_DETAIL 0x0: 0x0f,0x94,0x44,0x24,0x1f == sete byte ptr [rsp + 0x1f] ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0x0f 0x94 0x00 0x00 ; rex: 0x0 ; addr_size: 8 ; modrm: 0x44 ; disp: 0x1f ; sib: 0x24 ; sib_base: rsp ; sib_scale: 1 ; op_count: 1 ; operands[0].type: MEM ; operands[0].mem.base: REG = rsp ; operands[0].mem.disp: 0x1f ; operands[0].size: 1 ; operands[0].access: WRITE ; Registers read: rflags rsp ; EFLAGS: TEST_ZF !# issue 1263 !# CS_ARCH_X86, CS_MODE_64, None 0x0: 0x67,0x48,0x89,0x18 == mov qword ptr [eax], rbx !# issue 1263 !# CS_ARCH_X86, CS_MODE_64, None 0x0: 0x67,0x48,0x8b,0x03 == mov rax, qword ptr [ebx] !# issue 1255 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_DETAIL 0x0: 0xdb,0x7c,0x24,0x40 == fstp xword ptr [rsp + 0x40] ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0xdb 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 8 ; modrm: 0x7c ; disp: 0x40 ; sib: 0x24 ; sib_base: rsp ; sib_scale: 1 ; op_count: 1 ; operands[0].type: MEM ; operands[0].mem.base: REG = rsp ; operands[0].mem.disp: 0x40 ; operands[0].size: 10 ; operands[0].access: WRITE ; Registers read: rsp ; Registers modified: fpsw ; FPU_FLAGS: MOD_C1 UNDEF_C0 UNDEF_C2 UNDEF_C3 ; Groups: fpu !# issue 1255 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_DETAIL 0x0: 0xdd,0xd9 == fstp st(1) ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0xdd 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 8 ; modrm: 0xd9 ; disp: 0x0 ; sib: 0x0 ; op_count: 1 ; operands[0].type: REG = st(1) ; operands[0].size: 10 ; operands[0].access: WRITE ; Registers modified: fpsw st(1) ; EFLAGS: MOD_CF PRIOR_SF PRIOR_AF PRIOR_PF !# issue 1255 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_DETAIL 0x0: 0xdf,0x7c,0x24,0x68 == fistp qword ptr [rsp + 0x68] ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0xdf 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 8 ; modrm: 0x7c ; disp: 0x68 ; sib: 0x24 ; sib_base: rsp ; sib_scale: 1 ; op_count: 1 ; operands[0].type: MEM ; operands[0].mem.base: REG = rsp ; operands[0].mem.disp: 0x68 ; operands[0].size: 8 ; operands[0].access: WRITE ; Registers read: rsp ; Registers modified: fpsw ; FPU_FLAGS: RESET_C1 UNDEF_C0 UNDEF_C2 UNDEF_C3 ; Groups: fpu !# issue 1221 !# CS_ARCH_SPARC, CS_MODE_BIG_ENDIAN, None 0x0: 0x55,0x48,0x89,0xe5 == call 0x55222794 !# issue 1144 !# CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN, None 0x0: 0x00,0x00,0x02,0xb6 == tbz x0, #0x20, #0x4000 !# issue 1144 !# CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN, None 0x0: 0x00,0x00,0x04,0xb6 == tbz x0, #0x20, #0xffffffffffff8000 !# issue 1144 !# CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN, None 0x0: 0x00,0x00,0x02,0xb7 == tbnz x0, #0x20, #0x4000 !# issue 1144 !# CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN, None 0x0: 0x00,0x00,0x04,0xb7 == tbnz x0, #0x20, #0xffffffffffff8000 !# issue 826 !# CS_ARCH_ARM, CS_MODE_ARM, CS_OPT_DETAIL 0x0: 0x0b,0x00,0x00,0x0a == beq #0x34 ; op_count: 1 ; operands[0].type: IMM = 0x34 ; Code condition: 1 ; Registers read: pc ; Registers modified: pc ; Groups: branch_relative arm jump !# issue 1047 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_SYNTAX_ATT 0x0: 0x48,0x83,0xe4,0xf0 == andq $0xfffffffffffffff0, %rsp !# issue 959 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xa0,0x28,0x57,0x88,0x7c == mov al, byte ptr [0x7c885728] !# issue 950 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0x66,0xa3,0x94,0x90,0x04,0x08 == mov word ptr [0x8049094], ax ; Prefix:0x00 0x00 0x66 0x00 ; Opcode:0xa3 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x0 ; disp: 0x8049094 ; sib: 0x0 ; op_count: 2 ; operands[0].type: MEM ; operands[0].mem.disp: 0x8049094 ; operands[0].size: 2 ; operands[0].access: WRITE ; operands[1].type: REG = ax ; operands[1].size: 2 ; operands[1].access: READ ; Registers read: ax !# issue 938 !# CS_ARCH_MIPS, CS_MODE_MIPS64+CS_MODE_LITTLE_ENDIAN, None 0x0: 0x70,0x00,0xb2,0xff == sd $s2, 0x70($sp) !# issue 915 !# CS_ARCH_X86, CS_MODE_64, None 0x0: 0xf0,0x0f,0x1f,0x00 == lock nop dword ptr [rax] // !# issue 913 // !# CS_ARCH_ARM, CS_MODE_ARM, CS_OPT_DETAIL 0x0: 0x04,0x10,0x9d,0xe4 == pop {r1} ; op_count: 1 ; operands[0].type: REG = r1 ; operands[0].access: WRITE ; Write-back: True ; Registers read: sp ; Registers modified: sp r1 ; Groups: arm !# issue 884 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_SYNTAX_ATT 0x0: 0x64,0x48,0x03,0x04,0x25,0x00,0x00,0x00,0x00 == addq %fs:0, %rax !# issue 872 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xf2,0xeb,0x3e == bnd jmp 0x41 !# issue 861 !# CS_ARCH_ARM, CS_MODE_ARM, CS_OPT_DETAIL 0x0: 0x01,0x81,0xa0,0xfc == stc2 p1, c8, [r0], #4 ; op_count: 4 ; operands[0].type: P-IMM = 1 ; operands[1].type: C-IMM = 8 ; operands[2].type: MEM ; operands[2].mem.base: REG = r0 ; operands[2].access: READ ; operands[3].type: IMM = 0x4 ; Write-back: True ; Registers read: r0 ; Registers modified: r0 ; Groups: prev8 !# issue 852 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0x64,0xa3,0x00,0x00,0x00,0x00 == mov dword ptr fs:[0], eax ; Prefix:0x00 0x64 0x00 0x00 ; Opcode:0xa3 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x0 ; disp: 0x0 ; sib: 0x0 ; op_count: 2 ; operands[0].type: MEM ; operands[0].mem.segment: REG = fs ; operands[0].size: 4 ; operands[0].access: WRITE ; operands[1].type: REG = eax ; operands[1].size: 4 ; operands[1].access: READ ; Registers read: fs eax !# issue 825 !# CS_ARCH_ARM, CS_MODE_ARM, CS_OPT_DETAIL 0x0: 0x0e,0xf0,0xa0,0xe1 == mov pc, lr ; op_count: 2 ; operands[0].type: REG = pc ; operands[0].access: WRITE ; operands[1].type: REG = lr ; operands[1].access: READ ; Registers read: lr ; Registers modified: pc ; Groups: arm !# issue 813 !# CS_ARCH_ARM, CS_MODE_THUMB | CS_MODE_BIG_ENDIAN, None 0x0: 0xF6,0xC0,0x04,0x01 == movt r4, #0x801 !# issue 809 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_DETAIL 0x0: 0x0f,0x29,0x8d,0xf0,0xfd,0xff,0xff == movaps xmmword ptr [rbp - 0x210], xmm1 ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0x0f 0x29 0x00 0x00 ; rex: 0x0 ; addr_size: 8 ; modrm: 0x8d ; disp: 0xfffffffffffffdf0 ; sib: 0x0 ; op_count: 2 ; operands[0].type: MEM ; operands[0].mem.base: REG = rbp ; operands[0].mem.disp: 0xfffffffffffffdf0 ; operands[0].size: 16 ; operands[0].access: WRITE ; operands[1].type: REG = xmm1 ; operands[1].size: 16 ; operands[1].access: READ ; Registers read: rbp xmm1 ; Groups: sse1 !# issue 807 !# CS_ARCH_X86, CS_MODE_64, None 0x0: 0x4c,0x0f,0x00,0x80,0x16,0x76,0x8a,0xfe == sldt word ptr [rax - 0x17589ea] !# issue 806 !# CS_ARCH_X86, CS_MODE_64, None 0x0: 0x0f,0x35 == sysexit !# issue 805 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_SYNTAX_ATT 0x0: 0x48,0x4c,0x0f,0xb5,0x80,0x16,0x76,0x8a,0xfe == lgs -0x17589ea(%rax), %r8 !# issue 804 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_SYNTAX_ATT 0x0: 0x66,0x48,0xf3,0xd1,0xc0 == rolw $1, %ax !# issue 789 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_SYNTAX_ATT 0x0: 0x8e,0x1e == movw (%rsi), %ds !# issue 767 !# CS_ARCH_ARM, CS_MODE_THUMB, CS_OPT_DETAIL 0x0: 0xb1,0xe8,0xfc,0x07 == ldm.w r1!, {r2, r3, r4, r5, r6, r7, r8, sb, sl} ; op_count: 10 ; operands[0].type: REG = r1 ; operands[0].access: READ | WRITE ; operands[1].type: REG = r2 ; operands[1].access: WRITE ; operands[2].type: REG = r3 ; operands[2].access: WRITE ; operands[3].type: REG = r4 ; operands[3].access: WRITE ; operands[4].type: REG = r5 ; operands[4].access: WRITE ; operands[5].type: REG = r6 ; operands[5].access: WRITE ; operands[6].type: REG = r7 ; operands[6].access: WRITE ; operands[7].type: REG = r8 ; operands[7].access: WRITE ; operands[8].type: REG = sb ; operands[8].access: WRITE ; operands[9].type: REG = sl ; operands[9].access: WRITE ; Write-back: True ; Registers read: r1 ; Registers modified: r1 r2 r3 r4 r5 r6 r7 r8 sb sl ; Groups: thumb2 !# issue 760 !# CS_ARCH_ARM, CS_MODE_ARM, CS_OPT_DETAIL 0x0: 0x02,0x80,0xbd,0xe8 == pop {r1, pc} ; op_count: 2 ; operands[0].type: REG = r1 ; operands[0].access: WRITE ; operands[1].type: REG = pc ; operands[1].access: WRITE ; Registers read: sp ; Registers modified: sp r1 pc ; Groups: arm !# issue 750 !# CS_ARCH_ARM, CS_MODE_ARM, CS_OPT_DETAIL 0x0: 0x0e,0x00,0x20,0xe9 == stmdb r0!, {r1, r2, r3} ; op_count: 4 ; operands[0].type: REG = r0 ; operands[0].access: READ ; operands[1].type: REG = r1 ; operands[2].type: REG = r2 ; operands[3].type: REG = r3 ; Write-back: True ; Registers read: r0 ; Groups: arm !# issue 747 !# CS_ARCH_ARM, CS_MODE_ARM, CS_OPT_DETAIL 0x0: 0x0e,0x00,0xb0,0xe8 == ldm r0!, {r1, r2, r3} ; op_count: 4 ; operands[0].type: REG = r0 ; operands[0].access: READ | WRITE ; operands[1].type: REG = r1 ; operands[1].access: WRITE ; operands[2].type: REG = r2 ; operands[2].access: WRITE ; operands[3].type: REG = r3 ; operands[3].access: WRITE ; Write-back: True ; Registers read: r0 ; Registers modified: r0 r1 r2 r3 ; Groups: arm !# issue 747 !# CS_ARCH_ARM, CS_MODE_THUMB, CS_OPT_DETAIL 0x0: 0x0e,0xc8 == ldm r0!, {r1, r2, r3} ; op_count: 4 ; operands[0].type: REG = r0 ; operands[0].access: READ | WRITE ; operands[1].type: REG = r1 ; operands[1].access: WRITE ; operands[2].type: REG = r2 ; operands[2].access: WRITE ; operands[3].type: REG = r3 ; operands[3].access: WRITE ; Write-back: True ; Registers read: r0 ; Registers modified: r0 r1 r2 r3 ; Groups: thumb thumb1only !# issue 746 !# CS_ARCH_ARM, CS_MODE_ARM, CS_OPT_DETAIL 0x0: 0x89,0x00,0x2d,0xe9 == push {r0, r3, r7} ; op_count: 3 ; operands[0].type: REG = r0 ; operands[0].access: READ ; operands[1].type: REG = r3 ; operands[1].access: READ ; operands[2].type: REG = r7 ; operands[2].access: READ ; Registers read: sp r0 r3 r7 ; Registers modified: sp ; Groups: arm !# issue 744 !# CS_ARCH_ARM, CS_MODE_ARM, CS_OPT_DETAIL 0x0: 0x02,0x80,0xbd,0xe8 == pop {r1, pc} ; op_count: 2 ; operands[0].type: REG = r1 ; operands[0].access: WRITE ; operands[1].type: REG = pc ; operands[1].access: WRITE ; Registers read: sp ; Registers modified: sp r1 pc ; Groups: arm !# issue 741 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0x83,0xff,0xf7 == cmp edi, -9 !# issue 717 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_SYNTAX_ATT 0x0: 0x48,0x8b,0x04,0x25,0x00,0x00,0x00,0x00 == movq 0, %rax !# issue 711 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0xa3,0x44,0xb0,0x00,0x10 == mov dword ptr [0x1000b044], eax ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0xa3 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x0 ; disp: 0x1000b044 ; sib: 0x0 ; op_count: 2 ; operands[0].type: MEM ; operands[0].mem.disp: 0x1000b044 ; operands[0].size: 4 ; operands[0].access: WRITE ; operands[1].type: REG = eax ; operands[1].size: 4 ; operands[1].access: READ ; Registers read: eax !# issue 613 !# CS_ARCH_X86, CS_MODE_64, None 0x0: 0xd9,0x74,0x24,0xd8 == fnstenv [rsp - 0x28] !# issue 554 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xe7,0x84 == out 0x84, eax !# issue 554 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xe5,0x8c == in eax, 0x8c !# issue 545 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0x95 == xchg ebp, eax ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0x95 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x0 ; disp: 0x0 ; sib: 0x0 ; op_count: 2 ; operands[0].type: REG = ebp ; operands[0].size: 4 ; operands[0].access: READ | WRITE ; operands[1].type: REG = eax ; operands[1].size: 4 ; operands[1].access: READ | WRITE ; Registers read: ebp eax ; Registers modified: ebp eax ; Groups: not64bitmode !# issue 544 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xdf,0x30 == fbstp tbyte ptr [eax] !# issue 544 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xdf,0x20 == fbld tbyte ptr [eax] !# issue 541 !# CS_ARCH_X86, CS_MODE_64, None 0x0: 0x48,0xb8,0x00,0x00,0x00,0x00,0x80,0xf8,0xff,0xff == movabs rax, 0xfffff88000000000 !# issue 499 !# CS_ARCH_X86, CS_MODE_64, None 0x0: 0x48,0xb8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80 == movabs rax, 0x8000000000000000 !# issue 492 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xff,0x18 == call ptr [eax] !# issue 492 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xff,0x28 == jmp ptr [eax] !# issue 492 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0x0f,0xae,0x04,0x24 == fxsave [esp] !# issue 492 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0x0f,0xae,0x0c,0x24 == fxrstor [esp] !# issue 470 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0x0f,0x01,0x05,0xa0,0x90,0x04,0x08 == sgdt [0x80490a0] !# issue 470 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0x0f,0x01,0x0d,0xa7,0x90,0x04,0x08 == sidt [0x80490a7] !# issue 470 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0x0f,0x01,0x15,0xa0,0x90,0x04,0x08 == lgdt [0x80490a0] !# issue 470 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0x0f,0x01,0x1d,0xa7,0x90,0x04,0x08 == lidt [0x80490a7] !# issue 459 !# CS_ARCH_ARM, CS_MODE_ARM, CS_OPT_DETAIL 0x0: 0xd3,0x20,0x11,0xe1 == ldrsb r2, [r1, -r3] ; op_count: 2 ; operands[0].type: REG = r2 ; operands[0].access: WRITE ; operands[1].type: MEM ; operands[1].mem.base: REG = r1 ; operands[1].mem.index: REG = r3 ; operands[1].mem.scale: -1 ; Subtracted: True ; Registers read: r1 r3 ; Registers modified: r2 ; Groups: arm !# issue 456 !# CS_ARCH_X86, CS_MODE_16, None 0x0: 0xe8,0x35,0x64 == call 0x6438 !# issue 456 !# CS_ARCH_X86, CS_MODE_16, None 0x0: 0xe9,0x35,0x64 == jmp 0x6438 !# issue 456 !# CS_ARCH_X86, CS_MODE_16, None 0x0: 0x66,0xe9,0x35,0x64,0x93,0x53 == jmp 0x5393643b !# issue 456 !# CS_ARCH_X86, CS_MODE_16, None 0x0: 0x66,0xe8,0x35,0x64,0x93,0x53 == call 0x5393643b !# issue 456 !# CS_ARCH_X86, CS_MODE_16, None 0x0: 0x66,0xe9,0x35,0x64,0x93,0x53 == jmp 0x5393643b !# issue 456 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0x66,0xe8,0x35,0x64 == call 0x6439 !# issue 456 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xe9,0x35,0x64,0x93,0x53 == jmp 0x5393643a !# issue 456 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0x66,0xe9,0x35,0x64 == jmp 0x6439 !# issue 458 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0xA1,0x12,0x34,0x90,0x90 == mov eax, dword ptr [0x90903412] ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0xa1 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x0 ; disp: 0x90903412 ; sib: 0x0 ; op_count: 2 ; operands[0].type: REG = eax ; operands[0].size: 4 ; operands[0].access: WRITE ; operands[1].type: MEM ; operands[1].mem.disp: 0x90903412 ; operands[1].size: 4 ; operands[1].access: READ ; Registers modified: eax !# issue 454 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xf2,0x6c == repne insb byte ptr es:[edi], dx !# issue 454 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xf2,0x6d == repne insd dword ptr es:[edi], dx !# issue 454 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xf2,0x6e == repne outsb dx, byte ptr [esi] !# issue 454 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xf2,0x6f == repne outsd dx, dword ptr [esi] !# issue 454 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xf2,0xac == repne lodsb al, byte ptr [esi] !# issue 454 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xf2,0xad == repne lodsd eax, dword ptr [esi] !# issue 450 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0xff,0x2d,0x34,0x35,0x23,0x01 == jmp ptr [0x1233534] ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0xff 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x2d ; disp: 0x1233534 ; sib: 0x0 ; op_count: 1 ; operands[0].type: MEM ; operands[0].mem.disp: 0x1233534 ; operands[0].size: 6 ; Groups: jump !# issue 448 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0xea,0x12,0x34,0x56,0x78,0x9a,0xbc == ljmp 0xbc9a:0x78563412 ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0xea 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x0 ; disp: 0x0 ; sib: 0x0 ; imm_count: 2 ; imms[1]: 0xbc9a ; imms[2]: 0x78563412 ; op_count: 2 ; operands[0].type: IMM = 0xbc9a ; operands[0].size: 2 ; operands[1].type: IMM = 0x78563412 ; operands[1].size: 4 ; Groups: not64bitmode jump !# issue 426 !# CS_ARCH_SPARC, CS_MODE_BIG_ENDIAN, None 0x0: 0xbb,0x70,0x00,0x00 == popc %g0, %i5 !# issue 358 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0xe8,0xe3,0xf6,0xff,0xff == call 0xfffff6e8 ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0xe8 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x0 ; disp: 0x0 ; sib: 0x0 ; imm_count: 1 ; imms[1]: 0xfffff6e8 ; op_count: 1 ; operands[0].type: IMM = 0xfffff6e8 ; operands[0].size: 4 ; Registers read: esp eip ; Registers modified: esp ; Groups: call branch_relative not64bitmode !# issue 353 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0xe6,0xa2 == out 0xa2, al ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0xe6 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x0 ; disp: 0x0 ; sib: 0x0 ; imm_count: 1 ; imms[1]: 0xa2 ; op_count: 2 ; operands[0].type: IMM = 0xa2 ; operands[0].size: 1 ; operands[1].type: REG = al ; operands[1].size: 1 ; operands[1].access: READ ; Registers read: al !# issue 305 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0x34,0x8b == xor al, 0x8b !# issue 298 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xf3,0x90 == pause !# issue 298 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0x66,0xf3,0xf2,0x0f,0x59,0xff == mulsd xmm7, xmm7 // !# issue 298 // !# CS_ARCH_X86, CS_MODE_32, None // 0x0: 0xf2,0x66,0x0f,0x59,0xff == mulpd xmm7, xmm7 !# issue 294 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0xc1,0xe6,0x08 == shl esi, 8 ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0xc1 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0xe6 ; disp: 0x0 ; sib: 0x0 ; imm_count: 1 ; imms[1]: 0x8 ; op_count: 2 ; operands[0].type: REG = esi ; operands[0].size: 4 ; operands[0].access: READ | WRITE ; operands[1].type: IMM = 0x8 ; operands[1].size: 1 ; Registers read: esi ; Registers modified: eflags esi ; EFLAGS: MOD_CF MOD_SF MOD_ZF MOD_PF MOD_OF UNDEF_AF !# issue 285 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0x3c,0x12,0x80 == cmp al, 0x12 ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0x3c 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x0 ; disp: 0x0 ; sib: 0x0 ; imm_count: 1 ; imms[1]: 0x12 ; op_count: 2 ; operands[0].type: REG = al ; operands[0].size: 1 ; operands[0].access: READ ; operands[1].type: IMM = 0x12 ; operands[1].size: 1 ; Registers read: al ; Registers modified: eflags ; EFLAGS: MOD_AF MOD_CF MOD_SF MOD_ZF MOD_PF MOD_OF !# issue 265 !# CS_ARCH_ARM, CS_MODE_THUMB, CS_OPT_DETAIL 0x0: 0x52,0xf8,0x23,0x30 == ldr.w r3, [r2, r3, lsl #2] ; op_count: 2 ; operands[0].type: REG = r3 ; operands[0].access: WRITE ; operands[1].type: MEM ; operands[1].mem.base: REG = r2 ; operands[1].mem.index: REG = r3 ; operands[1].access: READ ; Shift: 2 = 2 ; Registers read: r2 r3 ; Registers modified: r3 ; Groups: thumb2 !# issue 264 !# CS_ARCH_ARM, CS_MODE_THUMB, None 0x0: 0x0c,0xbf == ite eq !# issue 264 !# CS_ARCH_ARM, CS_MODE_THUMB, None 0x0: 0x17,0x20 == movs r0, #0x17 !# issue 264 !# CS_ARCH_ARM, CS_MODE_THUMB, None 0x0: 0x4f,0xf0,0xff,0x30 == mov.w r0, #-1 !# issue 246 !# CS_ARCH_ARM, CS_MODE_THUMB, None 0x0: 0x52,0xf8,0x23,0xf0 == ldr.w pc, [r2, r3, lsl #2] !# issue 232 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0x8e,0x10 == mov ss, word ptr [eax] ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0x8e 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x10 ; disp: 0x0 ; sib: 0x0 ; op_count: 2 ; operands[0].type: REG = ss ; operands[0].size: 2 ; operands[0].access: WRITE ; operands[1].type: MEM ; operands[1].mem.base: REG = eax ; operands[1].size: 2 ; operands[1].access: READ ; Registers read: eax ; Registers modified: ss ; Groups: privilege !# issue 231 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0x66,0x6b,0xc0,0x02 == imul ax, ax, 2 ; Prefix:0x00 0x00 0x66 0x00 ; Opcode:0x6b 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0xc0 ; disp: 0x0 ; sib: 0x0 ; imm_count: 1 ; imms[1]: 0x2 ; op_count: 3 ; operands[0].type: REG = ax ; operands[0].size: 2 ; operands[0].access: WRITE ; operands[1].type: REG = ax ; operands[1].size: 2 ; operands[1].access: READ ; operands[2].type: IMM = 0x2 ; operands[2].size: 2 ; Registers read: ax ; Registers modified: eflags ax ; EFLAGS: MOD_CF MOD_SF MOD_OF UNDEF_ZF UNDEF_PF UNDEF_AF !# issue 230 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0xec == in al, dx ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0xec 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x0 ; disp: 0x0 ; sib: 0x0 ; op_count: 2 ; operands[0].type: REG = al ; operands[0].size: 1 ; operands[0].access: WRITE ; operands[1].type: REG = dx ; operands[1].size: 2 ; operands[1].access: READ ; Registers read: dx ; Registers modified: al !# issue 213 !# CS_ARCH_X86, CS_MODE_16, None 0x0: 0xea,0xaa,0xff,0x00,0xf0 == ljmp 0xf000:0xffaa !# issue 191 !# CS_ARCH_X86, CS_MODE_64, None 0x0: 0xc5,0xe8,0xc2,0x33,0x9b == vcmpps xmm6, xmm2, xmmword ptr [rbx], 0x9b !# issue 176 !# CS_ARCH_ARM, CS_MODE_ARM, None 0x0: 0xfd,0xff,0xff,0x1a == bne #0xfffffffc !# issue 151 !# CS_ARCH_X86, CS_MODE_64, None 0x0: 0x4d,0x8d,0x3d,0x02,0x00,0x00,0x00 == lea r15, [rip + 2] !# issue 151 !# CS_ARCH_X86, CS_MODE_64, None 0x0: 0xeb,0xb0 == jmp 0xffffffffffffffb2 !# issue 134 !# CS_ARCH_ARM, CS_MODE_BIG_ENDIAN, CS_OPT_DETAIL 0x0: 0xe7,0x92,0x11,0x80 == ldr r1, [r2, r0, lsl #3] ; op_count: 2 ; operands[0].type: REG = r1 ; operands[0].access: WRITE ; operands[1].type: MEM ; operands[1].mem.base: REG = r2 ; operands[1].mem.index: REG = r0 ; operands[1].access: READ ; Shift: 2 = 3 ; Registers read: r2 r0 ; Registers modified: r1 ; Groups: arm !# issue 133 !# CS_ARCH_ARM, CS_MODE_BIG_ENDIAN, CS_OPT_DETAIL 0x0: 0xed,0xdf,0x2b,0x1b == vldr d18, [pc, #0x6c] ; op_count: 2 ; operands[0].type: REG = d18 ; operands[0].access: WRITE ; operands[1].type: MEM ; operands[1].mem.base: REG = pc ; operands[1].mem.disp: 0x6c ; operands[1].access: READ ; Registers read: pc ; Registers modified: d18 ; Groups: vfp2 !# issue 132 !# CS_ARCH_ARM, CS_MODE_THUMB | CS_MODE_BIG_ENDIAN, CS_OPT_DETAIL 0x0: 0x49,0x19 == ldr r1, [pc, #0x64] ; op_count: 2 ; operands[0].type: REG = r1 ; operands[0].access: WRITE ; operands[1].type: MEM ; operands[1].mem.base: REG = pc ; operands[1].mem.disp: 0x64 ; operands[1].access: READ ; Registers read: pc ; Registers modified: r1 ; Groups: thumb thumb1only !# issue 130 !# CS_ARCH_ARM, CS_MODE_BIG_ENDIAN, CS_OPT_DETAIL 0x0: 0xe1,0xa0,0xf0,0x0e == mov pc, lr ; op_count: 2 ; operands[0].type: REG = pc ; operands[0].access: WRITE ; operands[1].type: REG = lr ; operands[1].access: READ ; Registers read: lr ; Registers modified: pc ; Groups: arm !# issue 85 !# CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN, None 0x0: 0xee,0x3f,0xbf,0x29 == stp w14, w15, [sp, #-8]! !# issue 82 !# CS_ARCH_X86, CS_MODE_64, None 0x0: 0xf2,0x66,0xaf == repne scasw ax, word ptr [rdi] !# issue 35 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xe8,0xc6,0x02,0x00,0x00 == call 0x2cb !# issue 8 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xff,0x8c,0xf9,0xff,0xff,0x9b,0xf9 == dec dword ptr [ecx + edi*8 - 0x6640001] !# issue 29 !# CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN, None 0x0: 0x00,0x00,0x00,0x4c == st4 {v0.16b, v1.16b, v2.16b, v3.16b}, [x0]
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text.Internal; using System.Text.Unicode; namespace System.Text.Encodings.Web { /// <summary> /// Represents a type used to do JavaScript encoding/escaping. /// </summary> public abstract class JavaScriptEncoder : TextEncoder { /// <summary> /// Returns a default built-in instance of <see cref="JavaScriptEncoder"/>. /// </summary> public static JavaScriptEncoder Default { get { return DefaultJavaScriptEncoder.Singleton; } } /// <summary> /// Creates a new instance of JavaScriptEncoder with provided settings. /// </summary> /// <param name="settings">Settings used to control how the created <see cref="JavaScriptEncoder"/> encodes, primarily which characters to encode.</param> /// <returns>A new instance of the <see cref="JavaScriptEncoder"/>.</returns> public static JavaScriptEncoder Create(TextEncoderSettings settings) { return new DefaultJavaScriptEncoder(settings); } /// <summary> /// Creates a new instance of JavaScriptEncoder specifying character to be encoded. /// </summary> /// <param name="allowedRanges">Set of characters that the endoder is allowed to not encode.</param> /// <returns>A new instance of the <see cref="JavaScriptEncoder"/>.</returns> /// <remarks>Some characters in <paramref name="allowedRanges"/> might still get encoded, i.e. this parameter is just telling the encoder what ranges it is allowed to not encode, not what characters it must not encode.</remarks> public static JavaScriptEncoder Create(params UnicodeRange[] allowedRanges) { return new DefaultJavaScriptEncoder(allowedRanges); } } internal sealed class DefaultJavaScriptEncoder : JavaScriptEncoder { private AllowedCharactersBitmap _allowedCharacters; internal readonly static DefaultJavaScriptEncoder Singleton = new DefaultJavaScriptEncoder(new TextEncoderSettings(UnicodeRanges.BasicLatin)); public DefaultJavaScriptEncoder(TextEncoderSettings filter) { if (filter == null) { throw new ArgumentNullException("filter"); } _allowedCharacters = filter.GetAllowedCharacters(); // Forbid codepoints which aren't mapped to characters or which are otherwise always disallowed // (includes categories Cc, Cs, Co, Cn, Zs [except U+0020 SPACE], Zl, Zp) _allowedCharacters.ForbidUndefinedCharacters(); // Forbid characters that are special in HTML. // Even though this is a not HTML encoder, // it's unfortunately common for developers to // forget to HTML-encode a string once it has been JS-encoded, // so this offers extra protection. DefaultHtmlEncoder.ForbidHtmlCharacters(_allowedCharacters); _allowedCharacters.ForbidCharacter('\\'); _allowedCharacters.ForbidCharacter('/'); } public DefaultJavaScriptEncoder(params UnicodeRange[] allowedRanges) : this(new TextEncoderSettings(allowedRanges)) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool WillEncode(int unicodeScalar) { if (UnicodeHelpers.IsSupplementaryCodePoint(unicodeScalar)) return true; return !_allowedCharacters.IsUnicodeScalarAllowed(unicodeScalar); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe override int FindFirstCharacterToEncode(char* text, int textLength) { if (text == null) { throw new ArgumentNullException("text"); } return _allowedCharacters.FindFirstCharacterToEncode(text, textLength); } // The worst case encoding is 6 output chars per input char: [input] U+FFFF -> [output] "\uFFFF" // We don't need to worry about astral code points since they're represented as encoded // surrogate pairs in the output. public override int MaxOutputCharactersPerInputCharacter { get { return 6; } // "\uFFFF" is the longest encoded form } static readonly char[] s_b = new char[] { '\\', 'b' }; static readonly char[] s_t = new char[] { '\\', 't' }; static readonly char[] s_n = new char[] { '\\', 'n' }; static readonly char[] s_f = new char[] { '\\', 'f' }; static readonly char[] s_r = new char[] { '\\', 'r' }; static readonly char[] s_forward = new char[] { '\\', '/' }; static readonly char[] s_back = new char[] { '\\', '\\' }; // Writes a scalar value as a JavaScript-escaped character (or sequence of characters). // See ECMA-262, Sec. 7.8.4, and ECMA-404, Sec. 9 // http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4 // http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf public unsafe override bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten) { if (buffer == null) { throw new ArgumentNullException("buffer"); } // ECMA-262 allows encoding U+000B as "\v", but ECMA-404 does not. // Both ECMA-262 and ECMA-404 allow encoding U+002F SOLIDUS as "\/". // (In ECMA-262 this character is a NonEscape character.) // HTML-specific characters (including apostrophe and quotes) will // be written out as numeric entities for defense-in-depth. // See UnicodeEncoderBase ctor comments for more info. if (!WillEncode(unicodeScalar)) { return TryWriteScalarAsChar(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten); } char[] toCopy = null; switch (unicodeScalar) { case '\b': toCopy = s_b; break; case '\t': toCopy = s_t; break; case '\n': toCopy = s_n; break; case '\f': toCopy = s_f; break; case '\r': toCopy = s_r; break; case '/': toCopy = s_forward; break; case '\\': toCopy = s_back; break; default: return TryWriteEncodedScalarAsNumericEntity(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten); } return TryCopyCharacters(toCopy, buffer, bufferLength, out numberOfCharactersWritten); } private unsafe static bool TryWriteEncodedScalarAsNumericEntity(int unicodeScalar, char* buffer, int length, out int numberOfCharactersWritten) { Debug.Assert(buffer != null && length >= 0); if (UnicodeHelpers.IsSupplementaryCodePoint(unicodeScalar)) { // Convert this back to UTF-16 and write out both characters. char leadingSurrogate, trailingSurrogate; UnicodeHelpers.GetUtf16SurrogatePairFromAstralScalarValue(unicodeScalar, out leadingSurrogate, out trailingSurrogate); int leadingSurrogateCharactersWritten; if (TryWriteEncodedSingleCharacter(leadingSurrogate, buffer, length, out leadingSurrogateCharactersWritten) && TryWriteEncodedSingleCharacter(trailingSurrogate, buffer + leadingSurrogateCharactersWritten, length - leadingSurrogateCharactersWritten, out numberOfCharactersWritten) ) { numberOfCharactersWritten += leadingSurrogateCharactersWritten; return true; } else { numberOfCharactersWritten = 0; return false; } } else { // This is only a single character. return TryWriteEncodedSingleCharacter(unicodeScalar, buffer, length, out numberOfCharactersWritten); } } // Writes an encoded scalar value (in the BMP) as a JavaScript-escaped character. private unsafe static bool TryWriteEncodedSingleCharacter(int unicodeScalar, char* buffer, int length, out int numberOfCharactersWritten) { Debug.Assert(buffer != null && length >= 0); Debug.Assert(!UnicodeHelpers.IsSupplementaryCodePoint(unicodeScalar), "The incoming value should've been in the BMP."); if (length < 6) { numberOfCharactersWritten = 0; return false; } // Encode this as 6 chars "\uFFFF". *buffer = '\\'; buffer++; *buffer = 'u'; buffer++; *buffer = HexUtil.Int32LsbToHexDigit(unicodeScalar >> 12); buffer++; *buffer = HexUtil.Int32LsbToHexDigit((int)((unicodeScalar >> 8) & 0xFU)); buffer++; *buffer = HexUtil.Int32LsbToHexDigit((int)((unicodeScalar >> 4) & 0xFU)); buffer++; *buffer = HexUtil.Int32LsbToHexDigit((int)(unicodeScalar & 0xFU)); buffer++; numberOfCharactersWritten = 6; return true; } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <peter@majorsilence.com> This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Collections; using System.IO; using System.Reflection; using RdlEngine.Resources; using fyiReporting.RDL; namespace fyiReporting.RDL { /// <summary> /// Obtain the runtime value of a Report parameter /// </summary> [Serializable] internal class FunctionReportParameter : IExpr { protected ReportParameter p; ReportParameterMethodEnum _type; IExpr _arg; // when MultiValue parameter; methods may need arguments /// <summary> /// obtain value of ReportParameter /// </summary> public FunctionReportParameter(ReportParameter parm) { p=parm; _type = ReportParameterMethodEnum.Value; _arg = null; } internal ReportParameterMethodEnum ParameterMethod { get { return _type; } set { _type = value; } } internal void SetParameterMethod(string pm, IExpr[] args) { if (!this.p.MultiValue) throw new ArgumentException(string.Format("{0} must be a MultiValue parameter to accept methods", this.p.Name.Nm)); if (pm == null) { _type = ReportParameterMethodEnum.Index; } else switch (pm) { case "Contains": _type = ReportParameterMethodEnum.Contains; break; case "BinarySearch": _type = ReportParameterMethodEnum.BinarySearch; break; case "Count": _type = ReportParameterMethodEnum.Count; if (args != null) throw new ArgumentException("Count does not have any arguments."); break; case "IndexOf": _type = ReportParameterMethodEnum.IndexOf; break; case "LastIndexOf": _type = ReportParameterMethodEnum.LastIndexOf; break; case "Value": _type = ReportParameterMethodEnum.Value; break; default: throw new ArgumentException(string.Format("{0} is an unknown array method.", pm)); } if (_type != ReportParameterMethodEnum.Count) { if (args == null || args.Length != 1) throw new ArgumentException(string.Format("{0} must have exactly one argument.", pm)); _arg = args[0]; } return; } public virtual TypeCode GetTypeCode() { switch (_type) { case ReportParameterMethodEnum.Contains: return TypeCode.Boolean; case ReportParameterMethodEnum.BinarySearch: case ReportParameterMethodEnum.Count: case ReportParameterMethodEnum.IndexOf: case ReportParameterMethodEnum.LastIndexOf: return TypeCode.Int32; case ReportParameterMethodEnum.Value: return p.MultiValue ? TypeCode.Object : p.dt; // MultiValue type is really ArrayList case ReportParameterMethodEnum.Index: default: return p.dt; } } public virtual bool IsConstant() { return false; } public virtual IExpr ConstantOptimization() { // not a constant expression return this; } // Evaluate is for interpretation (and is relatively slow) public virtual object Evaluate(Report rpt, Row row) { return this.p.MultiValue? EvaluateMV(rpt, row): p.GetRuntimeValue(rpt); } private object EvaluateMV(Report rpt, Row row) { ArrayList ar = p.GetRuntimeValues(rpt); object va = this._arg == null ? null : _arg.Evaluate(rpt, row); switch(_type) { case ReportParameterMethodEnum.Value: return ar; case ReportParameterMethodEnum.Contains: return ar.Contains(va); case ReportParameterMethodEnum.BinarySearch: return ar.BinarySearch(va); case ReportParameterMethodEnum.Count: return ar.Count; case ReportParameterMethodEnum.IndexOf: return ar.IndexOf(va); case ReportParameterMethodEnum.LastIndexOf: return ar.LastIndexOf(va); case ReportParameterMethodEnum.Index: int i = Convert.ToInt32(va); return ar[i]; default: throw new Exception(Strings.FunctionReportParameter_Error_UnknownReporParameterMethod); } } public virtual double EvaluateDouble(Report rpt, Row row) { object rtv = Evaluate(rpt, row); if (rtv == null) return Double.NaN; switch (this.GetTypeCode()) { case TypeCode.Double: return ((double) rtv); case TypeCode.Object: return Double.NaN; case TypeCode.Int32: return (double) ((int) rtv); case TypeCode.Boolean: return Convert.ToDouble((bool) rtv); case TypeCode.String: return Convert.ToDouble((string) rtv); case TypeCode.DateTime: return Convert.ToDouble((DateTime) rtv); default: return Double.NaN; } } public virtual decimal EvaluateDecimal(Report rpt, Row row) { object rtv = Evaluate(rpt, row); if (rtv == null) return Decimal.MinValue; switch (this.GetTypeCode()) { case TypeCode.Double: return Convert.ToDecimal((double) rtv); case TypeCode.Object: return Decimal.MinValue; case TypeCode.Int32: return Convert.ToDecimal((int) rtv); case TypeCode.Boolean: return Convert.ToDecimal((bool) rtv); case TypeCode.String: return Convert.ToDecimal((string) rtv); case TypeCode.DateTime: return Convert.ToDecimal((DateTime) rtv); default: return Decimal.MinValue; } } public virtual int EvaluateInt32(Report rpt, Row row) { object rtv = Evaluate(rpt, row); if (rtv == null) return int.MinValue; switch (this.GetTypeCode()) { case TypeCode.Double: return Convert.ToInt32((double)rtv); case TypeCode.Decimal: return Convert.ToInt32((decimal)rtv); case TypeCode.Object: return int.MinValue; case TypeCode.Int32: return (int)rtv; case TypeCode.Boolean: return Convert.ToInt32((bool)rtv); case TypeCode.String: return Convert.ToInt32((string)rtv); case TypeCode.DateTime: return Convert.ToInt32((DateTime)rtv); default: return int.MinValue; } } public virtual string EvaluateString(Report rpt, Row row) { object rtv = this.p.MultiValue ? EvaluateMV(rpt, row) : p.GetRuntimeValue(rpt); // object rtv = Evaluate(rpt, row); if (rtv == null) return null; return rtv.ToString(); } public virtual DateTime EvaluateDateTime(Report rpt, Row row) { object rtv = Evaluate(rpt, row); if (rtv == null) return DateTime.MinValue; switch (this.GetTypeCode()) { case TypeCode.Double: return Convert.ToDateTime((double) rtv); case TypeCode.Object: return DateTime.MinValue; case TypeCode.Int32: return Convert.ToDateTime((int) rtv); case TypeCode.Boolean: return Convert.ToDateTime((bool) rtv); case TypeCode.String: return Convert.ToDateTime((string) rtv); case TypeCode.DateTime: return (DateTime) rtv; default: return DateTime.MinValue; } } public virtual bool EvaluateBoolean(Report rpt, Row row) { object rtv = Evaluate(rpt, row); if (rtv == null) return false; switch (this.GetTypeCode()) { case TypeCode.Double: return Convert.ToBoolean((double) rtv); case TypeCode.Object: return false; case TypeCode.Int32: return Convert.ToBoolean((int) rtv); case TypeCode.Boolean: return (bool) rtv; case TypeCode.String: return Convert.ToBoolean((string) rtv); case TypeCode.DateTime: return Convert.ToBoolean((DateTime) rtv); default: return false; } } } public enum ReportParameterMethodEnum { Value, Contains, BinarySearch, Count, IndexOf, LastIndexOf, Index } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: Convenient wrapper for an array, an offset, and ** a count. Ideally used in streams & collections. ** Net Classes will consume an array of these. ** ** ===========================================================*/ using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace System { // Note: users should make sure they copy the fields out of an ArraySegment onto their stack // then validate that the fields describe valid bounds within the array. This must be done // because assignments to value types are not atomic, and also because one thread reading // three fields from an ArraySegment may not see the same ArraySegment from one call to another // (ie, users could assign a new value to the old location). [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct ArraySegment<T> : IList<T>, IReadOnlyList<T> { // Do not replace the array allocation with Array.Empty. We don't want to have the overhead of // instantiating another generic type in addition to ArraySegment<T> for new type parameters. public static ArraySegment<T> Empty { get; } = new ArraySegment<T>(new T[0]); private readonly T[] _array; // Do not rename (binary serialization) private readonly int _offset; // Do not rename (binary serialization) private readonly int _count; // Do not rename (binary serialization) public ArraySegment(T[] array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); _array = array; _offset = 0; _count = array.Length; } public ArraySegment(T[] array, int offset, int count) { // Validate arguments, check is minimal instructions with reduced branching for inlinable fast-path // Negative values discovered though conversion to high values when converted to unsigned // Failure should be rare and location determination and message is delegated to failure functions if (array == null || (uint)offset > (uint)array.Length || (uint)count > (uint)(array.Length - offset)) ThrowHelper.ThrowArraySegmentCtorValidationFailedExceptions(array, offset, count); _array = array; _offset = offset; _count = count; } public T[] Array => _array; public int Offset => _offset; public int Count => _count; public T this[int index] { get { if ((uint)index >= (uint)_count) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } return _array[_offset + index]; } set { if ((uint)index >= (uint)_count) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } _array[_offset + index] = value; } } public Enumerator GetEnumerator() { ThrowInvalidOperationIfDefault(); return new Enumerator(this); } public override int GetHashCode() { if (_array == null) { return 0; } int hash = 5381; hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _offset); hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _count); // The array hash is expected to be an evenly-distributed mixture of bits, // so rather than adding the cost of another rotation we just xor it. hash ^= _array.GetHashCode(); return hash; } public void CopyTo(T[] destination) => CopyTo(destination, 0); public void CopyTo(T[] destination, int destinationIndex) { ThrowInvalidOperationIfDefault(); System.Array.Copy(_array, _offset, destination, destinationIndex, _count); } public void CopyTo(ArraySegment<T> destination) { ThrowInvalidOperationIfDefault(); destination.ThrowInvalidOperationIfDefault(); if (_count > destination._count) { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } System.Array.Copy(_array, _offset, destination._array, destination._offset, _count); } public override bool Equals(Object obj) { if (obj is ArraySegment<T>) return Equals((ArraySegment<T>)obj); else return false; } public bool Equals(ArraySegment<T> obj) { return obj._array == _array && obj._offset == _offset && obj._count == _count; } public ArraySegment<T> Slice(int index) { ThrowInvalidOperationIfDefault(); if ((uint)index > (uint)_count) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } return new ArraySegment<T>(_array, _offset + index, _count - index); } public ArraySegment<T> Slice(int index, int count) { ThrowInvalidOperationIfDefault(); if ((uint)index > (uint)_count || (uint)count > (uint)(_count - index)) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } return new ArraySegment<T>(_array, _offset + index, count); } public T[] ToArray() { ThrowInvalidOperationIfDefault(); if (_count == 0) { return Empty._array; } var array = new T[_count]; System.Array.Copy(_array, _offset, array, 0, _count); return array; } public static bool operator ==(ArraySegment<T> a, ArraySegment<T> b) { return a.Equals(b); } public static bool operator !=(ArraySegment<T> a, ArraySegment<T> b) { return !(a == b); } public static implicit operator ArraySegment<T>(T[] array) => new ArraySegment<T>(array); #region IList<T> T IList<T>.this[int index] { get { ThrowInvalidOperationIfDefault(); if (index < 0 || index >= _count) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); return _array[_offset + index]; } set { ThrowInvalidOperationIfDefault(); if (index < 0 || index >= _count) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); _array[_offset + index] = value; } } int IList<T>.IndexOf(T item) { ThrowInvalidOperationIfDefault(); int index = System.Array.IndexOf<T>(_array, item, _offset, _count); Debug.Assert(index == -1 || (index >= _offset && index < _offset + _count)); return index >= 0 ? index - _offset : -1; } void IList<T>.Insert(int index, T item) { ThrowHelper.ThrowNotSupportedException(); } void IList<T>.RemoveAt(int index) { ThrowHelper.ThrowNotSupportedException(); } #endregion #region IReadOnlyList<T> T IReadOnlyList<T>.this[int index] { get { ThrowInvalidOperationIfDefault(); if (index < 0 || index >= _count) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); return _array[_offset + index]; } } #endregion IReadOnlyList<T> #region ICollection<T> bool ICollection<T>.IsReadOnly { get { // the indexer setter does not throw an exception although IsReadOnly is true. // This is to match the behavior of arrays. return true; } } void ICollection<T>.Add(T item) { ThrowHelper.ThrowNotSupportedException(); } void ICollection<T>.Clear() { ThrowHelper.ThrowNotSupportedException(); } bool ICollection<T>.Contains(T item) { ThrowInvalidOperationIfDefault(); int index = System.Array.IndexOf<T>(_array, item, _offset, _count); Debug.Assert(index == -1 || (index >= _offset && index < _offset + _count)); return index >= 0; } bool ICollection<T>.Remove(T item) { ThrowHelper.ThrowNotSupportedException(); return default(bool); } #endregion #region IEnumerable<T> IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator(); #endregion #region IEnumerable IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion private void ThrowInvalidOperationIfDefault() { if (_array == null) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray); } } public struct Enumerator : IEnumerator<T> { private readonly T[] _array; private readonly int _start; private readonly int _end; // cache Offset + Count, since it's a little slow private int _current; internal Enumerator(ArraySegment<T> arraySegment) { Debug.Assert(arraySegment.Array != null); Debug.Assert(arraySegment.Offset >= 0); Debug.Assert(arraySegment.Count >= 0); Debug.Assert(arraySegment.Offset + arraySegment.Count <= arraySegment.Array.Length); _array = arraySegment.Array; _start = arraySegment.Offset; _end = arraySegment.Offset + arraySegment.Count; _current = arraySegment.Offset - 1; } public bool MoveNext() { if (_current < _end) { _current++; return (_current < _end); } return false; } public T Current { get { if (_current < _start) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted(); if (_current >= _end) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded(); return _array[_current]; } } object IEnumerator.Current => Current; void IEnumerator.Reset() { _current = _start - 1; } public void Dispose() { } } } }
using System; using System.Collections.Generic; using System.IO; using Lucene.Net.Support; using NUnit.Framework; using Lucene.Net.Attributes; namespace Lucene.Net.Util { /* * 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> /// Tests for on-disk merge sorting. /// </summary> [TestFixture] public class TestOfflineSorter : LuceneTestCase { private DirectoryInfo TempDir; [SetUp] public override void SetUp() { base.SetUp(); TempDir = CreateTempDir("mergesort"); DeleteTestFiles(); TempDir.Create(); } [TearDown] public override void TearDown() { DeleteTestFiles(); base.TearDown(); } private void DeleteTestFiles() { if (TempDir != null) { if (Directory.Exists(TempDir.FullName)) { foreach (var file in TempDir.GetFiles()) { file.Delete(); } TempDir.Delete(); } } } [Test] public virtual void TestEmpty() { CheckSort(new OfflineSorter(), new byte[][] { }); } [Test] public virtual void TestSingleLine() { #pragma warning disable 612, 618 CheckSort(new OfflineSorter(), new byte[][] { "Single line only.".GetBytes(IOUtils.CHARSET_UTF_8) }); #pragma warning restore 612, 618 } [Test, LongRunningTest] public virtual void TestIntermediateMerges() { // Sort 20 mb worth of data with 1mb buffer, binary merging. OfflineSorter.SortInfo info = CheckSort(new OfflineSorter(OfflineSorter.DEFAULT_COMPARER, OfflineSorter.BufferSize.Megabytes(1), OfflineSorter.DefaultTempDir(), 2), GenerateRandom((int)OfflineSorter.MB * 20)); Assert.IsTrue(info.MergeRounds > 10); } [Test, LongRunningTest] public virtual void TestSmallRandom() { // Sort 20 mb worth of data with 1mb buffer. OfflineSorter.SortInfo sortInfo = CheckSort(new OfflineSorter(OfflineSorter.DEFAULT_COMPARER, OfflineSorter.BufferSize.Megabytes(1), OfflineSorter.DefaultTempDir(), OfflineSorter.MAX_TEMPFILES), GenerateRandom((int)OfflineSorter.MB * 20)); Assert.AreEqual(1, sortInfo.MergeRounds); } [Test, LongRunningTest] public virtual void TestLargerRandom() { // Sort 100MB worth of data with 15mb buffer. CheckSort(new OfflineSorter(OfflineSorter.DEFAULT_COMPARER, OfflineSorter.BufferSize.Megabytes(16), OfflineSorter.DefaultTempDir(), OfflineSorter.MAX_TEMPFILES), GenerateRandom((int)OfflineSorter.MB * 100)); } private byte[][] GenerateRandom(int howMuchData) { List<byte[]> data = new List<byte[]>(); while (howMuchData > 0) { byte[] current = new byte[Random().Next(256)]; Random().NextBytes(current); data.Add(current); howMuchData -= current.Length; } byte[][] bytes = data.ToArray(); return bytes; } internal static readonly IComparer<byte[]> unsignedByteOrderComparer = new ComparerAnonymousInnerClassHelper(); private class ComparerAnonymousInnerClassHelper : IComparer<byte[]> { public ComparerAnonymousInnerClassHelper() { } public virtual int Compare(byte[] left, byte[] right) { int max = Math.Min(left.Length, right.Length); for (int i = 0, j = 0; i < max; i++, j++) { int diff = (left[i] & 0xff) - (right[j] & 0xff); if (diff != 0) { return diff; } } return left.Length - right.Length; } } /// <summary> /// Check sorting data on an instance of <seealso cref="OfflineSorter"/>. /// </summary> private OfflineSorter.SortInfo CheckSort(OfflineSorter sort, byte[][] data) { FileInfo unsorted = WriteAll("unsorted", data); Array.Sort(data, unsignedByteOrderComparer); FileInfo golden = WriteAll("golden", data); FileInfo sorted = new FileInfo(Path.Combine(TempDir.FullName, "sorted")); OfflineSorter.SortInfo sortInfo = sort.Sort(unsorted, sorted); //System.out.println("Input size [MB]: " + unsorted.Length() / (1024 * 1024)); //System.out.println(sortInfo); AssertFilesIdentical(golden, sorted); return sortInfo; } /// <summary> /// Make sure two files are byte-byte identical. /// </summary> private void AssertFilesIdentical(FileInfo golden, FileInfo sorted) { Assert.AreEqual(golden.Length, sorted.Length); byte[] buf1 = new byte[64 * 1024]; byte[] buf2 = new byte[64 * 1024]; int len; //DataInputStream is1 = new DataInputStream(new FileInputStream(golden)); //DataInputStream is2 = new DataInputStream(new FileInputStream(sorted)); using (Stream is1 = golden.Open(FileMode.Open, FileAccess.Read, FileShare.Delete)) { using (Stream is2 = sorted.Open(FileMode.Open, FileAccess.Read, FileShare.Delete)) { while ((len = is1.Read(buf1, 0, buf1.Length)) > 0) { is2.Read(buf2, 0, len); for (int i = 0; i < len; i++) { Assert.AreEqual(buf1[i], buf2[i]); } } //IOUtils.Close(is1, is2); } } } private FileInfo WriteAll(string name, byte[][] data) { FileInfo file = new FileInfo(Path.Combine(TempDir.FullName, name)); using (file.Create()) { } OfflineSorter.ByteSequencesWriter w = new OfflineSorter.ByteSequencesWriter(file); foreach (byte[] datum in data) { w.Write(datum); } w.Dispose(); return file; } [Test] public virtual void TestRamBuffer() { int numIters = AtLeast(10000); for (int i = 0; i < numIters; i++) { OfflineSorter.BufferSize.Megabytes(1 + Random().Next(2047)); } OfflineSorter.BufferSize.Megabytes(2047); OfflineSorter.BufferSize.Megabytes(1); try { OfflineSorter.BufferSize.Megabytes(2048); Assert.Fail("max mb is 2047"); } #pragma warning disable 168 catch (System.ArgumentException e) #pragma warning restore 168 { } try { OfflineSorter.BufferSize.Megabytes(0); Assert.Fail("min mb is 0.5"); } #pragma warning disable 168 catch (System.ArgumentException e) #pragma warning restore 168 { } try { OfflineSorter.BufferSize.Megabytes(-1); Assert.Fail("min mb is 0.5"); } #pragma warning disable 168 catch (System.ArgumentException e) #pragma warning restore 168 { } } } }
/* * Copyright 2012-2016 The Pkcs11Interop Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <jimrich@jimrich.sk> */ using System; using System.IO; using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.LowLevelAPI80; using Net.Pkcs11Interop.LowLevelAPI80.MechanismParams; using NUnit.Framework; namespace Net.Pkcs11Interop.Tests.LowLevelAPI80 { /// <summary> /// C_EncryptInit, C_Encrypt, C_EncryptUpdate, C_EncryptFinish, C_DecryptInit, C_Decrypt, C_DecryptUpdate and C_DecryptFinish tests. /// </summary> [TestFixture()] public class _20_EncryptAndDecryptTest { /// <summary> /// C_EncryptInit, C_Encrypt, C_DecryptInit and C_Decrypt test. /// </summary> [Test()] public void _01_EncryptAndDecryptSinglePartTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs80); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present ulong slotId = Helpers.GetUsableSlot(pkcs11); ulong session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Login as normal user rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt64(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate symetric key ulong keyId = CK.CK_INVALID_HANDLE; rv = Helpers.GenerateKey(pkcs11, session, ref keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate random initialization vector byte[] iv = new byte[8]; rv = pkcs11.C_GenerateRandom(session, iv, Convert.ToUInt64(iv.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify encryption mechanism with initialization vector as parameter. // Note that CkmUtils.CreateMechanism() automaticaly copies iv into newly allocated unmanaged memory. CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_CBC, iv); // Initialize encryption operation rv = pkcs11.C_EncryptInit(session, ref mechanism, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password"); // Get length of encrypted data in first call ulong encryptedDataLen = 0; rv = pkcs11.C_Encrypt(session, sourceData, Convert.ToUInt64(sourceData.Length), null, ref encryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(encryptedDataLen > 0); // Allocate array for encrypted data byte[] encryptedData = new byte[encryptedDataLen]; // Get encrypted data in second call rv = pkcs11.C_Encrypt(session, sourceData, Convert.ToUInt64(sourceData.Length), encryptedData, ref encryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with encrypted data // Initialize decryption operation rv = pkcs11.C_DecryptInit(session, ref mechanism, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Get length of decrypted data in first call ulong decryptedDataLen = 0; rv = pkcs11.C_Decrypt(session, encryptedData, Convert.ToUInt64(encryptedData.Length), null, ref decryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(decryptedDataLen > 0); // Allocate array for decrypted data byte[] decryptedData = new byte[decryptedDataLen]; // Get decrypted data in second call rv = pkcs11.C_Decrypt(session, encryptedData, Convert.ToUInt64(encryptedData.Length), decryptedData, ref decryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with decrypted data Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData)); // In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter (iv in this case) UnmanagedMemory.Free(ref mechanism.Parameter); mechanism.ParameterLen = 0; rv = pkcs11.C_DestroyObject(session, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Logout(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } /// <summary> /// C_EncryptInit, C_EncryptUpdate, C_EncryptFinish, C_DecryptInit, C_DecryptUpdate and C_DecryptFinish test. /// </summary> [Test()] public void _02_EncryptAndDecryptMultiPartTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs80); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present ulong slotId = Helpers.GetUsableSlot(pkcs11); ulong session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Login as normal user rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt64(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate symetric key ulong keyId = CK.CK_INVALID_HANDLE; rv = Helpers.GenerateKey(pkcs11, session, ref keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate random initialization vector byte[] iv = new byte[8]; rv = pkcs11.C_GenerateRandom(session, iv, Convert.ToUInt64(iv.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify encryption mechanism with initialization vector as parameter. // Note that CkmUtils.CreateMechanism() automaticaly copies iv into newly allocated unmanaged memory. CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_CBC, iv); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password"); byte[] encryptedData = null; byte[] decryptedData = null; // Multipart encryption functions C_EncryptUpdate and C_EncryptFinal can be used i.e. for encryption of streamed data using (MemoryStream inputStream = new MemoryStream(sourceData), outputStream = new MemoryStream()) { // Initialize encryption operation rv = pkcs11.C_EncryptInit(session, ref mechanism, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Prepare buffer for source data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] part = new byte[8]; // Prepare buffer for encrypted data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] encryptedPart = new byte[8]; ulong encryptedPartLen = Convert.ToUInt64(encryptedPart.Length); // Read input stream with source data int bytesRead = 0; while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0) { // Encrypt each individual source data part encryptedPartLen = Convert.ToUInt64(encryptedPart.Length); rv = pkcs11.C_EncryptUpdate(session, part, Convert.ToUInt64(bytesRead), encryptedPart, ref encryptedPartLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Append encrypted data part to the output stream outputStream.Write(encryptedPart, 0, Convert.ToInt32(encryptedPartLen)); } // Get the length of last encrypted data part in first call byte[] lastEncryptedPart = null; ulong lastEncryptedPartLen = 0; rv = pkcs11.C_EncryptFinal(session, null, ref lastEncryptedPartLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Allocate array for the last encrypted data part lastEncryptedPart = new byte[lastEncryptedPartLen]; // Get the last encrypted data part in second call rv = pkcs11.C_EncryptFinal(session, lastEncryptedPart, ref lastEncryptedPartLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Append the last encrypted data part to the output stream outputStream.Write(lastEncryptedPart, 0, Convert.ToInt32(lastEncryptedPartLen)); // Read whole output stream to the byte array so we can compare results more easily encryptedData = outputStream.ToArray(); } // Do something interesting with encrypted data // Multipart decryption functions C_DecryptUpdate and C_DecryptFinal can be used i.e. for decryption of streamed data using (MemoryStream inputStream = new MemoryStream(encryptedData), outputStream = new MemoryStream()) { // Initialize decryption operation rv = pkcs11.C_DecryptInit(session, ref mechanism, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Prepare buffer for encrypted data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] encryptedPart = new byte[8]; // Prepare buffer for decrypted data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] part = new byte[8]; ulong partLen = Convert.ToUInt64(part.Length); // Read input stream with encrypted data int bytesRead = 0; while ((bytesRead = inputStream.Read(encryptedPart, 0, encryptedPart.Length)) > 0) { // Decrypt each individual encrypted data part partLen = Convert.ToUInt64(part.Length); rv = pkcs11.C_DecryptUpdate(session, encryptedPart, Convert.ToUInt64(bytesRead), part, ref partLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Append decrypted data part to the output stream outputStream.Write(part, 0, Convert.ToInt32(partLen)); } // Get the length of last decrypted data part in first call byte[] lastPart = null; ulong lastPartLen = 0; rv = pkcs11.C_DecryptFinal(session, null, ref lastPartLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Allocate array for the last decrypted data part lastPart = new byte[lastPartLen]; // Get the last decrypted data part in second call rv = pkcs11.C_DecryptFinal(session, lastPart, ref lastPartLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Append the last decrypted data part to the output stream outputStream.Write(lastPart, 0, Convert.ToInt32(lastPartLen)); // Read whole output stream to the byte array so we can compare results more easily decryptedData = outputStream.ToArray(); } // Do something interesting with decrypted data Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData)); // In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter (iv in this case) UnmanagedMemory.Free(ref mechanism.Parameter); mechanism.ParameterLen = 0; rv = pkcs11.C_DestroyObject(session, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Logout(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } /// <summary> /// C_EncryptInit, C_Encrypt, C_DecryptInit and C_Decrypt test with CKM_RSA_PKCS_OAEP mechanism. /// </summary> [Test()] public void _03_EncryptAndDecryptSinglePartOaepTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs80); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present ulong slotId = Helpers.GetUsableSlot(pkcs11); ulong session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Login as normal user rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt64(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate asymetric key pair ulong pubKeyId = CK.CK_INVALID_HANDLE; ulong privKeyId = CK.CK_INVALID_HANDLE; rv = Helpers.GenerateKeyPair(pkcs11, session, ref pubKeyId, ref privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify mechanism parameters CK_RSA_PKCS_OAEP_PARAMS mechanismParams = new CK_RSA_PKCS_OAEP_PARAMS(); mechanismParams.HashAlg = (ulong)CKM.CKM_SHA_1; mechanismParams.Mgf = (ulong)CKG.CKG_MGF1_SHA1; mechanismParams.Source = (ulong)CKZ.CKZ_DATA_SPECIFIED; mechanismParams.SourceData = IntPtr.Zero; mechanismParams.SourceDataLen = 0; // Specify encryption mechanism with parameters // Note that CkmUtils.CreateMechanism() automaticaly copies mechanismParams into newly allocated unmanaged memory. CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_RSA_PKCS_OAEP, mechanismParams); // Initialize encryption operation rv = pkcs11.C_EncryptInit(session, ref mechanism, pubKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); // Get length of encrypted data in first call ulong encryptedDataLen = 0; rv = pkcs11.C_Encrypt(session, sourceData, Convert.ToUInt64(sourceData.Length), null, ref encryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(encryptedDataLen > 0); // Allocate array for encrypted data byte[] encryptedData = new byte[encryptedDataLen]; // Get encrypted data in second call rv = pkcs11.C_Encrypt(session, sourceData, Convert.ToUInt64(sourceData.Length), encryptedData, ref encryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with encrypted data // Initialize decryption operation rv = pkcs11.C_DecryptInit(session, ref mechanism, privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Get length of decrypted data in first call ulong decryptedDataLen = 0; rv = pkcs11.C_Decrypt(session, encryptedData, Convert.ToUInt64(encryptedData.Length), null, ref decryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(decryptedDataLen > 0); // Allocate array for decrypted data byte[] decryptedData = new byte[decryptedDataLen]; // Get decrypted data in second call rv = pkcs11.C_Decrypt(session, encryptedData, Convert.ToUInt64(encryptedData.Length), decryptedData, ref decryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Array may need to be shrinked if (decryptedData.Length != Convert.ToInt32(decryptedDataLen)) Array.Resize(ref decryptedData, Convert.ToInt32(decryptedDataLen)); // Do something interesting with decrypted data Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData)); // In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter UnmanagedMemory.Free(ref mechanism.Parameter); mechanism.ParameterLen = 0; rv = pkcs11.C_DestroyObject(session, privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_DestroyObject(session, pubKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Logout(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Net; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; using Orleans.Runtime; using LogLevel = Microsoft.Extensions.Logging.LogLevel; namespace Orleans.AzureUtils { /// <summary> /// Utility class to encapsulate row-based access to Azure table storage. /// </summary> /// <remarks> /// These functions are mostly intended for internal usage by Orleans runtime, but due to certain assembly packaging constrants this class needs to have public visibility. /// </remarks> /// <typeparam name="T">Table data entry used by this table / manager.</typeparam> public class AzureTableDataManager<T> where T : class, ITableEntity, new() { /// <summary> Name of the table this instance is managing. </summary> public string TableName { get; private set; } /// <summary> Logger for this table manager instance. </summary> protected internal ILogger Logger { get; private set; } /// <summary> Connection string for the Azure storage account used to host this table. </summary> protected string ConnectionString { get; set; } private CloudTable tableReference; private readonly CounterStatistic numServerBusy = CounterStatistic.FindOrCreate(StatisticNames.AZURE_SERVER_BUSY, true); /// <summary> /// Constructor /// </summary> /// <param name="tableName">Name of the table to be connected to.</param> /// <param name="storageConnectionString">Connection string for the Azure storage account used to host this table.</param> /// <param name="loggerFactory">Logger factory to use.</param> public AzureTableDataManager(string tableName, string storageConnectionString, ILoggerFactory loggerFactory) { Logger = loggerFactory.CreateLogger<AzureTableDataManager<T>>(); TableName = tableName; ConnectionString = storageConnectionString; AzureStorageUtils.ValidateTableName(tableName); } /// <summary> /// Connects to, or creates and initializes a new Azure table if it does not already exist. /// </summary> /// <returns>Completion promise for this operation.</returns> public async Task InitTableAsync() { const string operation = "InitTable"; var startTime = DateTime.UtcNow; try { CloudTableClient tableCreationClient = GetCloudTableCreationClient(); CloudTable tableRef = tableCreationClient.GetTableReference(TableName); bool didCreate = await tableRef.CreateIfNotExistsAsync(); Logger.Info(ErrorCode.AzureTable_01, "{0} Azure storage table {1}", (didCreate ? "Created" : "Attached to"), TableName); CloudTableClient tableOperationsClient = GetCloudTableOperationsClient(); tableReference = tableOperationsClient.GetTableReference(TableName); } catch (Exception exc) { Logger.Error(ErrorCode.AzureTable_02, $"Could not initialize connection to storage table {TableName}", exc); throw; } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Deletes the Azure table. /// </summary> /// <returns>Completion promise for this operation.</returns> public async Task DeleteTableAsync() { const string operation = "DeleteTable"; var startTime = DateTime.UtcNow; try { CloudTableClient tableCreationClient = GetCloudTableCreationClient(); CloudTable tableRef = tableCreationClient.GetTableReference(TableName); bool didDelete = await tableRef.DeleteIfExistsAsync(); if (didDelete) { Logger.Info(ErrorCode.AzureTable_03, "Deleted Azure storage table {0}", TableName); } } catch (Exception exc) { Logger.Error(ErrorCode.AzureTable_04, "Could not delete storage table {0}", exc); throw; } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Deletes all entities the Azure table. /// </summary> /// <returns>Completion promise for this operation.</returns> public async Task ClearTableAsync() { IEnumerable<Tuple<T,string>> items = await ReadAllTableEntriesAsync(); IEnumerable<Task> work = items.GroupBy(item => item.Item1.PartitionKey) .SelectMany(partition => partition.ToBatch(AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS)) .Select(batch => DeleteTableEntriesAsync(batch.ToList())); await Task.WhenAll(work); } /// <summary> /// Create a new data entry in the Azure table (insert new, not update existing). /// Fails if the data already exists. /// </summary> /// <param name="data">Data to be inserted into the table.</param> /// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns> public async Task<string> CreateTableEntryAsync(T data) { const string operation = "CreateTableEntry"; var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Creating {0} table entry: {1}", TableName, data); try { // WAS: // svc.AddObject(TableName, data); // SaveChangesOptions.None try { // Presumably FromAsync(BeginExecute, EndExecute) has a slightly better performance then CreateIfNotExistsAsync. var opResult = await tableReference.ExecuteAsync(TableOperation.Insert(data)); return opResult.Etag; } catch (Exception exc) { CheckAlertWriteError(operation, data, null, exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Inserts a data entry in the Azure table: creates a new one if does not exists or overwrites (without eTag) an already existing version (the "update in place" semantincs). /// </summary> /// <param name="data">Data to be inserted or replaced in the table.</param> /// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns> public async Task<string> UpsertTableEntryAsync(T data) { const string operation = "UpsertTableEntry"; var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} entry {1} into table {2}", operation, data, TableName); try { try { // WAS: // svc.AttachTo(TableName, data, null); // svc.UpdateObject(data); // SaveChangesOptions.ReplaceOnUpdate, var opResult = await tableReference.ExecuteAsync(TableOperation.InsertOrReplace(data)); return opResult.Etag; } catch (Exception exc) { Logger.Warn(ErrorCode.AzureTable_06, $"Intermediate error upserting entry {(data == null ? "null" : data.ToString())} to the table {TableName}", exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Merges a data entry in the Azure table. /// </summary> /// <param name="data">Data to be merged in the table.</param> /// <param name="eTag">ETag to apply.</param> /// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns> internal async Task<string> MergeTableEntryAsync(T data, string eTag) { const string operation = "MergeTableEntry"; var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} entry {1} into table {2}", operation, data, TableName); try { try { // WAS: // svc.AttachTo(TableName, data, ANY_ETAG); // svc.UpdateObject(data); data.ETag = eTag; // Merge requires an ETag (which may be the '*' wildcard). var opResult = await tableReference.ExecuteAsync(TableOperation.Merge(data)); return opResult.Etag; } catch (Exception exc) { Logger.Warn(ErrorCode.AzureTable_07, $"Intermediate error merging entry {(data == null ? "null" : data.ToString())} to the table {TableName}", exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Updates a data entry in the Azure table: updates an already existing data in the table, by using eTag. /// Fails if the data does not already exist or of eTag does not match. /// </summary> /// <param name="data">Data to be updated into the table.</param> /// /// <param name="dataEtag">ETag to use.</param> /// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns> public async Task<string> UpdateTableEntryAsync(T data, string dataEtag) { const string operation = "UpdateTableEntryAsync"; var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} table {1} entry {2}", operation, TableName, data); try { try { data.ETag = dataEtag; var opResult = await tableReference.ExecuteAsync(TableOperation.Replace(data)); //The ETag of data is needed in further operations. return opResult.Etag; } catch (Exception exc) { CheckAlertWriteError(operation, data, null, exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Deletes an already existing data in the table, by using eTag. /// Fails if the data does not already exist or if eTag does not match. /// </summary> /// <param name="data">Data entry to be deleted from the table.</param> /// <param name="eTag">ETag to use.</param> /// <returns>Completion promise for this storage operation.</returns> public async Task DeleteTableEntryAsync(T data, string eTag) { const string operation = "DeleteTableEntryAsync"; var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} table {1} entry {2}", operation, TableName, data); try { data.ETag = eTag; try { await tableReference.ExecuteAsync(TableOperation.Delete(data)); } catch (Exception exc) { Logger.Warn(ErrorCode.AzureTable_08, $"Intermediate error deleting entry {data} from the table {TableName}.", exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Read a single table entry from the storage table. /// </summary> /// <param name="partitionKey">The partition key for the entry.</param> /// <param name="rowKey">The row key for the entry.</param> /// <returns>Value promise for tuple containing the data entry and its corresponding etag.</returns> public async Task<Tuple<T, string>> ReadSingleTableEntryAsync(string partitionKey, string rowKey) { const string operation = "ReadSingleTableEntryAsync"; var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} table {1} partitionKey {2} rowKey = {3}", operation, TableName, partitionKey, rowKey); T retrievedResult = default(T); try { try { string queryString = TableQueryFilterBuilder.MatchPartitionKeyAndRowKeyFilter(partitionKey, rowKey); var query = new TableQuery<T>().Where(queryString); TableQuerySegment<T> segment = await tableReference.ExecuteQuerySegmentedAsync(query, null); retrievedResult = segment.Results.SingleOrDefault(); } catch (StorageException exception) { if (!AzureStorageUtils.TableStorageDataNotFound(exception)) throw; } //The ETag of data is needed in further operations. if (retrievedResult != null) return new Tuple<T, string>(retrievedResult, retrievedResult.ETag); if (Logger.IsEnabled(LogLevel.Debug)) Logger.Debug("Could not find table entry for PartitionKey={0} RowKey={1}", partitionKey, rowKey); return null; // No data } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Read all entries in one partition of the storage table. /// NOTE: This could be an expensive and slow operation for large table partitions! /// </summary> /// <param name="partitionKey">The key for the partition to be searched.</param> /// <returns>Enumeration of all entries in the specified table partition.</returns> public Task<IEnumerable<Tuple<T, string>>> ReadAllTableEntriesForPartitionAsync(string partitionKey) { string query = TableQuery.GenerateFilterCondition(nameof(ITableEntity.PartitionKey), QueryComparisons.Equal, partitionKey); return ReadTableEntriesAndEtagsAsync(query); } /// <summary> /// Read all entries in the table. /// NOTE: This could be a very expensive and slow operation for large tables! /// </summary> /// <returns>Enumeration of all entries in the table.</returns> public Task<IEnumerable<Tuple<T, string>>> ReadAllTableEntriesAsync() { return ReadTableEntriesAndEtagsAsync(null); } /// <summary> /// Deletes a set of already existing data entries in the table, by using eTag. /// Fails if the data does not already exist or if eTag does not match. /// </summary> /// <param name="collection">Data entries and their corresponding etags to be deleted from the table.</param> /// <returns>Completion promise for this storage operation.</returns> public async Task DeleteTableEntriesAsync(IReadOnlyCollection<Tuple<T, string>> collection) { const string operation = "DeleteTableEntries"; var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Deleting {0} table entries: {1}", TableName, Utils.EnumerableToString(collection)); if (collection == null) throw new ArgumentNullException("collection"); if (collection.Count > AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS) { throw new ArgumentOutOfRangeException("collection", collection.Count, "Too many rows for bulk delete - max " + AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS); } if (collection.Count == 0) { return; } try { var entityBatch = new TableBatchOperation(); foreach (var tuple in collection) { // WAS: // svc.AttachTo(TableName, tuple.Item1, tuple.Item2); // svc.DeleteObject(tuple.Item1); // SaveChangesOptions.ReplaceOnUpdate | SaveChangesOptions.Batch, T item = tuple.Item1; item.ETag = tuple.Item2; entityBatch.Delete(item); } try { await tableReference.ExecuteBatchAsync(entityBatch); } catch (Exception exc) { Logger.Warn(ErrorCode.AzureTable_08, $"Intermediate error deleting entries {Utils.EnumerableToString(collection)} from the table {TableName}.", exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Read data entries and their corresponding eTags from the Azure table. /// </summary> /// <param name="filter">Filter string to use for querying the table and filtering the results.</param> /// <returns>Enumeration of entries in the table which match the query condition.</returns> public async Task<IEnumerable<Tuple<T, string>>> ReadTableEntriesAndEtagsAsync(string filter) { const string operation = "ReadTableEntriesAndEtags"; var startTime = DateTime.UtcNow; try { TableQuery<T> cloudTableQuery = filter == null ? new TableQuery<T>() : new TableQuery<T>().Where(filter); try { Func<Task<List<T>>> executeQueryHandleContinuations = async () => { TableQuerySegment<T> querySegment = null; var list = new List<T>(); //ExecuteSegmentedAsync not supported in "WindowsAzure.Storage": "7.2.1" yet while (querySegment == null || querySegment.ContinuationToken != null) { querySegment = await tableReference.ExecuteQuerySegmentedAsync(cloudTableQuery, querySegment?.ContinuationToken); list.AddRange(querySegment); } return list; }; IBackoffProvider backoff = new FixedBackoff(AzureTableDefaultPolicies.PauseBetweenTableOperationRetries); List<T> results = await AsyncExecutorWithRetries.ExecuteWithRetries( counter => executeQueryHandleContinuations(), AzureTableDefaultPolicies.MaxTableOperationRetries, (exc, counter) => AzureStorageUtils.AnalyzeReadException(exc.GetBaseException(), counter, TableName, Logger), AzureTableDefaultPolicies.TableOperationTimeout, backoff); // Data was read successfully if we got to here return results.Select(i => Tuple.Create(i, i.ETag)).ToList(); } catch (Exception exc) { // Out of retries... var errorMsg = $"Failed to read Azure storage table {TableName}: {exc.Message}"; if (!AzureStorageUtils.TableStorageDataNotFound(exc)) { Logger.Warn(ErrorCode.AzureTable_09, errorMsg, exc); } throw new OrleansException(errorMsg, exc); } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Inserts a set of new data entries into the table. /// Fails if the data does already exists. /// </summary> /// <param name="collection">Data entries to be inserted into the table.</param> /// <returns>Completion promise for this storage operation.</returns> public async Task BulkInsertTableEntries(IReadOnlyCollection<T> collection) { const string operation = "BulkInsertTableEntries"; if (collection == null) throw new ArgumentNullException("collection"); if (collection.Count > AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS) { throw new ArgumentOutOfRangeException("collection", collection.Count, "Too many rows for bulk update - max " + AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS); } if (collection.Count == 0) { return; } var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Bulk inserting {0} entries to {1} table", collection.Count, TableName); try { // WAS: // svc.AttachTo(TableName, entry); // svc.UpdateObject(entry); // SaveChangesOptions.None | SaveChangesOptions.Batch, // SaveChangesOptions.None == Insert-or-merge operation, SaveChangesOptions.Batch == Batch transaction // http://msdn.microsoft.com/en-us/library/hh452241.aspx var entityBatch = new TableBatchOperation(); foreach (T entry in collection) { entityBatch.Insert(entry); } try { // http://msdn.microsoft.com/en-us/library/hh452241.aspx await tableReference.ExecuteBatchAsync(entityBatch); } catch (Exception exc) { Logger.Warn(ErrorCode.AzureTable_37, $"Intermediate error bulk inserting {collection.Count} entries in the table {TableName}", exc); } } finally { CheckAlertSlowAccess(startTime, operation); } } #region Internal functions internal async Task<Tuple<string, string>> InsertTwoTableEntriesConditionallyAsync(T data1, T data2, string data2Etag) { const string operation = "InsertTableEntryConditionally"; string data2Str = (data2 == null ? "null" : data2.ToString()); var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} into table {1} data1 {2} data2 {3}", operation, TableName, data1, data2Str); try { try { // WAS: // Only AddObject, do NOT AttachTo. If we did both UpdateObject and AttachTo, it would have been equivalent to InsertOrReplace. // svc.AddObject(TableName, data); // --- // svc.AttachTo(TableName, tableVersion, tableVersionEtag); // svc.UpdateObject(tableVersion); // SaveChangesOptions.ReplaceOnUpdate | SaveChangesOptions.Batch, // EntityDescriptor dataResult = svc.GetEntityDescriptor(data); // return dataResult.ETag; var entityBatch = new TableBatchOperation(); entityBatch.Add(TableOperation.Insert(data1)); data2.ETag = data2Etag; entityBatch.Add(TableOperation.Replace(data2)); var opResults = await tableReference.ExecuteBatchAsync(entityBatch); //The batch results are returned in order of execution, //see reference at https://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storage.table.cloudtable.executebatch.aspx. //The ETag of data is needed in further operations. return new Tuple<string, string>(opResults[0].Etag, opResults[1].Etag); } catch (Exception exc) { CheckAlertWriteError(operation, data1, data2Str, exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } internal async Task<Tuple<string, string>> UpdateTwoTableEntriesConditionallyAsync(T data1, string data1Etag, T data2, string data2Etag) { const string operation = "UpdateTableEntryConditionally"; string data2Str = (data2 == null ? "null" : data2.ToString()); var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} table {1} data1 {2} data2 {3}", operation, TableName, data1, data2Str); try { try { // WAS: // Only AddObject, do NOT AttachTo. If we did both UpdateObject and AttachTo, it would have been equivalent to InsertOrReplace. // svc.AttachTo(TableName, data, dataEtag); // svc.UpdateObject(data); // ---- // svc.AttachTo(TableName, tableVersion, tableVersionEtag); // svc.UpdateObject(tableVersion); // SaveChangesOptions.ReplaceOnUpdate | SaveChangesOptions.Batch, // EntityDescriptor dataResult = svc.GetEntityDescriptor(data); // return dataResult.ETag; var entityBatch = new TableBatchOperation(); data1.ETag = data1Etag; entityBatch.Add(TableOperation.Replace(data1)); if (data2 != null && data2Etag != null) { data2.ETag = data2Etag; entityBatch.Add(TableOperation.Replace(data2)); } var opResults = await tableReference.ExecuteBatchAsync(entityBatch); //The batch results are returned in order of execution, //see reference at https://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storage.table.cloudtable.executebatch.aspx. //The ETag of data is needed in further operations. return new Tuple<string, string>(opResults[0].Etag, opResults[1].Etag); } catch (Exception exc) { CheckAlertWriteError(operation, data1, data2Str, exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } // Utility methods private CloudTableClient GetCloudTableOperationsClient() { try { CloudStorageAccount storageAccount = AzureStorageUtils.GetCloudStorageAccount(ConnectionString); CloudTableClient operationsClient = storageAccount.CreateCloudTableClient(); operationsClient.DefaultRequestOptions.RetryPolicy = AzureTableDefaultPolicies.TableOperationRetryPolicy; operationsClient.DefaultRequestOptions.ServerTimeout = AzureTableDefaultPolicies.TableOperationTimeout; // Values supported can be AtomPub, Json, JsonFullMetadata or JsonNoMetadata with Json being the default value operationsClient.DefaultRequestOptions.PayloadFormat = TablePayloadFormat.JsonNoMetadata; return operationsClient; } catch (Exception exc) { Logger.Error(ErrorCode.AzureTable_17, "Error creating CloudTableOperationsClient.", exc); throw; } } private CloudTableClient GetCloudTableCreationClient() { try { CloudStorageAccount storageAccount = AzureStorageUtils.GetCloudStorageAccount(ConnectionString); CloudTableClient creationClient = storageAccount.CreateCloudTableClient(); creationClient.DefaultRequestOptions.RetryPolicy = AzureTableDefaultPolicies.TableCreationRetryPolicy; creationClient.DefaultRequestOptions.ServerTimeout = AzureTableDefaultPolicies.TableCreationTimeout; // Values supported can be AtomPub, Json, JsonFullMetadata or JsonNoMetadata with Json being the default value creationClient.DefaultRequestOptions.PayloadFormat = TablePayloadFormat.JsonNoMetadata; return creationClient; } catch (Exception exc) { Logger.Error(ErrorCode.AzureTable_18, "Error creating CloudTableCreationClient.", exc); throw; } } private void CheckAlertWriteError(string operation, object data1, string data2, Exception exc) { HttpStatusCode httpStatusCode; string restStatus; if(AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus) && AzureStorageUtils.IsContentionError(httpStatusCode)) { // log at Verbose, since failure on conditional is not not an error. Will analyze and warn later, if required. if(Logger.IsEnabled(LogLevel.Debug)) Logger.Debug(ErrorCode.AzureTable_13, $"Intermediate Azure table write error {operation} to table {TableName} data1 {(data1 ?? "null")} data2 {(data2 ?? "null")}", exc); } else { Logger.Error(ErrorCode.AzureTable_14, $"Azure table access write error {operation} to table {TableName} entry {data1}", exc); } } private void CheckAlertSlowAccess(DateTime startOperation, string operation) { var timeSpan = DateTime.UtcNow - startOperation; if (timeSpan > AzureTableDefaultPolicies.TableOperationTimeout) { Logger.Warn(ErrorCode.AzureTable_15, "Slow access to Azure Table {0} for {1}, which took {2}.", TableName, operation, timeSpan); } } #endregion } internal static class TableDataManagerInternalExtensions { internal static IEnumerable<IEnumerable<TItem>> ToBatch<TItem>(this IEnumerable<TItem> source, int size) { using (IEnumerator<TItem> enumerator = source.GetEnumerator()) while (enumerator.MoveNext()) yield return Take(enumerator, size); } private static IEnumerable<TItem> Take<TItem>(IEnumerator<TItem> source, int size) { int i = 0; do yield return source.Current; while (++i < size && source.MoveNext()); } } }
using System; using System.Collections.Generic; using System.Data; using System.Dynamic; using System.Linq; using NUnit.Framework; namespace SequelocityDotNet.Tests.MySql.DatabaseCommandExtensionsTests { [TestFixture] public class GenerateInsertsForMySqlTests { public struct Customer { public int? CustomerId; public string FirstName; public string LastName; public DateTime DateOfBirth; } [Test] public void Should_Return_The_Last_Inserted_Ids() { // Arrange const string createSchemaSql = @" DROP TABLE IF EXISTS Customer; CREATE TABLE IF NOT EXISTS Customer ( CustomerId INT NOT NULL AUTO_INCREMENT, FirstName NVARCHAR(120) NOT NULL, LastName NVARCHAR(120) NOT NULL, DateOfBirth DATETIME NOT NULL, PRIMARY KEY ( CustomerId ) ); "; var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.MySqlConnectionString ); new DatabaseCommand( dbConnection ) .SetCommandText( createSchemaSql ) .ExecuteNonQuery(); var customer1 = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) }; var customer2 = new Customer { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) }; var customer3 = new Customer { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse( "08/18/1962" ) }; var list = new List<Customer> { customer1, customer2, customer3 }; // Act var customerIds = new DatabaseCommand( dbConnection ) .GenerateInsertsForMySql( list ) .ExecuteToList<long>(); // Assert Assert.That( customerIds.Count == 3 ); Assert.That( customerIds[0] == 1 ); Assert.That( customerIds[1] == 2 ); Assert.That( customerIds[2] == 3 ); } [Test] public void Should_Handle_Generating_Inserts_For_A_Strongly_Typed_Object() { // Arrange const string createSchemaSql = @" DROP TABLE IF EXISTS Customer; CREATE TABLE IF NOT EXISTS Customer ( CustomerId INT NOT NULL AUTO_INCREMENT, FirstName NVARCHAR(120) NOT NULL, LastName NVARCHAR(120) NOT NULL, DateOfBirth DATETIME NOT NULL, PRIMARY KEY ( CustomerId ) ); "; var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.MySqlConnectionString ); new DatabaseCommand( dbConnection ) .SetCommandText( createSchemaSql ) .ExecuteNonQuery(); var customer1 = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) }; var customer2 = new Customer { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) }; var customer3 = new Customer { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse( "08/18/1962" ) }; var list = new List<Customer> { customer1, customer2, customer3 }; // Act var customerIds = new DatabaseCommand( dbConnection ) .GenerateInsertsForMySql( list ) .ExecuteToList<int>(); const string selectCustomerQuery = @" SELECT CustomerId, FirstName, LastName, DateOfBirth FROM Customer WHERE CustomerId IN ( @CustomerIds ); "; var customers = new DatabaseCommand( dbConnection ) .SetCommandText( selectCustomerQuery ) .AddParameters( "@CustomerIds", customerIds, DbType.Int32 ) .ExecuteToList<Customer>() .OrderBy( x => x.CustomerId ) .ToList(); // Assert Assert.That( customers.Count == 3 ); Assert.That( customers[0].CustomerId == 1 ); Assert.That( customers[0].FirstName == customer1.FirstName ); Assert.That( customers[0].LastName == customer1.LastName ); Assert.That( customers[0].DateOfBirth == customer1.DateOfBirth ); Assert.That( customers[1].CustomerId == 2 ); Assert.That( customers[1].FirstName == customer2.FirstName ); Assert.That( customers[1].LastName == customer2.LastName ); Assert.That( customers[1].DateOfBirth == customer2.DateOfBirth ); Assert.That( customers[2].CustomerId == 3 ); Assert.That( customers[2].FirstName == customer3.FirstName ); Assert.That( customers[2].LastName == customer3.LastName ); Assert.That( customers[2].DateOfBirth == customer3.DateOfBirth ); } [Test] public void Should_Be_Able_To_Specify_The_Table_Name() { // Arrange const string createSchemaSql = @" DROP TABLE IF EXISTS Person; CREATE TABLE IF NOT EXISTS Person ( CustomerId INT NOT NULL AUTO_INCREMENT, FirstName NVARCHAR(120) NOT NULL, LastName NVARCHAR(120) NOT NULL, DateOfBirth DATETIME NOT NULL, PRIMARY KEY ( CustomerId ) ); "; var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.MySqlConnectionString ); new DatabaseCommand( dbConnection ) .SetCommandText( createSchemaSql ) .ExecuteNonQuery(); var customer1 = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) }; var customer2 = new Customer { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) }; var customer3 = new Customer { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse( "08/18/1962" ) }; var list = new List<Customer> { customer1, customer2, customer3 }; // Act var numberOfAffectedRecords = new DatabaseCommand( dbConnection ) .GenerateInsertsForMySql( list, "Person" ) // Specifying a table name of Person .ExecuteNonQuery(); // Assert Assert.That( numberOfAffectedRecords == list.Count ); } [Test] public void Should_Throw_An_Exception_When_Passing_An_Anonymous_Object_And_Not_Specifying_A_TableName() { // Arrange const string createSchemaSql = @" DROP TABLE IF EXISTS Person; CREATE TABLE IF NOT EXISTS Person ( CustomerId INT NOT NULL AUTO_INCREMENT, FirstName NVARCHAR(120) NOT NULL, LastName NVARCHAR(120) NOT NULL, DateOfBirth DATETIME NOT NULL, PRIMARY KEY ( CustomerId ) ); "; var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.MySqlConnectionString ); new DatabaseCommand( dbConnection ) .SetCommandText( createSchemaSql ) .ExecuteNonQuery(); var customer1 = new { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) }; var customer2 = new { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) }; var customer3 = new { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse( "08/18/1962" ) }; var list = new List<object> { customer1, customer2, customer3 }; // Act TestDelegate action = () => new DatabaseCommand( dbConnection ) .GenerateInsertsForMySql( list ) .ExecuteScalar() .ToInt(); // Assert var exception = Assert.Catch<ArgumentNullException>( action ); Assert.That( exception.Message.Contains( "The 'tableName' parameter must be provided when the object supplied is an anonymous type." ) ); } [Test] public void Should_Handle_Generating_Inserts_For_An_Anonymous_Object() { // Arrange const string createSchemaSql = @" DROP TABLE IF EXISTS Customer; CREATE TABLE IF NOT EXISTS Customer ( CustomerId INT NOT NULL AUTO_INCREMENT, FirstName NVARCHAR(120) NOT NULL, LastName NVARCHAR(120) NOT NULL, DateOfBirth DATETIME NOT NULL, PRIMARY KEY ( CustomerId ) ); "; var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.MySqlConnectionString ); new DatabaseCommand( dbConnection ) .SetCommandText( createSchemaSql ) .ExecuteNonQuery(); var customer1 = new { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) }; var customer2 = new { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) }; var customer3 = new { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse( "08/18/1962" ) }; var list = new List<object> { customer1, customer2, customer3 }; // Act var customerIds = new DatabaseCommand( dbConnection ) .GenerateInsertsForMySql( list, "Customer" ) .ExecuteToList<long>(); const string selectCustomerQuery = @" SELECT CustomerId, FirstName, LastName, DateOfBirth FROM Customer WHERE CustomerId IN ( @CustomerIds ); "; var customers = new DatabaseCommand( dbConnection ) .SetCommandText( selectCustomerQuery ) .AddParameters( "@CustomerIds", customerIds, DbType.Int64 ) .ExecuteToList<Customer>() .OrderBy( x => x.CustomerId ) .ToList(); // Assert Assert.That( customers.Count == 3 ); Assert.That( customers[0].CustomerId == 1 ); Assert.That( customers[0].FirstName == customer1.FirstName ); Assert.That( customers[0].LastName == customer1.LastName ); Assert.That( customers[0].DateOfBirth == customer1.DateOfBirth ); Assert.That( customers[1].CustomerId == 2 ); Assert.That( customers[1].FirstName == customer2.FirstName ); Assert.That( customers[1].LastName == customer2.LastName ); Assert.That( customers[1].DateOfBirth == customer2.DateOfBirth ); Assert.That( customers[2].CustomerId == 3 ); Assert.That( customers[2].FirstName == customer3.FirstName ); Assert.That( customers[2].LastName == customer3.LastName ); Assert.That( customers[2].DateOfBirth == customer3.DateOfBirth ); } [Test] public void Should_Handle_Generating_Inserts_For_A_Dynamic_Object() { // Arrange const string createSchemaSql = @" DROP TABLE IF EXISTS Customer; CREATE TABLE IF NOT EXISTS Customer ( CustomerId INT NOT NULL AUTO_INCREMENT, FirstName NVARCHAR(120) NOT NULL, LastName NVARCHAR(120) NOT NULL, DateOfBirth DATETIME NOT NULL, PRIMARY KEY ( CustomerId ) ); "; var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.MySqlConnectionString ); new DatabaseCommand( dbConnection ) .SetCommandText( createSchemaSql ) .ExecuteNonQuery(); dynamic customer1 = new ExpandoObject(); customer1.FirstName = "Clark"; customer1.LastName = "Kent"; customer1.DateOfBirth = DateTime.Parse( "06/18/1938" ); dynamic customer2 = new ExpandoObject(); customer2.FirstName = "Bruce"; customer2.LastName = "Wayne"; customer2.DateOfBirth = DateTime.Parse( "05/27/1939" ); dynamic customer3 = new ExpandoObject(); customer3.FirstName = "Peter"; customer3.LastName = "Parker"; customer3.DateOfBirth = DateTime.Parse( "08/18/1962" ); var list = new List<dynamic> { customer1, customer2, customer3 }; // Act var customerIds = new DatabaseCommand( dbConnection ) .GenerateInsertsForMySql( list, "Customer" ) .ExecuteToList<long>(); const string selectCustomerQuery = @" SELECT CustomerId, FirstName, LastName, DateOfBirth FROM Customer WHERE CustomerId IN ( @CustomerIds ); "; var customers = new DatabaseCommand( dbConnection ) .SetCommandText( selectCustomerQuery ) .AddParameters( "@CustomerIds", customerIds, DbType.Int64 ) .ExecuteToList<Customer>() .OrderBy( x => x.CustomerId ) .ToList(); // Assert Assert.That( customers.Count == 3 ); Assert.That( customers[0].CustomerId == 1 ); Assert.That( customers[0].FirstName == customer1.FirstName ); Assert.That( customers[0].LastName == customer1.LastName ); Assert.That( customers[0].DateOfBirth == customer1.DateOfBirth ); Assert.That( customers[1].CustomerId == 2 ); Assert.That( customers[1].FirstName == customer2.FirstName ); Assert.That( customers[1].LastName == customer2.LastName ); Assert.That( customers[1].DateOfBirth == customer2.DateOfBirth ); Assert.That( customers[2].CustomerId == 3 ); Assert.That( customers[2].FirstName == customer3.FirstName ); Assert.That( customers[2].LastName == customer3.LastName ); Assert.That( customers[2].DateOfBirth == customer3.DateOfBirth ); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Net.Http.Headers; using System.Text; namespace System.Net.Http { public class HttpResponseMessage : IDisposable { private const HttpStatusCode defaultStatusCode = HttpStatusCode.OK; private HttpStatusCode _statusCode; private HttpResponseHeaders _headers; private string _reasonPhrase; private HttpRequestMessage _requestMessage; private Version _version; private HttpContent _content; private bool _disposed; public Version Version { get { return _version; } set { #if !PHONE if (value == null) { throw new ArgumentNullException("value"); } #endif CheckDisposed(); _version = value; } } public HttpContent Content { get { return _content; } set { CheckDisposed(); if (Logging.On) { if (value == null) { Logging.PrintInfo(Logging.Http, this, SR.net_http_log_content_null); } else { Logging.Associate(Logging.Http, this, value); } } _content = value; } } public HttpStatusCode StatusCode { get { return _statusCode; } set { if (((int)value < 0) || ((int)value > 999)) { throw new ArgumentOutOfRangeException("value"); } CheckDisposed(); _statusCode = value; } } public string ReasonPhrase { get { if (_reasonPhrase != null) { return _reasonPhrase; } // Provide a default if one was not set. return HttpStatusDescription.Get(StatusCode); } set { if ((value != null) && ContainsNewLineCharacter(value)) { throw new FormatException(SR.net_http_reasonphrase_format_error); } CheckDisposed(); _reasonPhrase = value; // It's OK to have a 'null' reason phrase. } } public HttpResponseHeaders Headers { get { if (_headers == null) { _headers = new HttpResponseHeaders(); } return _headers; } } public HttpRequestMessage RequestMessage { get { return _requestMessage; } set { CheckDisposed(); if (Logging.On && (value != null)) Logging.Associate(Logging.Http, this, value); _requestMessage = value; } } public bool IsSuccessStatusCode { get { return ((int)_statusCode >= 200) && ((int)_statusCode <= 299); } } public HttpResponseMessage() : this(defaultStatusCode) { } public HttpResponseMessage(HttpStatusCode statusCode) { if (Logging.On) Logging.Enter(Logging.Http, this, ".ctor", "StatusCode: " + (int)statusCode + ", ReasonPhrase: '" + _reasonPhrase + "'"); if (((int)statusCode < 0) || ((int)statusCode > 999)) { throw new ArgumentOutOfRangeException("statusCode"); } _statusCode = statusCode; _version = HttpUtilities.DefaultResponseVersion; if (Logging.On) Logging.Exit(Logging.Http, this, ".ctor", null); } public HttpResponseMessage EnsureSuccessStatusCode() { if (!IsSuccessStatusCode) { // Disposing the content should help users: If users call EnsureSuccessStatusCode(), an exception is // thrown if the response status code is != 2xx. I.e. the behavior is similar to a failed request (e.g. // connection failure). Users don't expect to dispose the content in this case: If an exception is // thrown, the object is responsible fore cleaning up its state. if (_content != null) { _content.Dispose(); } throw new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_message_not_success_statuscode, (int)_statusCode, ReasonPhrase)); } return this; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("StatusCode: "); sb.Append((int)_statusCode); sb.Append(", ReasonPhrase: '"); sb.Append(ReasonPhrase ?? "<null>"); sb.Append("', Version: "); sb.Append(_version); sb.Append(", Content: "); sb.Append(_content == null ? "<null>" : _content.GetType().ToString()); sb.Append(", Headers:\r\n"); sb.Append(HeaderUtilities.DumpHeaders(_headers, _content == null ? null : _content.Headers)); return sb.ToString(); } private bool ContainsNewLineCharacter(string value) { foreach (char character in value) { if ((character == HttpRuleParser.CR) || (character == HttpRuleParser.LF)) { return true; } } return false; } #region IDisposable Members protected virtual void Dispose(bool disposing) { // The reason for this type to implement IDisposable is that it contains instances of types that implement // IDisposable (content). if (disposing && !_disposed) { _disposed = true; if (_content != null) { _content.Dispose(); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(this.GetType().ToString()); } } } }
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using PlayFab.Json.Utilities; using System.Globalization; using System.Dynamic; using System.Linq.Expressions; using System.Numerics; namespace PlayFab.Json.Linq { /// <summary> /// Represents a value in JSON (string, integer, date, etc). /// </summary> public class JValue : JToken, IEquatable<JValue>, IFormattable, IComparable, IComparable<JValue> { private JTokenType _valueType; private object _value; internal JValue(object value, JTokenType type) { _value = value; _valueType = type; } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class from another <see cref="JValue"/> object. /// </summary> /// <param name="other">A <see cref="JValue"/> object to copy from.</param> public JValue(JValue other) : this(other.Value, other.Type) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(long value) : this(value, JTokenType.Integer) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(char value) : this(value, JTokenType.String) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(ulong value) : this(value, JTokenType.Integer) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(double value) : this(value, JTokenType.Float) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(float value) : this(value, JTokenType.Float) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(DateTime value) : this(value, JTokenType.Date) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(bool value) : this(value, JTokenType.Boolean) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(string value) : this(value, JTokenType.String) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(Guid value) : this(value, JTokenType.Guid) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(Uri value) : this(value, (value != null) ? JTokenType.Uri : JTokenType.Null) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(TimeSpan value) : this(value, JTokenType.TimeSpan) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(object value) : this(value, GetValueType(null, value)) { } internal override bool DeepEquals(JToken node) { JValue other = node as JValue; if (other == null) return false; if (other == this) return true; return ValuesEquals(this, other); } /// <summary> /// Gets a value indicating whether this token has child tokens. /// </summary> /// <value> /// <c>true</c> if this token has child values; otherwise, <c>false</c>. /// </value> public override bool HasValues { get { return false; } } private static int CompareBigInteger(BigInteger i1, object i2) { int result = i1.CompareTo(ConvertUtils.ToBigInteger(i2)); if (result != 0) return result; // converting a fractional number to a BigInteger will lose the fraction // check for fraction if result is two numbers are equal if (i2 is decimal) { decimal d = (decimal) i2; return (0m).CompareTo(Math.Abs(d - Math.Truncate(d))); } else if (i2 is double || i2 is float) { double d = Convert.ToDouble(i2, CultureInfo.InvariantCulture); return (0d).CompareTo(Math.Abs(d - Math.Truncate(d))); } return result; } internal static int Compare(JTokenType valueType, object objA, object objB) { if (objA == null && objB == null) return 0; if (objA != null && objB == null) return 1; if (objA == null && objB != null) return -1; switch (valueType) { case JTokenType.Integer: if (objA is BigInteger) return CompareBigInteger((BigInteger)objA, objB); if (objB is BigInteger) return -CompareBigInteger((BigInteger)objB, objA); if (objA is ulong || objB is ulong || objA is decimal || objB is decimal) return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture)); else if (objA is float || objB is float || objA is double || objB is double) return CompareFloat(objA, objB); else return Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture)); case JTokenType.Float: if (objA is BigInteger) return CompareBigInteger((BigInteger)objA, objB); if (objB is BigInteger) return -CompareBigInteger((BigInteger)objB, objA); return CompareFloat(objA, objB); case JTokenType.Comment: case JTokenType.String: case JTokenType.Raw: string s1 = Convert.ToString(objA, CultureInfo.InvariantCulture); string s2 = Convert.ToString(objB, CultureInfo.InvariantCulture); return string.CompareOrdinal(s1, s2); case JTokenType.Boolean: bool b1 = Convert.ToBoolean(objA, CultureInfo.InvariantCulture); bool b2 = Convert.ToBoolean(objB, CultureInfo.InvariantCulture); return b1.CompareTo(b2); case JTokenType.Date: if (objA is DateTime) { DateTime date1 = (DateTime)objA; DateTime date2; if (objB is DateTimeOffset) date2 = ((DateTimeOffset)objB).DateTime; else date2 = Convert.ToDateTime(objB, CultureInfo.InvariantCulture); return date1.CompareTo(date2); } else { DateTimeOffset date1 = (DateTimeOffset) objA; DateTimeOffset date2; if (objB is DateTimeOffset) date2 = (DateTimeOffset)objB; else date2 = new DateTimeOffset(Convert.ToDateTime(objB, CultureInfo.InvariantCulture)); return date1.CompareTo(date2); } case JTokenType.Bytes: if (!(objB is byte[])) throw new ArgumentException("Object must be of type byte[]."); byte[] bytes1 = objA as byte[]; byte[] bytes2 = objB as byte[]; if (bytes1 == null) return -1; if (bytes2 == null) return 1; return MiscellaneousUtils.ByteArrayCompare(bytes1, bytes2); case JTokenType.Guid: if (!(objB is Guid)) throw new ArgumentException("Object must be of type Guid."); Guid guid1 = (Guid) objA; Guid guid2 = (Guid) objB; return guid1.CompareTo(guid2); case JTokenType.Uri: if (!(objB is Uri)) throw new ArgumentException("Object must be of type Uri."); Uri uri1 = (Uri)objA; Uri uri2 = (Uri)objB; return Comparer<string>.Default.Compare(uri1.ToString(), uri2.ToString()); case JTokenType.TimeSpan: if (!(objB is TimeSpan)) throw new ArgumentException("Object must be of type TimeSpan."); TimeSpan ts1 = (TimeSpan)objA; TimeSpan ts2 = (TimeSpan)objB; return ts1.CompareTo(ts2); default: throw MiscellaneousUtils.CreateArgumentOutOfRangeException("valueType", valueType, "Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType)); } } private static int CompareFloat(object objA, object objB) { double d1 = Convert.ToDouble(objA, CultureInfo.InvariantCulture); double d2 = Convert.ToDouble(objB, CultureInfo.InvariantCulture); // take into account possible floating point errors if (MathUtils.ApproxEquals(d1, d2)) return 0; return d1.CompareTo(d2); } private static bool Operation(ExpressionType operation, object objA, object objB, out object result) { if (objA is string || objB is string) { if (operation == ExpressionType.Add || operation == ExpressionType.AddAssign) { result = ((objA != null) ? objA.ToString() : null) + ((objB != null) ? objB.ToString() : null); return true; } } if (objA is BigInteger || objB is BigInteger) { if (objA == null || objB == null) { result = null; return true; } // not that this will lose the fraction // BigInteger doesn't have operators with non-integer types BigInteger i1 = ConvertUtils.ToBigInteger(objA); BigInteger i2 = ConvertUtils.ToBigInteger(objB); switch (operation) { case ExpressionType.Add: case ExpressionType.AddAssign: result = i1 + i2; return true; case ExpressionType.Subtract: case ExpressionType.SubtractAssign: result = i1 - i2; return true; case ExpressionType.Multiply: case ExpressionType.MultiplyAssign: result = i1 * i2; return true; case ExpressionType.Divide: case ExpressionType.DivideAssign: result = i1 / i2; return true; } } else if (objA is ulong || objB is ulong || objA is decimal || objB is decimal) { if (objA == null || objB == null) { result = null; return true; } decimal d1 = Convert.ToDecimal(objA, CultureInfo.InvariantCulture); decimal d2 = Convert.ToDecimal(objB, CultureInfo.InvariantCulture); switch (operation) { case ExpressionType.Add: case ExpressionType.AddAssign: result = d1 + d2; return true; case ExpressionType.Subtract: case ExpressionType.SubtractAssign: result = d1 - d2; return true; case ExpressionType.Multiply: case ExpressionType.MultiplyAssign: result = d1 * d2; return true; case ExpressionType.Divide: case ExpressionType.DivideAssign: result = d1 / d2; return true; } } else if (objA is float || objB is float || objA is double || objB is double) { if (objA == null || objB == null) { result = null; return true; } double d1 = Convert.ToDouble(objA, CultureInfo.InvariantCulture); double d2 = Convert.ToDouble(objB, CultureInfo.InvariantCulture); switch (operation) { case ExpressionType.Add: case ExpressionType.AddAssign: result = d1 + d2; return true; case ExpressionType.Subtract: case ExpressionType.SubtractAssign: result = d1 - d2; return true; case ExpressionType.Multiply: case ExpressionType.MultiplyAssign: result = d1 * d2; return true; case ExpressionType.Divide: case ExpressionType.DivideAssign: result = d1 / d2; return true; } } else if (objA is int || objA is uint || objA is long || objA is short || objA is ushort || objA is sbyte || objA is byte || objB is int || objB is uint || objB is long || objB is short || objB is ushort || objB is sbyte || objB is byte) { if (objA == null || objB == null) { result = null; return true; } long l1 = Convert.ToInt64(objA, CultureInfo.InvariantCulture); long l2 = Convert.ToInt64(objB, CultureInfo.InvariantCulture); switch (operation) { case ExpressionType.Add: case ExpressionType.AddAssign: result = l1 + l2; return true; case ExpressionType.Subtract: case ExpressionType.SubtractAssign: result = l1 - l2; return true; case ExpressionType.Multiply: case ExpressionType.MultiplyAssign: result = l1 * l2; return true; case ExpressionType.Divide: case ExpressionType.DivideAssign: result = l1 / l2; return true; } } result = null; return false; } internal override JToken CloneToken() { return new JValue(this); } /// <summary> /// Creates a <see cref="JValue"/> comment with the given value. /// </summary> /// <param name="value">The value.</param> /// <returns>A <see cref="JValue"/> comment with the given value.</returns> public static JValue CreateComment(string value) { return new JValue(value, JTokenType.Comment); } /// <summary> /// Creates a <see cref="JValue"/> string with the given value. /// </summary> /// <param name="value">The value.</param> /// <returns>A <see cref="JValue"/> string with the given value.</returns> public static JValue CreateString(string value) { return new JValue(value, JTokenType.String); } private static JTokenType GetValueType(JTokenType? current, object value) { if (value == null) return JTokenType.Null; else if (value is string) return GetStringValueType(current); else if (value is long || value is int || value is short || value is sbyte || value is ulong || value is uint || value is ushort || value is byte) return JTokenType.Integer; else if (value is Enum) return JTokenType.Integer; else if (value is BigInteger) return JTokenType.Integer; else if (value is double || value is float || value is decimal) return JTokenType.Float; else if (value is DateTime) return JTokenType.Date; else if (value is DateTimeOffset) return JTokenType.Date; else if (value is byte[]) return JTokenType.Bytes; else if (value is bool) return JTokenType.Boolean; else if (value is Guid) return JTokenType.Guid; else if (value is Uri) return JTokenType.Uri; else if (value is TimeSpan) return JTokenType.TimeSpan; throw new ArgumentException("Could not determine JSON object type for type {0}.".FormatWith(CultureInfo.InvariantCulture, value.GetType())); } private static JTokenType GetStringValueType(JTokenType? current) { if (current == null) return JTokenType.String; switch (current.Value) { case JTokenType.Comment: case JTokenType.String: case JTokenType.Raw: return current.Value; default: return JTokenType.String; } } /// <summary> /// Gets the node type for this <see cref="JToken"/>. /// </summary> /// <value>The type.</value> public override JTokenType Type { get { return _valueType; } } /// <summary> /// Gets or sets the underlying token value. /// </summary> /// <value>The underlying token value.</value> public object Value { get { return _value; } set { Type currentType = (_value != null) ? _value.GetType() : null; Type newType = (value != null) ? value.GetType() : null; if (currentType != newType) _valueType = GetValueType(_valueType, value); _value = value; } } /// <summary> /// Writes this token to a <see cref="JsonWriter"/>. /// </summary> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { if (converters != null && converters.Length > 0 && _value != null) { JsonConverter matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType()); if (matchingConverter != null) { matchingConverter.WriteJson(writer, _value, JsonSerializer.CreateDefault()); return; } } switch (_valueType) { case JTokenType.Comment: writer.WriteComment((_value != null) ? _value.ToString() : null); return; case JTokenType.Raw: writer.WriteRawValue((_value != null) ? _value.ToString() : null); return; case JTokenType.Null: writer.WriteNull(); return; case JTokenType.Undefined: writer.WriteUndefined(); return; case JTokenType.Integer: if (_value is BigInteger) writer.WriteValue((BigInteger)_value); else writer.WriteValue(Convert.ToInt64(_value, CultureInfo.InvariantCulture)); return; case JTokenType.Float: if (_value is decimal) writer.WriteValue((decimal)_value); else if (_value is double) writer.WriteValue((double)_value); else if (_value is float) writer.WriteValue((float)_value); else writer.WriteValue(Convert.ToDouble(_value, CultureInfo.InvariantCulture)); return; case JTokenType.String: writer.WriteValue((_value != null) ? _value.ToString() : null); return; case JTokenType.Boolean: writer.WriteValue(Convert.ToBoolean(_value, CultureInfo.InvariantCulture)); return; case JTokenType.Date: if (_value is DateTimeOffset) writer.WriteValue((DateTimeOffset)_value); else writer.WriteValue(Convert.ToDateTime(_value, CultureInfo.InvariantCulture)); return; case JTokenType.Bytes: writer.WriteValue((byte[])_value); return; case JTokenType.Guid: case JTokenType.Uri: case JTokenType.TimeSpan: writer.WriteValue((_value != null) ? _value.ToString() : null); return; } throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", _valueType, "Unexpected token type."); } internal override int GetDeepHashCode() { int valueHashCode = (_value != null) ? _value.GetHashCode() : 0; return _valueType.GetHashCode() ^ valueHashCode; } private static bool ValuesEquals(JValue v1, JValue v2) { return (v1 == v2 || (v1._valueType == v2._valueType && Compare(v1._valueType, v1._value, v2._value) == 0)); } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <returns> /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false. /// </returns> /// <param name="other">An object to compare with this object.</param> public bool Equals(JValue other) { if (other == null) return false; return ValuesEquals(this, other); } /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param> /// <returns> /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false. /// </returns> /// <exception cref="T:System.NullReferenceException"> /// The <paramref name="obj"/> parameter is null. /// </exception> public override bool Equals(object obj) { if (obj == null) return false; JValue otherValue = obj as JValue; if (otherValue != null) return Equals(otherValue); return base.Equals(obj); } /// <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() { if (_value == null) return 0; return _value.GetHashCode(); } /// <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() { if (_value == null) return string.Empty; return _value.ToString(); } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <param name="format">The format.</param> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public string ToString(string format) { return ToString(format, CultureInfo.CurrentCulture); } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <param name="formatProvider">The format provider.</param> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public string ToString(IFormatProvider formatProvider) { return ToString(null, formatProvider); } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <param name="format">The format.</param> /// <param name="formatProvider">The format provider.</param> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public string ToString(string format, IFormatProvider formatProvider) { if (_value == null) return string.Empty; IFormattable formattable = _value as IFormattable; if (formattable != null) return formattable.ToString(format, formatProvider); else return _value.ToString(); } /// <summary> /// Returns the <see cref="T:System.Dynamic.DynamicMetaObject"/> responsible for binding operations performed on this object. /// </summary> /// <param name="parameter">The expression tree representation of the runtime value.</param> /// <returns> /// The <see cref="T:System.Dynamic.DynamicMetaObject"/> to bind this object. /// </returns> protected override DynamicMetaObject GetMetaObject(Expression parameter) { return new DynamicProxyMetaObject<JValue>(parameter, this, new JValueDynamicProxy(), true); } private class JValueDynamicProxy : DynamicProxy<JValue> { public override bool TryConvert(JValue instance, ConvertBinder binder, out object result) { if (binder.Type == typeof(JValue)) { result = instance; return true; } object value = instance.Value; if (value == null) { result = null; return ReflectionUtils.IsNullable(binder.Type); } result = ConvertUtils.Convert(instance.Value, CultureInfo.InvariantCulture, binder.Type); return true; } public override bool TryBinaryOperation(JValue instance, BinaryOperationBinder binder, object arg, out object result) { object compareValue = (arg is JValue) ? ((JValue) arg).Value : arg; switch (binder.Operation) { case ExpressionType.Equal: result = (Compare(instance.Type, instance.Value, compareValue) == 0); return true; case ExpressionType.NotEqual: result = (Compare(instance.Type, instance.Value, compareValue) != 0); return true; case ExpressionType.GreaterThan: result = (Compare(instance.Type, instance.Value, compareValue) > 0); return true; case ExpressionType.GreaterThanOrEqual: result = (Compare(instance.Type, instance.Value, compareValue) >= 0); return true; case ExpressionType.LessThan: result = (Compare(instance.Type, instance.Value, compareValue) < 0); return true; case ExpressionType.LessThanOrEqual: result = (Compare(instance.Type, instance.Value, compareValue) <= 0); return true; case ExpressionType.Add: case ExpressionType.AddAssign: case ExpressionType.Subtract: case ExpressionType.SubtractAssign: case ExpressionType.Multiply: case ExpressionType.MultiplyAssign: case ExpressionType.Divide: case ExpressionType.DivideAssign: if (Operation(binder.Operation, instance.Value, compareValue, out result)) { result = new JValue(result); return true; } break; } result = null; return false; } } int IComparable.CompareTo(object obj) { if (obj == null) return 1; object otherValue = (obj is JValue) ? ((JValue) obj).Value : obj; return Compare(_valueType, _value, otherValue); } /// <summary> /// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has these meanings: /// Value /// Meaning /// Less than zero /// This instance is less than <paramref name="obj"/>. /// Zero /// This instance is equal to <paramref name="obj"/>. /// Greater than zero /// This instance is greater than <paramref name="obj"/>. /// </returns> /// <exception cref="T:System.ArgumentException"> /// <paramref name="obj"/> is not the same type as this instance. /// </exception> public int CompareTo(JValue obj) { if (obj == null) return 1; return Compare(_valueType, _value, obj._value); } } } #endif
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using UnityEngine; using Memoria; using Memoria.Data; using Memoria.Prime; using Memoria.Assets; using Object = System.Object; using System.Net.Mime; using Assets.Sources.Scripts.UI.Common; public static class AssetManager { /* New system for Memoria: 1) Assets can be read from mod folders (defined in Memoria.Configuration.Mod) - They can be either read from bundle archives or as plain non-archived files - Assets in non-bundle archives (typically "resources.assets", but also all the "levelX" and "sharedassetsX.assets") can currently only be read as plain files when they are in a mod's folder - They are read in priority from the first mod's folder up to the last mod's folder, then from the default folder - Bundle archives should be placed directly in the mod's folder - Plain files should be placed in a subfolder of the mod's folder respecting the asset's access path (eg. "EmbeddedAsset/Manifest/Text/Localization.txt") - Only assets of certain types can be read as plain files currently: binary (TextAsset), text (TextAsset), textures (Texture / Texture2D / Sprite / UIAtlas) and animations (AnimationClip) - Texture files that are not in archives should be placed as PNG or JPG files, not DXT-compressed files or using Unity's format - Assets that are not present in the mod folders must be archived as normally in the default folder 2) Any asset that is not archived can use a "Memoria information" file which is a text file placed in the same subfolder as the asset, with the same name and the extension "AssetManager.MemoriaInfoExtension" (".memnfo"); the purpose of these files may vary from type to type - For textures, they can define different properties of the texture that are usually in the Unity-formatted assets, such as the anisotropic level (see "AssetManager.ApplyTextureGenericMemoriaInfo") - For sounds and musics, they can define or change different properties, such as the LoopStart/LoopEnd frame points (see "SoundLoaderResources.Load") - For battle scene binary files (".raw16"), they can give battle properties as textual informations, which can be useful for adding custom properties to Memoria or go beyond binary max limits (see "BTL_SCENE.ReadBattleScene") - Etc... [To be completed] - The idea behind these files is that they should be optional (non-modded assets don't need them) and allow to use asset-specific special features without forcing other mods to take these features into account (for explicitely disabling them for instance) */ static AssetManager() { Array values = Enum.GetValues(typeof(AssetManagerUtil.ModuleBundle)); String[] foldname = new String[Configuration.Mod.FolderNames.Length + 1]; String url; for (Int32 i = 0; i < (Int32)Configuration.Mod.FolderNames.Length; ++i) foldname[i] = Configuration.Mod.FolderNames[i] + "/"; foldname[Configuration.Mod.FolderNames.Length] = ""; Folder = new AssetFolder[foldname.Length]; for (Int32 i = 0; i < (Int32)foldname.Length; ++i) { Folder[i] = new AssetFolder(foldname[i]); foreach (Object obj in values) { AssetManagerUtil.ModuleBundle moduleBundle = (AssetManagerUtil.ModuleBundle)((Int32)obj); if (moduleBundle == AssetManagerUtil.ModuleBundle.FieldMaps) { Array values2 = Enum.GetValues(typeof(AssetManagerUtil.FieldMapBundleId)); foreach (Object obj2 in values2) { AssetManagerUtil.FieldMapBundleId bundleId = (AssetManagerUtil.FieldMapBundleId)((Int32)obj2); url = foldname[i] + AssetManagerUtil.GetStreamingAssetsPath() + "/" + AssetManagerUtil.CreateFieldMapBundleFilename(Application.platform, false, bundleId); if (File.Exists(url)) Folder[i].DictAssetBundleRefs.Add(AssetManagerUtil.GetFieldMapBundleName(bundleId), new AssetBundleRef(url, 0)); } } else if (moduleBundle == AssetManagerUtil.ModuleBundle.Sounds) { Array values3 = Enum.GetValues(typeof(AssetManagerUtil.SoundBundleId)); foreach (Object obj3 in values3) { AssetManagerUtil.SoundBundleId bundleId2 = (AssetManagerUtil.SoundBundleId)((Int32)obj3); url = foldname[i] + AssetManagerUtil.GetStreamingAssetsPath() + "/" + AssetManagerUtil.CreateSoundBundleFilename(Application.platform, false, bundleId2); if (File.Exists(url)) Folder[i].DictAssetBundleRefs.Add(AssetManagerUtil.GetSoundBundleName(bundleId2), new AssetBundleRef(url, 0)); } } else { url = foldname[i] + AssetManagerUtil.GetStreamingAssetsPath() + "/" + AssetManagerUtil.CreateModuleBundleFilename(Application.platform, false, moduleBundle); if (File.Exists(url)) Folder[i].DictAssetBundleRefs.Add(AssetManagerUtil.GetModuleBundleName(moduleBundle), new AssetBundleRef(url, 0)); } } } _LoadAnimationFolderMapping(); } private static void _LoadAnimationFolderMapping() { _animationInFolder = new Dictionary<String, List<String>>(); _animationReverseFolder = new Dictionary<String, String>(); String filestr = LoadString("EmbeddedAsset/Manifest/Animations/AnimationFolderMapping.txt", out _); if (filestr == null) { return; } String[] folderList = filestr.Split(new Char[] { '\n' }); for (Int32 i = 0; i < (Int32)folderList.Length; i++) { String folderFull = folderList[i]; String[] geoAndAnim = folderFull.Split(new Char[] { ':' }); String geoFolder = geoAndAnim[0]; String modelName = Path.GetFileNameWithoutExtension(geoFolder); String[] animList = geoAndAnim[1].Split(new Char[] { ',' }); List<String> animFolderList = new List<String>(); for (Int32 j = 0; j < (Int32)animList.Length; j++) { String animName = animList[j].Trim(); String animFolder = geoFolder + "/" + animName; animFolder = animFolder.Trim(); animFolderList.Add(animFolder); _animationReverseFolder[animName] = modelName; } _animationInFolder.Add(geoFolder, animFolderList); } } public static void ClearCache() { Caching.CleanCache(); foreach (AssetFolder modfold in Folder) foreach (KeyValuePair<String, AssetBundleRef> keyValuePair in modfold.DictAssetBundleRefs) { AssetBundleRef value = keyValuePair.Value; if (value.assetBundle != (UnityEngine.Object)null) { value.assetBundle.Unload(true); value.assetBundle = (AssetBundle)null; } } } /* public static Byte[] LoadBinary(String resourcePath) { // By default, this method is only used for Localization.txt for a subsequent ByteReader.ReadCSV call // We delete it and use LoadBytes instead TextAsset textAsset = Resources.Load<TextAsset>(resourcePath); if (textAsset == null) throw new FileNotFoundException(resourcePath); return textAsset.bytes; } */ public static void ApplyTextureGenericMemoriaInfo<T>(ref T texture, ref String[] memoriaInfo) where T : UnityEngine.Texture { // Maybe remove the successfully parsed lines from the "info" array? foreach (String s in memoriaInfo) { String[] textureCode = s.Split(' '); if (textureCode.Length >= 2 && String.Compare(textureCode[0], "AnisotropicLevel") == 0) { Int32 anisoLevel; if (Int32.TryParse(textureCode[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out anisoLevel) && anisoLevel >= 1 && anisoLevel <= 9) texture.anisoLevel = anisoLevel; } else if (textureCode.Length >= 2 && String.Compare(textureCode[0], "FilterMode") == 0) { foreach (FilterMode m in (FilterMode[]) Enum.GetValues(typeof(FilterMode))) if (String.Compare(textureCode[1], m.ToString()) == 0) texture.filterMode = m; } else if(textureCode.Length >= 2 && String.Compare(textureCode[0], "HideFlags") == 0) { foreach (HideFlags f in (HideFlags[]) Enum.GetValues(typeof(HideFlags))) if (String.Compare(textureCode[1], f.ToString()) == 0) texture.hideFlags = f; } else if(textureCode.Length >= 2 && String.Compare(textureCode[0], "MipMapBias") == 0) { Single mipMapBias; if (Single.TryParse(textureCode[1], out mipMapBias)) texture.mipMapBias = mipMapBias; } else if(textureCode.Length >= 2 && String.Compare(textureCode[0], "WrapMode") == 0) { foreach (TextureWrapMode m in (TextureWrapMode[]) Enum.GetValues(typeof(TextureWrapMode))) if (String.Compare(textureCode[1], m.ToString()) == 0) texture.wrapMode = m; } } } public static Boolean IsTextureFormatReadableFromBytes(TextureFormat format) { // Todo: verify which TextureFormat are compatible with LoadRawTextureData return format == TextureFormat.Alpha8 || format == TextureFormat.RGB24 || format == TextureFormat.RGBA32 || format == TextureFormat.ARGB32 || format == TextureFormat.RGB565 || format == TextureFormat.DXT1 || format == TextureFormat.DXT5; } public static Texture2D LoadTextureGeneric(Byte[] raw) { const UInt32 DDS_HEADER_SIZE = 0x3C; if (raw.Length >= DDS_HEADER_SIZE) { UInt32 w = BitConverter.ToUInt32(raw, 0); UInt32 h = BitConverter.ToUInt32(raw, 4); UInt32 imgSize = BitConverter.ToUInt32(raw, 8); TextureFormat fmt = (TextureFormat)BitConverter.ToUInt32(raw, 12); UInt32 mipCount = BitConverter.ToUInt32(raw, 16); // UInt32 flags = BitConverter.ToUInt32(raw, 20); // 1 = isReadable (for use of GetPixels); 0x100 is usually on // UInt32 imageCount = BitConverter.ToUInt32(raw, 24); // UInt32 dimension = BitConverter.ToUInt32(raw, 28); // UInt32 filterMode = BitConverter.ToUInt32(raw, 32); // UInt32 anisotropic = BitConverter.ToUInt32(raw, 36); // UInt32 mipBias = BitConverter.ToUInt32(raw, 40); // UInt32 wrapMode = BitConverter.ToUInt32(raw, 44); // UInt32 lightmapFormat = BitConverter.ToUInt32(raw, 48); // UInt32 colorSpace = BitConverter.ToUInt32(raw, 52); // UInt32 imgSize = BitConverter.ToUInt32(raw, 56); if (raw.Length == DDS_HEADER_SIZE + imgSize && IsTextureFormatReadableFromBytes(fmt)) { Byte[] imgBytes = new Byte[imgSize]; Buffer.BlockCopy(raw, (Int32)DDS_HEADER_SIZE, imgBytes, 0, (Int32)imgSize); Texture2D ddsTexture = new Texture2D((Int32)w, (Int32)h, fmt, mipCount > 1); ddsTexture.LoadRawTextureData(imgBytes); ddsTexture.Apply(); return ddsTexture; } } Texture2D pngTexture = new Texture2D(1, 1, DefaultTextureFormat, false); if (pngTexture.LoadImage(raw)) return pngTexture; return null; } public static T LoadFromDisc<T>(String name, ref String[] memoriaInfo, String archiveName) { /* Types used by the game by default: * TextAsset (many, both text and binaries, including sounds and musics) - Use LoadString / LoadBytes instead * Texture2D (LoadAsync is used in MBG) - Can be read as PNG/JPG * Texture (only used by ModelFactory for "GEO_MAIN_F3_ZDN", "GEO_MAIN_F4_ZDN" and "GEO_MAIN_F5_ZDN") - Can be read as PNG/JPG as Texture2D * RenderTexture (Usually split into many pieces) - Can't be read from disc currently * Material - Can't be read from disc currently * AnimationClip (LoadAll is used in AnimationFactory) - Can be read as .anim (serialized format, as in the p0data5.bin) or JSON but with simple readers * GameObject (Usually split into many pieces ; LoadAsync is used in WMWorld) - Can't be read from disc currently */ if (typeof(T) == typeof(String)) { return (T)(Object)File.ReadAllText(name); } else if (typeof(T) == typeof(Byte[])) { return (T)(Object)File.ReadAllBytes(name); } else if (typeof(T) == typeof(Texture2D) || typeof(T) == typeof(Texture)) { Byte[] raw = File.ReadAllBytes(name); Texture2D newTexture = LoadTextureGeneric(raw); if (newTexture == null) newTexture = new Texture2D(1, 1, DefaultTextureFormat, false); ApplyTextureGenericMemoriaInfo<Texture2D>(ref newTexture, ref memoriaInfo); return (T)(Object)newTexture; } else if (typeof(T) == typeof(Sprite)) { Byte[] raw = File.ReadAllBytes(name); Texture2D newTexture = LoadTextureGeneric(raw); if (newTexture == null) newTexture = new Texture2D(1, 1, DefaultTextureFormat, false); ApplyTextureGenericMemoriaInfo<Texture2D>(ref newTexture, ref memoriaInfo); Sprite newSprite = Sprite.Create(newTexture, new Rect(0, 0, newTexture.width, newTexture.height), new Vector2(0.5f, 0.5f)); return (T)(Object)newSprite; } else if (typeof(T) == typeof(UIAtlas)) { // Todo: Maybe avoid the call of Resources.Load<UIAtlas> if a complete .tpsheet is available and it's not necessary to get the original's sprite list UIAtlas newAtlas = Resources.Load<UIAtlas>(archiveName); if (newAtlas != null) newAtlas.ReadFromDisc(name); else Log.Message("[AssetManager] Embeded asset not found: " + archiveName); return (T)(Object)newAtlas; } else if (typeof(T) == typeof(AnimationClip)) { return (T)(Object)AnimationClipReader.ReadAnimationClipFromDisc(name); } Log.Message("[AssetManager] Trying to load from disc the asset " + name + " of type " + typeof(T).ToString() + ", which is not currently possible"); return (T)(Object)null; } public static T Load<T>(String name, out String[] info, Boolean suppressMissingError = false) where T : UnityEngine.Object { String infoFileName = Path.ChangeExtension(name, MemoriaInfoExtension); info = new String[0]; T result; if (AssetManagerForObb.IsUseOBB) return AssetManagerForObb.Load<T>(name, suppressMissingError); if (AssetManagerUtil.IsMemoriaAssets(name)) { foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + name)) { if (File.Exists(modfold.FolderPath + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + infoFileName); return LoadFromDisc<T>(modfold.FolderPath + name, ref info, name); } if (File.Exists(name)) { if (File.Exists(infoFileName)) info = File.ReadAllLines(infoFileName); return LoadFromDisc<T>(name, ref info, name); } if (!suppressMissingError) Log.Message("[AssetManager] Memoria asset not found: " + name); return null; } if (!UseBundles || AssetManagerUtil.IsEmbededAssets(name)) { foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name)) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName); return LoadFromDisc<T>(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name, ref info, name); } result = Resources.Load<T>(name); if (result == (UnityEngine.Object)null && !suppressMissingError) Log.Message("[AssetManager] Embeded asset not found: " + name); return result; } String belongingBundleFilename = AssetManagerUtil.GetBelongingBundleFilename(name); if (!String.IsNullOrEmpty(belongingBundleFilename)) { String nameInBundle = AssetManagerUtil.GetResourcesBasePath() + name + AssetManagerUtil.GetAssetExtension<T>(name); foreach (AssetFolder modfold in Folder) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + nameInBundle)) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + AssetManagerUtil.GetResourcesBasePath() + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + AssetManagerUtil.GetResourcesBasePath() + infoFileName); return LoadFromDisc<T>(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + nameInBundle, ref info, nameInBundle); } AssetBundleRef assetBundleRef = null; modfold.DictAssetBundleRefs.TryGetValue(belongingBundleFilename, out assetBundleRef); if (assetBundleRef != null && assetBundleRef.assetBundle != (UnityEngine.Object)null) { result = assetBundleRef.assetBundle.LoadAsset<T>(nameInBundle); if (result != (UnityEngine.Object)null) { return result; } } } } if (ForceUseBundles) return (T)((Object)null); foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name)) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName); return LoadFromDisc<T>(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name, ref info, name); } result = Resources.Load<T>(name); if (result == (UnityEngine.Object)null && !suppressMissingError) Log.Message("[AssetManager] Asset not found: " + name); return result; } public static String LoadString(String name, out String[] info, Boolean suppressMissingError = false) { String infoFileName = Path.ChangeExtension(name, MemoriaInfoExtension); TextAsset txt = null; info = new String[0]; if (AssetManagerForObb.IsUseOBB) { txt = AssetManagerForObb.Load<TextAsset>(name, suppressMissingError); if (txt != (UnityEngine.Object)null) return txt.text; return null; } if (AssetManagerUtil.IsMemoriaAssets(name)) { foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + name)) { if (File.Exists(modfold.FolderPath + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + infoFileName); return LoadFromDisc<String>(modfold.FolderPath + name, ref info, name); } if (File.Exists(name)) { if (File.Exists(infoFileName)) info = File.ReadAllLines(infoFileName); return LoadFromDisc<String>(name, ref info, name); } if (!suppressMissingError) Log.Message("[AssetManager] Memoria asset not found: " + name); return null; } if (!UseBundles || AssetManagerUtil.IsEmbededAssets(name)) { foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name)) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName); return LoadFromDisc<String>(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name, ref info, name); } txt = Resources.Load<TextAsset>(name); if (txt != (UnityEngine.Object)null) return txt.text; if (!suppressMissingError) Log.Message("[AssetManager] Embeded asset not found: " + name); return null; } String belongingBundleFilename = AssetManagerUtil.GetBelongingBundleFilename(name); if (!String.IsNullOrEmpty(belongingBundleFilename)) { String nameInBundle = AssetManagerUtil.GetResourcesBasePath() + name + AssetManagerUtil.GetAssetExtension<TextAsset>(name); foreach (AssetFolder modfold in Folder) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + nameInBundle)) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + AssetManagerUtil.GetResourcesBasePath() + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + AssetManagerUtil.GetResourcesBasePath() + infoFileName); return LoadFromDisc<String>(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + nameInBundle, ref info, nameInBundle); } AssetBundleRef assetBundleRef = null; modfold.DictAssetBundleRefs.TryGetValue(belongingBundleFilename, out assetBundleRef); if (assetBundleRef != null && assetBundleRef.assetBundle != (UnityEngine.Object)null) { txt = assetBundleRef.assetBundle.LoadAsset<TextAsset>(nameInBundle); if (txt != (UnityEngine.Object)null) return txt.text; } } } if (ForceUseBundles) return null; foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name)) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName); return LoadFromDisc<String>(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name, ref info, name); } txt = Resources.Load<TextAsset>(name); if (txt != (UnityEngine.Object)null) return txt.text; if (!suppressMissingError) Log.Message("[AssetManager] Asset not found: " + name); return null; } public static Byte[] LoadBytes(String name, out String[] info, Boolean suppressMissingError = false) { String infoFileName = Path.ChangeExtension(name, MemoriaInfoExtension); TextAsset txt = null; info = new String[0]; if (AssetManagerForObb.IsUseOBB) { txt = AssetManagerForObb.Load<TextAsset>(name, suppressMissingError); if (txt != (UnityEngine.Object)null) return txt.bytes; return null; } if (AssetManagerUtil.IsMemoriaAssets(name)) { foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + name)) { if (File.Exists(modfold.FolderPath + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + infoFileName); return LoadFromDisc<Byte[]>(modfold.FolderPath + name, ref info, name); } if (File.Exists(name)) { if (File.Exists(infoFileName)) info = File.ReadAllLines(infoFileName); return LoadFromDisc<Byte[]>(name, ref info, name); } if (!suppressMissingError) Log.Message("[AssetManager] Memoria asset not found: " + name); return null; } if (!UseBundles || AssetManagerUtil.IsEmbededAssets(name)) { foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name)) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName); return LoadFromDisc<Byte[]>(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name, ref info, name); } txt = Resources.Load<TextAsset>(name); if (txt != (UnityEngine.Object)null) return txt.bytes; if (!suppressMissingError) Log.Message("[AssetManager] Embeded asset not found: " + name); return null; } String belongingBundleFilename = AssetManagerUtil.GetBelongingBundleFilename(name); if (!String.IsNullOrEmpty(belongingBundleFilename)) { String nameInBundle = AssetManagerUtil.GetResourcesBasePath() + name + AssetManagerUtil.GetAssetExtension<TextAsset>(name); foreach (AssetFolder modfold in Folder) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + nameInBundle)) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + AssetManagerUtil.GetResourcesBasePath() + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + AssetManagerUtil.GetResourcesBasePath() + infoFileName); return LoadFromDisc<Byte[]>(modfold.FolderPath + AssetManagerUtil.GetStreamingAssetsPath() + "/" + nameInBundle, ref info, nameInBundle); } AssetBundleRef assetBundleRef = null; modfold.DictAssetBundleRefs.TryGetValue(belongingBundleFilename, out assetBundleRef); if (assetBundleRef != null && assetBundleRef.assetBundle != (UnityEngine.Object)null) { txt = assetBundleRef.assetBundle.LoadAsset<TextAsset>(nameInBundle); if (txt != (UnityEngine.Object)null) return txt.bytes; } } } if (ForceUseBundles) return null; foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name)) { if (File.Exists(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName)) info = File.ReadAllLines(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + infoFileName); return LoadFromDisc<Byte[]>(modfold.FolderPath + AssetManagerUtil.GetResourcesAssetsPath(true) + "/" + name, ref info, name); } txt = Resources.Load<TextAsset>(name); if (txt != (UnityEngine.Object)null) return txt.bytes; if (!suppressMissingError) Log.Message("[AssetManager] Asset not found: " + name); return null; } public static AssetManagerRequest LoadAsync<T>(String name) where T : UnityEngine.Object { if (AssetManagerForObb.IsUseOBB) return AssetManagerForObb.LoadAsync<T>(name); if (!UseBundles || AssetManagerUtil.IsEmbededAssets(name)) { ResourceRequest resourceRequest = Resources.LoadAsync<T>(name); if (resourceRequest != null) return new AssetManagerRequest(resourceRequest, (AssetBundleRequest)null); } String belongingBundleFilename = AssetManagerUtil.GetBelongingBundleFilename(name); if (!String.IsNullOrEmpty(belongingBundleFilename)) { String nameInBundle = AssetManagerUtil.GetResourcesBasePath() + name + AssetManagerUtil.GetAssetExtension<T>(name); foreach (AssetFolder modfold in Folder) { AssetBundleRef assetBundleRef = null; modfold.DictAssetBundleRefs.TryGetValue(belongingBundleFilename, out assetBundleRef); if (assetBundleRef != null && assetBundleRef.assetBundle != (UnityEngine.Object)null) { AssetBundleRequest assetBundleRequest = assetBundleRef.assetBundle.LoadAssetAsync(nameInBundle); if (assetBundleRequest != null) return new AssetManagerRequest((ResourceRequest)null, assetBundleRequest); } } } if (ForceUseBundles) return (AssetManagerRequest)null; ResourceRequest resourceRequest2 = Resources.LoadAsync<T>(name); if (resourceRequest2 != null) return new AssetManagerRequest(resourceRequest2, (AssetBundleRequest)null); Log.Message("[AssetManager] Asset not found: " + name); return (AssetManagerRequest)null; } public static String SearchAssetOnDisc(String name, Boolean includeAssetPath, Boolean includeAssetExtension) { if (!UseBundles || AssetManagerUtil.IsEmbededAssets(name)) { foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + (includeAssetPath ? AssetManagerUtil.GetResourcesAssetsPath(true) + "/" : "") + name)) return modfold.FolderPath + (includeAssetPath ? AssetManagerUtil.GetResourcesAssetsPath(true) + "/" : "") + name; return String.Empty; } String belongingBundleFilename = AssetManagerUtil.GetBelongingBundleFilename(name); if (!String.IsNullOrEmpty(belongingBundleFilename)) { String nameInBundle = (includeAssetPath ? AssetManagerUtil.GetStreamingAssetsPath() + "/" + AssetManagerUtil.GetResourcesBasePath() : "") + name + (includeAssetExtension ? AssetManagerUtil.GetAssetExtension<TextAsset>(name) : ""); foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + nameInBundle)) return modfold.FolderPath + nameInBundle; } if (ForceUseBundles) return String.Empty; foreach (AssetFolder modfold in Folder) if (File.Exists(modfold.FolderPath + (includeAssetPath ? AssetManagerUtil.GetResourcesAssetsPath(true) : "") + "/" + name)) return modfold.FolderPath + (includeAssetPath ? AssetManagerUtil.GetResourcesAssetsPath(true) : "") + "/" + name; return String.Empty; } public static T[] LoadAll<T>(String name) where T : UnityEngine.Object { if (AssetManagerForObb.IsUseOBB) { return AssetManagerForObb.LoadAll<T>(name); } if (typeof(T) != typeof(AnimationClip)) { return null; } if (!UseBundles) { name = AnimationFactory.GetRenameAnimationDirectory(name); return Resources.LoadAll<T>(name); } if (_animationInFolder.ContainsKey(name)) { List<String> list = _animationInFolder[name]; T[] array = new T[list.Count]; for (Int32 i = 0; i < list.Count; i++) { String renameAnimationPath = AnimationFactory.GetRenameAnimationPath(list[i]); array[i] = Load<T>(renameAnimationPath, out _, false); AnimationClip clip = array[i] as AnimationClip; if (clip != null) { if (String.Compare(clip.name, "CUSTOM_MUST_RENAME") == 0) clip.name = Path.GetFileNameWithoutExtension(list[i]); } } return array; } return null; } public static void PatchDictionaries(String[] patchCode) { // This method might go somewhere else... foreach (String s in patchCode) { String[] entry = s.Split(' '); if (entry.Length < 3) continue; if (String.Compare(entry[0], "MessageFile") == 0) { // eg.: MessageFile 2000 MES_CUSTOM_PLACE if (FF9DBAll.MesDB == null) continue; Int32 ID; if (!Int32.TryParse(entry[1], out ID)) continue; FF9DBAll.MesDB[ID] = entry[2]; } else if (String.Compare(entry[0], "IconSprite") == 0) { // eg.: IconSprite 19 arrow_down if (FF9UIDataTool.IconSpriteName == null) continue; Int32 ID; if (!Int32.TryParse(entry[1], out ID)) continue; FF9UIDataTool.IconSpriteName[ID] = entry[2]; } else if (String.Compare(entry[0], "DebuffIcon") == 0) { // eg.: DebuffIcon 0 188 // or : DebuffIcon 0 ability_stone if (BattleHUD.DebuffIconNames == null) continue; Int32 ID, iconID; if (!Int32.TryParse(entry[1], out ID)) continue; if (Int32.TryParse(entry[2], out iconID)) { if (!FF9UIDataTool.IconSpriteName.ContainsKey(iconID)) { Log.Message("[AssetManager.PatchDictionaries] Trying to use the invalid sprite index " + iconID + " for the icon of status " + ID); continue; } BattleHUD.DebuffIconNames[(BattleStatus)(1 << ID)] = FF9UIDataTool.IconSpriteName[iconID]; if (BattleResultUI.BadIconDict == null || FF9UIDataTool.status_id == null) continue; BattleResultUI.BadIconDict[(UInt32)(1 << ID)] = (Byte)iconID; if (ID < FF9UIDataTool.status_id.Length) FF9UIDataTool.status_id[ID] = iconID; // Todo: debuff icons in the main menus (status menu, items...) are UISprite components of CharacterDetailHUD and are enabled/disabled in FF9UIDataTool.DisplayCharacterDetail // Maybe add UISprite components at runtime? The width of the window may require adjustments then // By design (in FF9UIDataTool.DisplayCharacterDetail for instance), permanent debuffs must be the first ones of the list of statuses } else { BattleHUD.DebuffIconNames[(BattleStatus)(1 << ID)] = entry[2]; // When adding a debuff icon by sprite name, not all the dictionaries are updated } } else if (String.Compare(entry[0], "BuffIcon") == 0) { // eg.: BuffIcon 18 188 // or : BuffIcon 18 ability_stone if (BattleHUD.BuffIconNames == null) continue; Int32 ID, iconID; if (!Int32.TryParse(entry[1], out ID)) continue; if (Int32.TryParse(entry[2], out iconID)) { if (!FF9UIDataTool.IconSpriteName.ContainsKey(iconID)) { Log.Message("[AssetManager.PatchDictionaries] Trying to use the invalid sprite index " + iconID + " for the icon of status " + ID); continue; } BattleHUD.BuffIconNames[(BattleStatus)(1 << ID)] = FF9UIDataTool.IconSpriteName[iconID]; } else { BattleHUD.BuffIconNames[(BattleStatus)(1 << ID)] = entry[2]; } } else if (String.Compare(entry[0], "HalfTranceCommand") == 0) { // eg.: HalfTranceCommand Set DoubleWhiteMagic DoubleBlackMagic HolySword2 if (btl_cmd.half_trance_cmd_list == null) continue; Boolean add = String.Compare(entry[1], "Remove") != 0; if (String.Compare(entry[1], "Set") == 0) btl_cmd.half_trance_cmd_list.Clear(); for (Int32 i = 2; i < entry.Length; i++) foreach (BattleCommandId cmdid in (BattleCommandId[])Enum.GetValues(typeof(BattleCommandId))) if (String.Compare(entry[i], cmdid.ToString()) == 0) { if (add && !btl_cmd.half_trance_cmd_list.Contains(cmdid)) btl_cmd.half_trance_cmd_list.Add(cmdid); else if (!add) btl_cmd.half_trance_cmd_list.Remove(cmdid); break; } } else if (String.Compare(entry[0], "BattleMapModel") == 0) { // eg.: BattleMapModel BSC_CUSTOM_FIELD BBG_B065 // Can also be modified using "BattleScene" if (FF9BattleDB.MapModel == null) continue; FF9BattleDB.MapModel[entry[1]] = entry[2]; } else if (String.Compare(entry[0], "FieldScene") == 0 && entry.Length >= 6) { // eg.: FieldScene 4000 57 CUSTOM_FIELD CUSTOM_FIELD 2000 if (FF9DBAll.EventDB == null || EventEngineUtils.eventIDToFBGID == null || EventEngineUtils.eventIDToMESID == null) continue; Int32 ID, mesID, areaID; if (!Int32.TryParse(entry[1], out ID)) continue; if (!Int32.TryParse(entry[2], out areaID)) continue; if (!Int32.TryParse(entry[5], out mesID)) continue; if (!FF9DBAll.MesDB.ContainsKey(mesID)) { Log.Message("[AssetManager.PatchDictionaries] Trying to use the invalid message file ID " + mesID + " for the field map field scene " + entry[3] + " (" + ID + ")"); continue; } String fieldMapName = "FBG_N" + areaID + "_" + entry[3]; EventEngineUtils.eventIDToFBGID[ID] = fieldMapName; FF9DBAll.EventDB[ID] = "EVT_" + entry[4]; EventEngineUtils.eventIDToMESID[ID] = mesID; // p0data1X: // Assets/Resources/FieldMaps/{fieldMapName}/atlas.png // Assets/Resources/FieldMaps/{fieldMapName}/{fieldMapName}.bgi.bytes // Assets/Resources/FieldMaps/{fieldMapName}/{fieldMapName}.bgs.bytes // [Optional] Assets/Resources/FieldMaps/{fieldMapName}/spt.tcb.bytes // [Optional for each sps] Assets/Resources/FieldMaps/{fieldMapName}/{spsID}.sps.bytes // p0data7: // Assets/Resources/CommonAsset/EventEngine/EventBinary/Field/LANG/EVT_{entry[4]}.eb.bytes // [Optional] Assets/Resources/CommonAsset/EventEngine/EventAnimation/EVT_{entry[4]}.txt.bytes // [Optional] Assets/Resources/CommonAsset/MapConfigData/EVT_{entry[4]}.bytes // [Optional] Assets/Resources/CommonAsset/VibrationData/EVT_{entry[4]}.bytes } else if (String.Compare(entry[0], "BattleScene") == 0 && entry.Length >= 4) { // eg.: BattleScene 5000 CUSTOM_BATTLE BBG_B065 if (FF9DBAll.EventDB == null || FF9BattleDB.SceneData == null || FF9BattleDB.MapModel == null) continue; Int32 ID; if (!Int32.TryParse(entry[1], out ID)) continue; FF9DBAll.EventDB[ID] = "EVT_BATTLE_" + entry[2]; FF9BattleDB.SceneData["BSC_" + entry[2]] = ID; FF9BattleDB.MapModel["BSC_" + entry[2]] = entry[3]; // p0data2: // Assets/Resources/BattleMap/BattleScene/EVT_BATTLE_{entry[2]}/{ID}.raw17.bytes // Assets/Resources/BattleMap/BattleScene/EVT_BATTLE_{entry[2]}/dbfile0000.raw16.bytes // p0data7: // Assets/Resources/CommonAsset/EventEngine/EventBinary/Battle/{Lang}/EVT_BATTLE_{entry[2]}.eb.bytes // resources: // EmbeddedAsset/Text/{Lang}/Battle/{ID}.mes } else if (String.Compare(entry[0], "CharacterDefaultName") == 0 && entry.Length >= 4) { // eg.: CharacterDefaultName 0 US Zinedine // REMARK: Character default names can also be changed with the option "[Import] Text = 1" although it would monopolise the whole machinery of text importing // "[Import] Text = 1" has the priority over DictionaryPatch if (CharacterNamesFormatter._characterNames == null) continue; Int32 ID; if (!Int32.TryParse(entry[1], out ID)) continue; String[] nameArray; if (!CharacterNamesFormatter._characterNames.TryGetValue(entry[2], out nameArray)) nameArray = new String[ID + 1]; if (nameArray.Length <= ID) { nameArray = new String[ID + 1]; CharacterNamesFormatter._characterNames[entry[2]].CopyTo(nameArray, 0); } nameArray[ID] = String.Join(" ", entry, 3, entry.Length - 3); // Character names can't have spaces now and are max 8 char long, so there's no real point in joining instead of using entry[3] directly CharacterNamesFormatter._characterNames[entry[2]] = nameArray; } else if (String.Compare(entry[0], "3DModel") == 0) { // For both field models and enemy battle models (+ animations) // eg.: // 3DModel 98 GEO_NPC_F0_RMF // 3DModelAnimation 200 ANH_NPC_F0_RMF_IDLE // 3DModelAnimation 25 ANH_NPC_F0_RMF_WALK // 3DModelAnimation 38 ANH_NPC_F0_RMF_RUN // 3DModelAnimation 40 ANH_NPC_F0_RMF_TURN_L // 3DModelAnimation 41 ANH_NPC_F0_RMF_TURN_R // 3DModelAnimation 54 55 56 57 59 ANH_NPC_F0_RMF_ANGRY_INN if (FF9BattleDB.GEO == null) continue; Int32 idcount = entry.Length - 2; Int32[] ID = new Int32[entry.Length-2]; Boolean formatOK = true; for (Int32 idindex = 0; formatOK && idindex < idcount; ++idindex) if (!Int32.TryParse(entry[idindex + 1], out ID[idindex])) formatOK = false; if (!formatOK) continue; for (Int32 idindex = 0; formatOK && idindex < idcount; ++idindex) { FF9BattleDB.GEO[ID[idindex]] = entry[entry.Length - 1]; } // TODO: make it work for replacing battle weapon models // Currently, a line like "3DModel 476 GEO_ACC_F0_OPB" for replacing the dagger by a book freezes the game on black screen when battle starts } else if (String.Compare(entry[0], "3DModelAnimation") == 0) { // eg.: See above // When adding custom animations, the name must follow the following pattern: // ANH_[MODEL TYPE]_[MODEL VERSION]_[MODEL 3 LETTER CODE]_[WHATEVER] // in such a way that the model's name GEO_[...] and its new animation ANH_[...] have the middle block in common in their name // Then that custom animation's file must be placed in that model's animation folder // (eg. "assets/resources/animations/98/100000.anim" for a custom animation of Zidane with ID 100000) if (FF9DBAll.AnimationDB == null || FF9BattleDB.Animation == null) continue; Int32 idcount = entry.Length - 2; Int32[] ID = new Int32[entry.Length - 2]; Boolean formatOK = true; for (Int32 idindex = 0; formatOK && idindex < idcount; ++idindex) if (!Int32.TryParse(entry[idindex + 1], out ID[idindex])) formatOK = false; if (!formatOK) continue; for (Int32 idindex = 0; formatOK && idindex < idcount; ++idindex) { FF9DBAll.AnimationDB[ID[idindex]] = entry[entry.Length - 1]; FF9BattleDB.Animation[ID[idindex]] = entry[entry.Length - 1]; } } else if (String.Compare(entry[0], "PlayerBattleModel") == 0 && entry.Length >= 39) { // For party battle models and animations // Check btl_mot's note for the sorting of battle animations // eg.: // 3DModelAnimation 100000 ANH_SUB_F0_KJA_MYCUSTOM_ANIM // PlayerBattleModel 0 GEO_SUB_F0_KJA GEO_SUB_F0_KJA 18 // ANH_SUB_F0_KJA_ARMS_CROSS_2_2 ANH_SUB_F0_KJA_ARMS_CROSS_2_2 ANH_MON_B3_125_003 ANH_MON_B3_125_040 // ANH_SUB_F0_KJA_DOWN ANH_SUB_F0_KJA_ARMS_CROSS_2_2 ANH_SUB_F0_KJA_ARMS_CROSS_2_2 ANH_SUB_F0_KJA_MYCUSTOM_ANIM // ANH_SUB_F0_KJA_DOWN ANH_SUB_F0_KJA_IDLE ANH_SUB_F0_KJA_ARMS_CROSS_2_3 ANH_SUB_F0_KJA_ARMS_CROSS_2_2 // ANH_SUB_F0_KJA_SHOW_OFF_1_1 ANH_SUB_F0_KJA_SHOW_OFF_1_2 ANH_SUB_F0_KJA_SHOW_OFF_1_3 // ANH_MON_B3_125_021 ANH_SUB_F0_KJA_LAUGH_2_2 ANH_SUB_F0_KJA_SHOW_OFF_2_2 // ANH_SUB_F0_KJA_OJIGI_1 ANH_SUB_F0_KJA_OJIGI_2 // ANH_SUB_F0_KJA_GET_HSK_1 ANH_SUB_F0_KJA_GET_HSK_2 ANH_SUB_F0_KJA_GET_HSK_2 ANH_SUB_F0_KJA_GET_HSK_3 ANH_SUB_F0_KJA_ARMS_CROSS_2_2 ANH_SUB_F0_KJA_ARMS_CROSS_2_2 // ANH_MON_B3_125_020 ANH_MON_B3_125_021 ANH_MON_B3_125_022 // ANH_SUB_F0_KJA_WALK ANH_SUB_F0_KJA_WALK ANH_SUB_F0_KJA_RAIN_1 // ANH_SUB_F0_KJA_ARMS_CROSS_2_1 ANH_SUB_F0_KJA_ARMS_UP_KUBIFURI_2 // (in a single line) if (FF9.btl_mot.mot == null || BattlePlayerCharacter.PlayerModelFileName == null || btl_init.model_id == null) continue; Int32 ID; Byte boneID; if (!Int32.TryParse(entry[1], out ID)) continue; if (!Byte.TryParse(entry[4], out boneID)) continue; if (ID < 0 || ID >= 19) // Replace only existing characters continue; BattlePlayerCharacter.PlayerModelFileName[ID] = entry[2]; // Model btl_init.model_id[ID] = entry[2]; btl_init.model_id[ID + 19] = entry[3]; // Trance model BattlePlayerCharacter.PlayerWeaponToBoneName[ID] = boneID; // Model's weapon bone for (Int32 animid = 0; animid < 34; ++animid) FF9.btl_mot.mot[ID, animid] = entry[animid + 5]; List<String> modelAnimList; String animlistID = "Animations/" + entry[2]; String animID, animModelID; if (!_animationInFolder.TryGetValue(animlistID, out modelAnimList)) modelAnimList = new List<String>(); for (Int32 animid = 0; animid < 34; ++animid) { if (!_animationReverseFolder.TryGetValue(entry[animid + 5], out animModelID)) // Animation registered in "AnimationFolderMapping.txt": use ID of registered model animModelID = entry[2]; // Custom animation: the path is "Animation/[ID of battle model]/[Anim ID]" animID = "Animations/" + animModelID + "/" + entry[animid + 5]; if (!modelAnimList.Contains(animID)) { modelAnimList.Add(animID); _animationReverseFolder[entry[animid + 5]] = animModelID; } } _animationInFolder[animlistID] = modelAnimList; } } } public const String MemoriaInfoExtension = ".memnfo"; public const String MemoriaDictionaryPatcherPath = "DictionaryPatch.txt"; public const TextureFormat DefaultTextureFormat = TextureFormat.ARGB32; public static Boolean UseBundles; public static Boolean ForceUseBundles; public static AssetFolder[] Folder; private static Dictionary<String, List<String>> _animationInFolder; private static Dictionary<String, String> _animationReverseFolder; public class AssetBundleRef { public AssetBundleRef(String strUrl, Int32 intVersionIn) { this.fullUrl = strUrl; this.version = intVersionIn; } public AssetBundle assetBundle; public Int32 version; public String fullUrl; } public class AssetFolder { public AssetFolder(String path) { this.FolderPath = path; this.DictAssetBundleRefs = new Dictionary<String, AssetBundleRef>(); } public String FolderPath; public Dictionary<String, AssetBundleRef> DictAssetBundleRefs; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Data.SqlTypes; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Transactions; namespace System.Data.Common { internal static partial class ADP { // The class ADP defines the exceptions that are specific to the Adapters. // The class contains functions that take the proper informational variables and then construct // the appropriate exception with an error string obtained from the resource framework. // The exception is then returned to the caller, so that the caller may then throw from its // location so that the catcher of the exception will have the appropriate call stack. // This class is used so that there will be compile time checking of error messages. internal static Exception ExceptionWithStackTrace(Exception e) { try { throw e; } catch (Exception caught) { return caught; } } // // COM+ exceptions // internal static IndexOutOfRangeException IndexOutOfRange(int value) { IndexOutOfRangeException e = new IndexOutOfRangeException(value.ToString(CultureInfo.InvariantCulture)); return e; } internal static IndexOutOfRangeException IndexOutOfRange() { IndexOutOfRangeException e = new IndexOutOfRangeException(); return e; } internal static TimeoutException TimeoutException(string error) { TimeoutException e = new TimeoutException(error); return e; } internal static InvalidOperationException InvalidOperation(string error, Exception inner) { InvalidOperationException e = new InvalidOperationException(error, inner); return e; } internal static OverflowException Overflow(string error) { return Overflow(error, null); } internal static OverflowException Overflow(string error, Exception inner) { OverflowException e = new OverflowException(error, inner); return e; } internal static PlatformNotSupportedException DbTypeNotSupported(string dbType) { PlatformNotSupportedException e = new PlatformNotSupportedException(SR.GetString(SR.SQL_DbTypeNotSupportedOnThisPlatform, dbType)); return e; } internal static InvalidCastException InvalidCast() { InvalidCastException e = new InvalidCastException(); return e; } internal static IOException IO(string error) { IOException e = new IOException(error); return e; } internal static IOException IO(string error, Exception inner) { IOException e = new IOException(error, inner); return e; } internal static ObjectDisposedException ObjectDisposed(object instance) { ObjectDisposedException e = new ObjectDisposedException(instance.GetType().Name); return e; } internal static Exception DataTableDoesNotExist(string collectionName) { return Argument(SR.GetString(SR.MDF_DataTableDoesNotExist, collectionName)); } internal static InvalidOperationException MethodCalledTwice(string method) { InvalidOperationException e = new InvalidOperationException(SR.GetString(SR.ADP_CalledTwice, method)); return e; } // IDbCommand.CommandType internal static ArgumentOutOfRangeException InvalidCommandType(CommandType value) { #if DEBUG switch (value) { case CommandType.Text: case CommandType.StoredProcedure: case CommandType.TableDirect: Debug.Assert(false, "valid CommandType " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(CommandType), (int)value); } // IDbConnection.BeginTransaction, OleDbTransaction.Begin internal static ArgumentOutOfRangeException InvalidIsolationLevel(IsolationLevel value) { #if DEBUG switch (value) { case IsolationLevel.Unspecified: case IsolationLevel.Chaos: case IsolationLevel.ReadUncommitted: case IsolationLevel.ReadCommitted: case IsolationLevel.RepeatableRead: case IsolationLevel.Serializable: case IsolationLevel.Snapshot: Debug.Fail("valid IsolationLevel " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(IsolationLevel), (int)value); } // IDataParameter.Direction internal static ArgumentOutOfRangeException InvalidParameterDirection(ParameterDirection value) { #if DEBUG switch (value) { case ParameterDirection.Input: case ParameterDirection.Output: case ParameterDirection.InputOutput: case ParameterDirection.ReturnValue: Debug.Assert(false, "valid ParameterDirection " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(ParameterDirection), (int)value); } internal static Exception TooManyRestrictions(string collectionName) { return Argument(SR.GetString(SR.MDF_TooManyRestrictions, collectionName)); } // IDbCommand.UpdateRowSource internal static ArgumentOutOfRangeException InvalidUpdateRowSource(UpdateRowSource value) { #if DEBUG switch (value) { case UpdateRowSource.None: case UpdateRowSource.OutputParameters: case UpdateRowSource.FirstReturnedRecord: case UpdateRowSource.Both: Debug.Assert(false, "valid UpdateRowSource " + value.ToString()); break; } #endif return InvalidEnumerationValue(typeof(UpdateRowSource), (int)value); } // // DbConnectionOptions, DataAccess // internal static ArgumentException InvalidMinMaxPoolSizeValues() { return ADP.Argument(SR.GetString(SR.ADP_InvalidMinMaxPoolSizeValues)); } // // DbConnection // internal static InvalidOperationException NoConnectionString() { return InvalidOperation(SR.GetString(SR.ADP_NoConnectionString)); } internal static Exception MethodNotImplemented([CallerMemberName] string methodName = "") { return NotImplemented.ByDesignWithMessage(methodName); } internal static Exception QueryFailed(string collectionName, Exception e) { return InvalidOperation(SR.GetString(SR.MDF_QueryFailed, collectionName), e); } // // : DbConnectionOptions, DataAccess, SqlClient // internal static Exception InvalidConnectionOptionValueLength(string key, int limit) { return Argument(SR.GetString(SR.ADP_InvalidConnectionOptionValueLength, key, limit)); } internal static Exception MissingConnectionOptionValue(string key, string requiredAdditionalKey) { return Argument(SR.GetString(SR.ADP_MissingConnectionOptionValue, key, requiredAdditionalKey)); } // // DbConnectionPool and related // internal static Exception PooledOpenTimeout() { return ADP.InvalidOperation(SR.GetString(SR.ADP_PooledOpenTimeout)); } internal static Exception NonPooledOpenTimeout() { return ADP.TimeoutException(SR.GetString(SR.ADP_NonPooledOpenTimeout)); } // // DbProviderException // internal static InvalidOperationException TransactionConnectionMismatch() { return Provider(SR.GetString(SR.ADP_TransactionConnectionMismatch)); } internal static InvalidOperationException TransactionRequired(string method) { return Provider(SR.GetString(SR.ADP_TransactionRequired, method)); } internal static Exception CommandTextRequired(string method) { return InvalidOperation(SR.GetString(SR.ADP_CommandTextRequired, method)); } internal static Exception NoColumns() { return Argument(SR.GetString(SR.MDF_NoColumns)); } internal static InvalidOperationException ConnectionRequired(string method) { return InvalidOperation(SR.GetString(SR.ADP_ConnectionRequired, method)); } internal static InvalidOperationException OpenConnectionRequired(string method, ConnectionState state) { return InvalidOperation(SR.GetString(SR.ADP_OpenConnectionRequired, method, ADP.ConnectionStateMsg(state))); } internal static Exception OpenReaderExists() { return OpenReaderExists(null); } internal static Exception OpenReaderExists(Exception e) { return InvalidOperation(SR.GetString(SR.ADP_OpenReaderExists), e); } // // DbDataReader // internal static Exception NonSeqByteAccess(long badIndex, long currIndex, string method) { return InvalidOperation(SR.GetString(SR.ADP_NonSeqByteAccess, badIndex.ToString(CultureInfo.InvariantCulture), currIndex.ToString(CultureInfo.InvariantCulture), method)); } internal static Exception InvalidXml() { return Argument(SR.GetString(SR.MDF_InvalidXml)); } internal static Exception NegativeParameter(string parameterName) { return InvalidOperation(SR.GetString(SR.ADP_NegativeParameter, parameterName)); } internal static Exception InvalidXmlMissingColumn(string collectionName, string columnName) { return Argument(SR.GetString(SR.MDF_InvalidXmlMissingColumn, collectionName, columnName)); } // // SqlMetaData, SqlTypes, SqlClient // internal static Exception InvalidMetaDataValue() { return ADP.Argument(SR.GetString(SR.ADP_InvalidMetaDataValue)); } internal static InvalidOperationException NonSequentialColumnAccess(int badCol, int currCol) { return InvalidOperation(SR.GetString(SR.ADP_NonSequentialColumnAccess, badCol.ToString(CultureInfo.InvariantCulture), currCol.ToString(CultureInfo.InvariantCulture))); } internal static Exception InvalidXmlInvalidValue(string collectionName, string columnName) { return Argument(SR.GetString(SR.MDF_InvalidXmlInvalidValue, collectionName, columnName)); } internal static Exception CollectionNameIsNotUnique(string collectionName) { return Argument(SR.GetString(SR.MDF_CollectionNameISNotUnique, collectionName)); } // // : IDbCommand // internal static Exception InvalidCommandTimeout(int value, [CallerMemberName] string property = "") { return Argument(SR.GetString(SR.ADP_InvalidCommandTimeout, value.ToString(CultureInfo.InvariantCulture)), property); } internal static Exception UninitializedParameterSize(int index, Type dataType) { return InvalidOperation(SR.GetString(SR.ADP_UninitializedParameterSize, index.ToString(CultureInfo.InvariantCulture), dataType.Name)); } internal static Exception UnableToBuildCollection(string collectionName) { return Argument(SR.GetString(SR.MDF_UnableToBuildCollection, collectionName)); } internal static Exception PrepareParameterType(DbCommand cmd) { return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterType, cmd.GetType().Name)); } internal static Exception UndefinedCollection(string collectionName) { return Argument(SR.GetString(SR.MDF_UndefinedCollection, collectionName)); } internal static Exception UnsupportedVersion(string collectionName) { return Argument(SR.GetString(SR.MDF_UnsupportedVersion, collectionName)); } internal static Exception AmbigousCollectionName(string collectionName) { return Argument(SR.GetString(SR.MDF_AmbigousCollectionName, collectionName)); } internal static Exception PrepareParameterSize(DbCommand cmd) { return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterSize, cmd.GetType().Name)); } internal static Exception PrepareParameterScale(DbCommand cmd, string type) { return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterScale, cmd.GetType().Name, type)); } internal static Exception MissingDataSourceInformationColumn() { return Argument(SR.GetString(SR.MDF_MissingDataSourceInformationColumn)); } internal static Exception IncorrectNumberOfDataSourceInformationRows() { return Argument(SR.GetString(SR.MDF_IncorrectNumberOfDataSourceInformationRows)); } internal static Exception MismatchedAsyncResult(string expectedMethod, string gotMethod) { return InvalidOperation(SR.GetString(SR.ADP_MismatchedAsyncResult, expectedMethod, gotMethod)); } // // : ConnectionUtil // internal static Exception ClosedConnectionError() { return InvalidOperation(SR.GetString(SR.ADP_ClosedConnectionError)); } internal static Exception ConnectionAlreadyOpen(ConnectionState state) { return InvalidOperation(SR.GetString(SR.ADP_ConnectionAlreadyOpen, ADP.ConnectionStateMsg(state))); } internal static Exception TransactionPresent() { return InvalidOperation(SR.GetString(SR.ADP_TransactionPresent)); } internal static Exception LocalTransactionPresent() { return InvalidOperation(SR.GetString(SR.ADP_LocalTransactionPresent)); } internal static Exception OpenConnectionPropertySet(string property, ConnectionState state) { return InvalidOperation(SR.GetString(SR.ADP_OpenConnectionPropertySet, property, ADP.ConnectionStateMsg(state))); } internal static Exception EmptyDatabaseName() { return Argument(SR.GetString(SR.ADP_EmptyDatabaseName)); } internal enum ConnectionError { BeginGetConnectionReturnsNull, GetConnectionReturnsNull, ConnectionOptionsMissing, CouldNotSwitchToClosedPreviouslyOpenedState, } internal static Exception MissingRestrictionColumn() { return Argument(SR.GetString(SR.MDF_MissingRestrictionColumn)); } internal static Exception InternalConnectionError(ConnectionError internalError) { return InvalidOperation(SR.GetString(SR.ADP_InternalConnectionError, (int)internalError)); } internal static Exception InvalidConnectRetryCountValue() { return Argument(SR.GetString(SR.SQLCR_InvalidConnectRetryCountValue)); } internal static Exception MissingRestrictionRow() { return Argument(SR.GetString(SR.MDF_MissingRestrictionRow)); } internal static Exception InvalidConnectRetryIntervalValue() { return Argument(SR.GetString(SR.SQLCR_InvalidConnectRetryIntervalValue)); } // // : DbDataReader // internal static InvalidOperationException AsyncOperationPending() { return InvalidOperation(SR.GetString(SR.ADP_PendingAsyncOperation)); } // // : Stream // internal static IOException ErrorReadingFromStream(Exception internalException) { return IO(SR.GetString(SR.SqlMisc_StreamErrorMessage), internalException); } internal static ArgumentException InvalidDataType(string typeName) { return Argument(SR.GetString(SR.ADP_InvalidDataType, typeName)); } internal static ArgumentException UnknownDataType(Type dataType) { return Argument(SR.GetString(SR.ADP_UnknownDataType, dataType.FullName)); } internal static ArgumentException DbTypeNotSupported(DbType type, Type enumtype) { return Argument(SR.GetString(SR.ADP_DbTypeNotSupported, type.ToString(), enumtype.Name)); } internal static ArgumentException InvalidOffsetValue(int value) { return Argument(SR.GetString(SR.ADP_InvalidOffsetValue, value.ToString(CultureInfo.InvariantCulture))); } internal static ArgumentException InvalidSizeValue(int value) { return Argument(SR.GetString(SR.ADP_InvalidSizeValue, value.ToString(CultureInfo.InvariantCulture))); } internal static ArgumentException ParameterValueOutOfRange(Decimal value) { return ADP.Argument(SR.GetString(SR.ADP_ParameterValueOutOfRange, value.ToString((IFormatProvider)null))); } internal static ArgumentException ParameterValueOutOfRange(SqlDecimal value) { return ADP.Argument(SR.GetString(SR.ADP_ParameterValueOutOfRange, value.ToString())); } internal static ArgumentException VersionDoesNotSupportDataType(string typeName) { return Argument(SR.GetString(SR.ADP_VersionDoesNotSupportDataType, typeName)); } internal static Exception ParameterConversionFailed(object value, Type destType, Exception inner) { Debug.Assert(null != value, "null value on conversion failure"); Debug.Assert(null != inner, "null inner on conversion failure"); Exception e; string message = SR.GetString(SR.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name); if (inner is ArgumentException) { e = new ArgumentException(message, inner); } else if (inner is FormatException) { e = new FormatException(message, inner); } else if (inner is InvalidCastException) { e = new InvalidCastException(message, inner); } else if (inner is OverflowException) { e = new OverflowException(message, inner); } else { e = inner; } return e; } // // : IDataParameterCollection // internal static Exception ParametersMappingIndex(int index, DbParameterCollection collection) { return CollectionIndexInt32(index, collection.GetType(), collection.Count); } internal static Exception ParametersSourceIndex(string parameterName, DbParameterCollection collection, Type parameterType) { return CollectionIndexString(parameterType, ADP.ParameterName, parameterName, collection.GetType()); } internal static Exception ParameterNull(string parameter, DbParameterCollection collection, Type parameterType) { return CollectionNullValue(parameter, collection.GetType(), parameterType); } internal static Exception UndefinedPopulationMechanism(string populationMechanism) { throw new NotImplementedException(); } internal static Exception InvalidParameterType(DbParameterCollection collection, Type parameterType, object invalidValue) { return CollectionInvalidType(collection.GetType(), parameterType, invalidValue); } // // : IDbTransaction // internal static Exception ParallelTransactionsNotSupported(DbConnection obj) { return InvalidOperation(SR.GetString(SR.ADP_ParallelTransactionsNotSupported, obj.GetType().Name)); } internal static Exception TransactionZombied(DbTransaction obj) { return InvalidOperation(SR.GetString(SR.ADP_TransactionZombied, obj.GetType().Name)); } // global constant strings internal const string Parameter = "Parameter"; internal const string ParameterName = "ParameterName"; internal const string ParameterSetPosition = "set_Position"; internal const int DefaultCommandTimeout = 30; internal const float FailoverTimeoutStep = 0.08F; // fraction of timeout to use for fast failover connections // security issue, don't rely upon public static readonly values internal static readonly string StrEmpty = ""; // String.Empty internal const int CharSize = sizeof(char); internal static Delegate FindBuilder(MulticastDelegate mcd) { if (null != mcd) { foreach (Delegate del in mcd.GetInvocationList()) { if (del.Target is DbCommandBuilder) return del; } } return null; } internal static void TimerCurrent(out long ticks) { ticks = DateTime.UtcNow.ToFileTimeUtc(); } internal static long TimerCurrent() { return DateTime.UtcNow.ToFileTimeUtc(); } internal static long TimerFromSeconds(int seconds) { long result = checked((long)seconds * TimeSpan.TicksPerSecond); return result; } internal static long TimerFromMilliseconds(long milliseconds) { long result = checked(milliseconds * TimeSpan.TicksPerMillisecond); return result; } internal static bool TimerHasExpired(long timerExpire) { bool result = TimerCurrent() > timerExpire; return result; } internal static long TimerRemaining(long timerExpire) { long timerNow = TimerCurrent(); long result = checked(timerExpire - timerNow); return result; } internal static long TimerRemainingMilliseconds(long timerExpire) { long result = TimerToMilliseconds(TimerRemaining(timerExpire)); return result; } internal static long TimerRemainingSeconds(long timerExpire) { long result = TimerToSeconds(TimerRemaining(timerExpire)); return result; } internal static long TimerToMilliseconds(long timerValue) { long result = timerValue / TimeSpan.TicksPerMillisecond; return result; } private static long TimerToSeconds(long timerValue) { long result = timerValue / TimeSpan.TicksPerSecond; return result; } internal static string MachineName() { return Environment.MachineName; } internal static Transaction GetCurrentTransaction() { return Transaction.Current; } internal static bool IsDirection(DbParameter value, ParameterDirection condition) { #if DEBUG IsDirectionValid(condition); #endif return (condition == (condition & value.Direction)); } #if DEBUG private static void IsDirectionValid(ParameterDirection value) { switch (value) { // @perfnote: Enum.IsDefined case ParameterDirection.Input: case ParameterDirection.Output: case ParameterDirection.InputOutput: case ParameterDirection.ReturnValue: break; default: throw ADP.InvalidParameterDirection(value); } } #endif internal static void IsNullOrSqlType(object value, out bool isNull, out bool isSqlType) { if ((value == null) || (value == DBNull.Value)) { isNull = true; isSqlType = false; } else { INullable nullable = (value as INullable); if (nullable != null) { isNull = nullable.IsNull; // Duplicated from DataStorage.cs // For back-compat, SqlXml is not in this list isSqlType = ((value is SqlBinary) || (value is SqlBoolean) || (value is SqlByte) || (value is SqlBytes) || (value is SqlChars) || (value is SqlDateTime) || (value is SqlDecimal) || (value is SqlDouble) || (value is SqlGuid) || (value is SqlInt16) || (value is SqlInt32) || (value is SqlInt64) || (value is SqlMoney) || (value is SqlSingle) || (value is SqlString)); } else { isNull = false; isSqlType = false; } } } private static Version s_systemDataVersion; internal static Version GetAssemblyVersion() { // NOTE: Using lazy thread-safety since we don't care if two threads both happen to update the value at the same time if (s_systemDataVersion == null) { s_systemDataVersion = new Version(ThisAssembly.InformationalVersion); } return s_systemDataVersion; } internal static readonly string[] AzureSqlServerEndpoints = {SR.GetString(SR.AZURESQL_GenericEndpoint), SR.GetString(SR.AZURESQL_GermanEndpoint), SR.GetString(SR.AZURESQL_UsGovEndpoint), SR.GetString(SR.AZURESQL_ChinaEndpoint)}; // This method assumes dataSource parameter is in TCP connection string format. internal static bool IsAzureSqlServerEndpoint(string dataSource) { // remove server port int i = dataSource.LastIndexOf(','); if (i >= 0) { dataSource = dataSource.Substring(0, i); } // check for the instance name i = dataSource.LastIndexOf('\\'); if (i >= 0) { dataSource = dataSource.Substring(0, i); } // trim redundant whitespace dataSource = dataSource.Trim(); // check if servername end with any azure endpoints for (i = 0; i < AzureSqlServerEndpoints.Length; i++) { if (dataSource.EndsWith(AzureSqlServerEndpoints[i], StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } internal static ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion value) { #if DEBUG switch (value) { case DataRowVersion.Default: case DataRowVersion.Current: case DataRowVersion.Original: case DataRowVersion.Proposed: Debug.Fail($"Invalid DataRowVersion {value}"); break; } #endif return InvalidEnumerationValue(typeof(DataRowVersion), (int)value); } internal static ArgumentException SingleValuedProperty(string propertyName, string value) { ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_SingleValuedProperty, propertyName, value)); TraceExceptionAsReturnValue(e); return e; } internal static ArgumentException DoubleValuedProperty(string propertyName, string value1, string value2) { ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_DoubleValuedProperty, propertyName, value1, value2)); TraceExceptionAsReturnValue(e); return e; } internal static ArgumentException InvalidPrefixSuffix() { ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_InvalidPrefixSuffix)); TraceExceptionAsReturnValue(e); return e; } // the return value is true if the string was quoted and false if it was not // this allows the caller to determine if it is an error or not for the quotedString to not be quoted internal static bool RemoveStringQuotes(string quotePrefix, string quoteSuffix, string quotedString, out string unquotedString) { int prefixLength = quotePrefix != null ? quotePrefix.Length : 0; int suffixLength = quoteSuffix != null ? quoteSuffix.Length : 0; if ((suffixLength + prefixLength) == 0) { unquotedString = quotedString; return true; } if (quotedString == null) { unquotedString = quotedString; return false; } int quotedStringLength = quotedString.Length; // is the source string too short to be quoted if (quotedStringLength < prefixLength + suffixLength) { unquotedString = quotedString; return false; } // is the prefix present? if (prefixLength > 0) { if (!quotedString.StartsWith(quotePrefix, StringComparison.Ordinal)) { unquotedString = quotedString; return false; } } // is the suffix present? if (suffixLength > 0) { if (!quotedString.EndsWith(quoteSuffix, StringComparison.Ordinal)) { unquotedString = quotedString; return false; } unquotedString = quotedString.Substring(prefixLength, quotedStringLength - (prefixLength + suffixLength)).Replace(quoteSuffix + quoteSuffix, quoteSuffix); } else { unquotedString = quotedString.Substring(prefixLength, quotedStringLength - prefixLength); } return true; } internal static ArgumentOutOfRangeException InvalidCommandBehavior(CommandBehavior value) { Debug.Assert((0 > (int)value) || ((int)value > 0x3F), "valid CommandType " + value.ToString()); return InvalidEnumerationValue(typeof(CommandBehavior), (int)value); } internal static void ValidateCommandBehavior(CommandBehavior value) { if (((int)value < 0) || (0x3F < (int)value)) { throw InvalidCommandBehavior(value); } } internal static ArgumentOutOfRangeException NotSupportedCommandBehavior(CommandBehavior value, string method) { return NotSupportedEnumerationValue(typeof(CommandBehavior), value.ToString(), method); } internal static ArgumentException BadParameterName(string parameterName) { ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_BadParameterName, parameterName)); TraceExceptionAsReturnValue(e); return e; } internal static Exception DeriveParametersNotSupported(IDbCommand value) { return DataAdapter(SR.GetString(SR.ADP_DeriveParametersNotSupported, value.GetType().Name, value.CommandType.ToString())); } internal static Exception NoStoredProcedureExists(string sproc) { return InvalidOperation(SR.GetString(SR.ADP_NoStoredProcedureExists, sproc)); } // // DbProviderException // internal static InvalidOperationException TransactionCompletedButNotDisposed() { return Provider(SR.GetString(SR.ADP_TransactionCompletedButNotDisposed)); } } }
/* * ****************************************************************************** * Copyright 2014-2017 Spectra Logic 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. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ // This code is auto-generated, do not modify using System.Collections.Generic; using Ds3.Calls; using Ds3.Models; namespace Ds3 { /// <summary> /// The main DS3 API interface. Use Ds3Builder to instantiate. /// </summary> public interface IDs3Client { CompleteMultiPartUploadResponse CompleteMultiPartUpload(CompleteMultiPartUploadRequest request); DeleteObjectsResponse DeleteObjects(DeleteObjectsRequest request); GetBucketResponse GetBucket(GetBucketRequest request); GetServiceResponse GetService(GetServiceRequest request); HeadBucketResponse HeadBucket(HeadBucketRequest request); HeadObjectResponse HeadObject(HeadObjectRequest request); InitiateMultiPartUploadResponse InitiateMultiPartUpload(InitiateMultiPartUploadRequest request); ListMultiPartUploadPartsResponse ListMultiPartUploadParts(ListMultiPartUploadPartsRequest request); ListMultiPartUploadsResponse ListMultiPartUploads(ListMultiPartUploadsRequest request); PutBucketAclForGroupSpectraS3Response PutBucketAclForGroupSpectraS3(PutBucketAclForGroupSpectraS3Request request); PutBucketAclForUserSpectraS3Response PutBucketAclForUserSpectraS3(PutBucketAclForUserSpectraS3Request request); PutDataPolicyAclForGroupSpectraS3Response PutDataPolicyAclForGroupSpectraS3(PutDataPolicyAclForGroupSpectraS3Request request); PutDataPolicyAclForUserSpectraS3Response PutDataPolicyAclForUserSpectraS3(PutDataPolicyAclForUserSpectraS3Request request); PutGlobalBucketAclForGroupSpectraS3Response PutGlobalBucketAclForGroupSpectraS3(PutGlobalBucketAclForGroupSpectraS3Request request); PutGlobalBucketAclForUserSpectraS3Response PutGlobalBucketAclForUserSpectraS3(PutGlobalBucketAclForUserSpectraS3Request request); PutGlobalDataPolicyAclForGroupSpectraS3Response PutGlobalDataPolicyAclForGroupSpectraS3(PutGlobalDataPolicyAclForGroupSpectraS3Request request); PutGlobalDataPolicyAclForUserSpectraS3Response PutGlobalDataPolicyAclForUserSpectraS3(PutGlobalDataPolicyAclForUserSpectraS3Request request); GetBucketAclSpectraS3Response GetBucketAclSpectraS3(GetBucketAclSpectraS3Request request); GetBucketAclsSpectraS3Response GetBucketAclsSpectraS3(GetBucketAclsSpectraS3Request request); GetDataPolicyAclSpectraS3Response GetDataPolicyAclSpectraS3(GetDataPolicyAclSpectraS3Request request); GetDataPolicyAclsSpectraS3Response GetDataPolicyAclsSpectraS3(GetDataPolicyAclsSpectraS3Request request); PutBucketSpectraS3Response PutBucketSpectraS3(PutBucketSpectraS3Request request); GetBucketSpectraS3Response GetBucketSpectraS3(GetBucketSpectraS3Request request); GetBucketsSpectraS3Response GetBucketsSpectraS3(GetBucketsSpectraS3Request request); ModifyBucketSpectraS3Response ModifyBucketSpectraS3(ModifyBucketSpectraS3Request request); GetCacheFilesystemSpectraS3Response GetCacheFilesystemSpectraS3(GetCacheFilesystemSpectraS3Request request); GetCacheFilesystemsSpectraS3Response GetCacheFilesystemsSpectraS3(GetCacheFilesystemsSpectraS3Request request); GetCacheStateSpectraS3Response GetCacheStateSpectraS3(GetCacheStateSpectraS3Request request); ModifyCacheFilesystemSpectraS3Response ModifyCacheFilesystemSpectraS3(ModifyCacheFilesystemSpectraS3Request request); GetBucketCapacitySummarySpectraS3Response GetBucketCapacitySummarySpectraS3(GetBucketCapacitySummarySpectraS3Request request); GetStorageDomainCapacitySummarySpectraS3Response GetStorageDomainCapacitySummarySpectraS3(GetStorageDomainCapacitySummarySpectraS3Request request); GetSystemCapacitySummarySpectraS3Response GetSystemCapacitySummarySpectraS3(GetSystemCapacitySummarySpectraS3Request request); GetDataPathBackendSpectraS3Response GetDataPathBackendSpectraS3(GetDataPathBackendSpectraS3Request request); GetDataPlannerBlobStoreTasksSpectraS3Response GetDataPlannerBlobStoreTasksSpectraS3(GetDataPlannerBlobStoreTasksSpectraS3Request request); ModifyDataPathBackendSpectraS3Response ModifyDataPathBackendSpectraS3(ModifyDataPathBackendSpectraS3Request request); PutAzureDataReplicationRuleSpectraS3Response PutAzureDataReplicationRuleSpectraS3(PutAzureDataReplicationRuleSpectraS3Request request); PutDataPersistenceRuleSpectraS3Response PutDataPersistenceRuleSpectraS3(PutDataPersistenceRuleSpectraS3Request request); PutDataPolicySpectraS3Response PutDataPolicySpectraS3(PutDataPolicySpectraS3Request request); PutDs3DataReplicationRuleSpectraS3Response PutDs3DataReplicationRuleSpectraS3(PutDs3DataReplicationRuleSpectraS3Request request); PutS3DataReplicationRuleSpectraS3Response PutS3DataReplicationRuleSpectraS3(PutS3DataReplicationRuleSpectraS3Request request); GetAzureDataReplicationRuleSpectraS3Response GetAzureDataReplicationRuleSpectraS3(GetAzureDataReplicationRuleSpectraS3Request request); GetAzureDataReplicationRulesSpectraS3Response GetAzureDataReplicationRulesSpectraS3(GetAzureDataReplicationRulesSpectraS3Request request); GetDataPersistenceRuleSpectraS3Response GetDataPersistenceRuleSpectraS3(GetDataPersistenceRuleSpectraS3Request request); GetDataPersistenceRulesSpectraS3Response GetDataPersistenceRulesSpectraS3(GetDataPersistenceRulesSpectraS3Request request); GetDataPoliciesSpectraS3Response GetDataPoliciesSpectraS3(GetDataPoliciesSpectraS3Request request); GetDataPolicySpectraS3Response GetDataPolicySpectraS3(GetDataPolicySpectraS3Request request); GetDs3DataReplicationRuleSpectraS3Response GetDs3DataReplicationRuleSpectraS3(GetDs3DataReplicationRuleSpectraS3Request request); GetDs3DataReplicationRulesSpectraS3Response GetDs3DataReplicationRulesSpectraS3(GetDs3DataReplicationRulesSpectraS3Request request); GetS3DataReplicationRuleSpectraS3Response GetS3DataReplicationRuleSpectraS3(GetS3DataReplicationRuleSpectraS3Request request); GetS3DataReplicationRulesSpectraS3Response GetS3DataReplicationRulesSpectraS3(GetS3DataReplicationRulesSpectraS3Request request); ModifyAzureDataReplicationRuleSpectraS3Response ModifyAzureDataReplicationRuleSpectraS3(ModifyAzureDataReplicationRuleSpectraS3Request request); ModifyDataPersistenceRuleSpectraS3Response ModifyDataPersistenceRuleSpectraS3(ModifyDataPersistenceRuleSpectraS3Request request); ModifyDataPolicySpectraS3Response ModifyDataPolicySpectraS3(ModifyDataPolicySpectraS3Request request); ModifyDs3DataReplicationRuleSpectraS3Response ModifyDs3DataReplicationRuleSpectraS3(ModifyDs3DataReplicationRuleSpectraS3Request request); ModifyS3DataReplicationRuleSpectraS3Response ModifyS3DataReplicationRuleSpectraS3(ModifyS3DataReplicationRuleSpectraS3Request request); GetDegradedAzureDataReplicationRulesSpectraS3Response GetDegradedAzureDataReplicationRulesSpectraS3(GetDegradedAzureDataReplicationRulesSpectraS3Request request); GetDegradedBlobsSpectraS3Response GetDegradedBlobsSpectraS3(GetDegradedBlobsSpectraS3Request request); GetDegradedBucketsSpectraS3Response GetDegradedBucketsSpectraS3(GetDegradedBucketsSpectraS3Request request); GetDegradedDataPersistenceRulesSpectraS3Response GetDegradedDataPersistenceRulesSpectraS3(GetDegradedDataPersistenceRulesSpectraS3Request request); GetDegradedDs3DataReplicationRulesSpectraS3Response GetDegradedDs3DataReplicationRulesSpectraS3(GetDegradedDs3DataReplicationRulesSpectraS3Request request); GetDegradedS3DataReplicationRulesSpectraS3Response GetDegradedS3DataReplicationRulesSpectraS3(GetDegradedS3DataReplicationRulesSpectraS3Request request); GetSuspectBlobAzureTargetsSpectraS3Response GetSuspectBlobAzureTargetsSpectraS3(GetSuspectBlobAzureTargetsSpectraS3Request request); GetSuspectBlobDs3TargetsSpectraS3Response GetSuspectBlobDs3TargetsSpectraS3(GetSuspectBlobDs3TargetsSpectraS3Request request); GetSuspectBlobPoolsSpectraS3Response GetSuspectBlobPoolsSpectraS3(GetSuspectBlobPoolsSpectraS3Request request); GetSuspectBlobS3TargetsSpectraS3Response GetSuspectBlobS3TargetsSpectraS3(GetSuspectBlobS3TargetsSpectraS3Request request); GetSuspectBlobTapesSpectraS3Response GetSuspectBlobTapesSpectraS3(GetSuspectBlobTapesSpectraS3Request request); GetSuspectBucketsSpectraS3Response GetSuspectBucketsSpectraS3(GetSuspectBucketsSpectraS3Request request); GetSuspectObjectsSpectraS3Response GetSuspectObjectsSpectraS3(GetSuspectObjectsSpectraS3Request request); GetSuspectObjectsWithFullDetailsSpectraS3Response GetSuspectObjectsWithFullDetailsSpectraS3(GetSuspectObjectsWithFullDetailsSpectraS3Request request); PutGroupGroupMemberSpectraS3Response PutGroupGroupMemberSpectraS3(PutGroupGroupMemberSpectraS3Request request); PutGroupSpectraS3Response PutGroupSpectraS3(PutGroupSpectraS3Request request); PutUserGroupMemberSpectraS3Response PutUserGroupMemberSpectraS3(PutUserGroupMemberSpectraS3Request request); GetGroupMemberSpectraS3Response GetGroupMemberSpectraS3(GetGroupMemberSpectraS3Request request); GetGroupMembersSpectraS3Response GetGroupMembersSpectraS3(GetGroupMembersSpectraS3Request request); GetGroupSpectraS3Response GetGroupSpectraS3(GetGroupSpectraS3Request request); GetGroupsSpectraS3Response GetGroupsSpectraS3(GetGroupsSpectraS3Request request); ModifyGroupSpectraS3Response ModifyGroupSpectraS3(ModifyGroupSpectraS3Request request); VerifyUserIsMemberOfGroupSpectraS3Response VerifyUserIsMemberOfGroupSpectraS3(VerifyUserIsMemberOfGroupSpectraS3Request request); AllocateJobChunkSpectraS3Response AllocateJobChunkSpectraS3(AllocateJobChunkSpectraS3Request request); CloseAggregatingJobSpectraS3Response CloseAggregatingJobSpectraS3(CloseAggregatingJobSpectraS3Request request); GetBulkJobSpectraS3Response GetBulkJobSpectraS3(GetBulkJobSpectraS3Request request); PutBulkJobSpectraS3Response PutBulkJobSpectraS3(PutBulkJobSpectraS3Request request); VerifyBulkJobSpectraS3Response VerifyBulkJobSpectraS3(VerifyBulkJobSpectraS3Request request); GetActiveJobSpectraS3Response GetActiveJobSpectraS3(GetActiveJobSpectraS3Request request); GetActiveJobsSpectraS3Response GetActiveJobsSpectraS3(GetActiveJobsSpectraS3Request request); GetCanceledJobSpectraS3Response GetCanceledJobSpectraS3(GetCanceledJobSpectraS3Request request); GetCanceledJobsSpectraS3Response GetCanceledJobsSpectraS3(GetCanceledJobsSpectraS3Request request); GetCompletedJobSpectraS3Response GetCompletedJobSpectraS3(GetCompletedJobSpectraS3Request request); GetCompletedJobsSpectraS3Response GetCompletedJobsSpectraS3(GetCompletedJobsSpectraS3Request request); GetJobChunkDaoSpectraS3Response GetJobChunkDaoSpectraS3(GetJobChunkDaoSpectraS3Request request); GetJobChunkSpectraS3Response GetJobChunkSpectraS3(GetJobChunkSpectraS3Request request); GetJobChunksReadyForClientProcessingSpectraS3Response GetJobChunksReadyForClientProcessingSpectraS3(GetJobChunksReadyForClientProcessingSpectraS3Request request); GetJobSpectraS3Response GetJobSpectraS3(GetJobSpectraS3Request request); GetJobToReplicateSpectraS3Response GetJobToReplicateSpectraS3(GetJobToReplicateSpectraS3Request request); GetJobsSpectraS3Response GetJobsSpectraS3(GetJobsSpectraS3Request request); ModifyActiveJobSpectraS3Response ModifyActiveJobSpectraS3(ModifyActiveJobSpectraS3Request request); ModifyJobSpectraS3Response ModifyJobSpectraS3(ModifyJobSpectraS3Request request); ReplicatePutJobSpectraS3Response ReplicatePutJobSpectraS3(ReplicatePutJobSpectraS3Request request); StageObjectsJobSpectraS3Response StageObjectsJobSpectraS3(StageObjectsJobSpectraS3Request request); GetNodeSpectraS3Response GetNodeSpectraS3(GetNodeSpectraS3Request request); GetNodesSpectraS3Response GetNodesSpectraS3(GetNodesSpectraS3Request request); ModifyNodeSpectraS3Response ModifyNodeSpectraS3(ModifyNodeSpectraS3Request request); PutAzureTargetFailureNotificationRegistrationSpectraS3Response PutAzureTargetFailureNotificationRegistrationSpectraS3(PutAzureTargetFailureNotificationRegistrationSpectraS3Request request); PutBucketChangesNotificationRegistrationSpectraS3Response PutBucketChangesNotificationRegistrationSpectraS3(PutBucketChangesNotificationRegistrationSpectraS3Request request); PutDs3TargetFailureNotificationRegistrationSpectraS3Response PutDs3TargetFailureNotificationRegistrationSpectraS3(PutDs3TargetFailureNotificationRegistrationSpectraS3Request request); PutJobCompletedNotificationRegistrationSpectraS3Response PutJobCompletedNotificationRegistrationSpectraS3(PutJobCompletedNotificationRegistrationSpectraS3Request request); PutJobCreatedNotificationRegistrationSpectraS3Response PutJobCreatedNotificationRegistrationSpectraS3(PutJobCreatedNotificationRegistrationSpectraS3Request request); PutJobCreationFailedNotificationRegistrationSpectraS3Response PutJobCreationFailedNotificationRegistrationSpectraS3(PutJobCreationFailedNotificationRegistrationSpectraS3Request request); PutObjectCachedNotificationRegistrationSpectraS3Response PutObjectCachedNotificationRegistrationSpectraS3(PutObjectCachedNotificationRegistrationSpectraS3Request request); PutObjectLostNotificationRegistrationSpectraS3Response PutObjectLostNotificationRegistrationSpectraS3(PutObjectLostNotificationRegistrationSpectraS3Request request); PutObjectPersistedNotificationRegistrationSpectraS3Response PutObjectPersistedNotificationRegistrationSpectraS3(PutObjectPersistedNotificationRegistrationSpectraS3Request request); PutPoolFailureNotificationRegistrationSpectraS3Response PutPoolFailureNotificationRegistrationSpectraS3(PutPoolFailureNotificationRegistrationSpectraS3Request request); PutS3TargetFailureNotificationRegistrationSpectraS3Response PutS3TargetFailureNotificationRegistrationSpectraS3(PutS3TargetFailureNotificationRegistrationSpectraS3Request request); PutStorageDomainFailureNotificationRegistrationSpectraS3Response PutStorageDomainFailureNotificationRegistrationSpectraS3(PutStorageDomainFailureNotificationRegistrationSpectraS3Request request); PutSystemFailureNotificationRegistrationSpectraS3Response PutSystemFailureNotificationRegistrationSpectraS3(PutSystemFailureNotificationRegistrationSpectraS3Request request); PutTapeFailureNotificationRegistrationSpectraS3Response PutTapeFailureNotificationRegistrationSpectraS3(PutTapeFailureNotificationRegistrationSpectraS3Request request); PutTapePartitionFailureNotificationRegistrationSpectraS3Response PutTapePartitionFailureNotificationRegistrationSpectraS3(PutTapePartitionFailureNotificationRegistrationSpectraS3Request request); GetAzureTargetFailureNotificationRegistrationSpectraS3Response GetAzureTargetFailureNotificationRegistrationSpectraS3(GetAzureTargetFailureNotificationRegistrationSpectraS3Request request); GetAzureTargetFailureNotificationRegistrationsSpectraS3Response GetAzureTargetFailureNotificationRegistrationsSpectraS3(GetAzureTargetFailureNotificationRegistrationsSpectraS3Request request); GetBucketChangesNotificationRegistrationSpectraS3Response GetBucketChangesNotificationRegistrationSpectraS3(GetBucketChangesNotificationRegistrationSpectraS3Request request); GetBucketChangesNotificationRegistrationsSpectraS3Response GetBucketChangesNotificationRegistrationsSpectraS3(GetBucketChangesNotificationRegistrationsSpectraS3Request request); GetBucketHistorySpectraS3Response GetBucketHistorySpectraS3(GetBucketHistorySpectraS3Request request); GetDs3TargetFailureNotificationRegistrationSpectraS3Response GetDs3TargetFailureNotificationRegistrationSpectraS3(GetDs3TargetFailureNotificationRegistrationSpectraS3Request request); GetDs3TargetFailureNotificationRegistrationsSpectraS3Response GetDs3TargetFailureNotificationRegistrationsSpectraS3(GetDs3TargetFailureNotificationRegistrationsSpectraS3Request request); GetJobCompletedNotificationRegistrationSpectraS3Response GetJobCompletedNotificationRegistrationSpectraS3(GetJobCompletedNotificationRegistrationSpectraS3Request request); GetJobCompletedNotificationRegistrationsSpectraS3Response GetJobCompletedNotificationRegistrationsSpectraS3(GetJobCompletedNotificationRegistrationsSpectraS3Request request); GetJobCreatedNotificationRegistrationSpectraS3Response GetJobCreatedNotificationRegistrationSpectraS3(GetJobCreatedNotificationRegistrationSpectraS3Request request); GetJobCreatedNotificationRegistrationsSpectraS3Response GetJobCreatedNotificationRegistrationsSpectraS3(GetJobCreatedNotificationRegistrationsSpectraS3Request request); GetJobCreationFailedNotificationRegistrationSpectraS3Response GetJobCreationFailedNotificationRegistrationSpectraS3(GetJobCreationFailedNotificationRegistrationSpectraS3Request request); GetJobCreationFailedNotificationRegistrationsSpectraS3Response GetJobCreationFailedNotificationRegistrationsSpectraS3(GetJobCreationFailedNotificationRegistrationsSpectraS3Request request); GetObjectCachedNotificationRegistrationSpectraS3Response GetObjectCachedNotificationRegistrationSpectraS3(GetObjectCachedNotificationRegistrationSpectraS3Request request); GetObjectCachedNotificationRegistrationsSpectraS3Response GetObjectCachedNotificationRegistrationsSpectraS3(GetObjectCachedNotificationRegistrationsSpectraS3Request request); GetObjectLostNotificationRegistrationSpectraS3Response GetObjectLostNotificationRegistrationSpectraS3(GetObjectLostNotificationRegistrationSpectraS3Request request); GetObjectLostNotificationRegistrationsSpectraS3Response GetObjectLostNotificationRegistrationsSpectraS3(GetObjectLostNotificationRegistrationsSpectraS3Request request); GetObjectPersistedNotificationRegistrationSpectraS3Response GetObjectPersistedNotificationRegistrationSpectraS3(GetObjectPersistedNotificationRegistrationSpectraS3Request request); GetObjectPersistedNotificationRegistrationsSpectraS3Response GetObjectPersistedNotificationRegistrationsSpectraS3(GetObjectPersistedNotificationRegistrationsSpectraS3Request request); GetPoolFailureNotificationRegistrationSpectraS3Response GetPoolFailureNotificationRegistrationSpectraS3(GetPoolFailureNotificationRegistrationSpectraS3Request request); GetPoolFailureNotificationRegistrationsSpectraS3Response GetPoolFailureNotificationRegistrationsSpectraS3(GetPoolFailureNotificationRegistrationsSpectraS3Request request); GetS3TargetFailureNotificationRegistrationSpectraS3Response GetS3TargetFailureNotificationRegistrationSpectraS3(GetS3TargetFailureNotificationRegistrationSpectraS3Request request); GetS3TargetFailureNotificationRegistrationsSpectraS3Response GetS3TargetFailureNotificationRegistrationsSpectraS3(GetS3TargetFailureNotificationRegistrationsSpectraS3Request request); GetStorageDomainFailureNotificationRegistrationSpectraS3Response GetStorageDomainFailureNotificationRegistrationSpectraS3(GetStorageDomainFailureNotificationRegistrationSpectraS3Request request); GetStorageDomainFailureNotificationRegistrationsSpectraS3Response GetStorageDomainFailureNotificationRegistrationsSpectraS3(GetStorageDomainFailureNotificationRegistrationsSpectraS3Request request); GetSystemFailureNotificationRegistrationSpectraS3Response GetSystemFailureNotificationRegistrationSpectraS3(GetSystemFailureNotificationRegistrationSpectraS3Request request); GetSystemFailureNotificationRegistrationsSpectraS3Response GetSystemFailureNotificationRegistrationsSpectraS3(GetSystemFailureNotificationRegistrationsSpectraS3Request request); GetTapeFailureNotificationRegistrationSpectraS3Response GetTapeFailureNotificationRegistrationSpectraS3(GetTapeFailureNotificationRegistrationSpectraS3Request request); GetTapeFailureNotificationRegistrationsSpectraS3Response GetTapeFailureNotificationRegistrationsSpectraS3(GetTapeFailureNotificationRegistrationsSpectraS3Request request); GetTapePartitionFailureNotificationRegistrationSpectraS3Response GetTapePartitionFailureNotificationRegistrationSpectraS3(GetTapePartitionFailureNotificationRegistrationSpectraS3Request request); GetTapePartitionFailureNotificationRegistrationsSpectraS3Response GetTapePartitionFailureNotificationRegistrationsSpectraS3(GetTapePartitionFailureNotificationRegistrationsSpectraS3Request request); GetBlobPersistenceSpectraS3Response GetBlobPersistenceSpectraS3(GetBlobPersistenceSpectraS3Request request); GetObjectDetailsSpectraS3Response GetObjectDetailsSpectraS3(GetObjectDetailsSpectraS3Request request); GetObjectsDetailsSpectraS3Response GetObjectsDetailsSpectraS3(GetObjectsDetailsSpectraS3Request request); GetObjectsWithFullDetailsSpectraS3Response GetObjectsWithFullDetailsSpectraS3(GetObjectsWithFullDetailsSpectraS3Request request); GetPhysicalPlacementForObjectsSpectraS3Response GetPhysicalPlacementForObjectsSpectraS3(GetPhysicalPlacementForObjectsSpectraS3Request request); GetPhysicalPlacementForObjectsWithFullDetailsSpectraS3Response GetPhysicalPlacementForObjectsWithFullDetailsSpectraS3(GetPhysicalPlacementForObjectsWithFullDetailsSpectraS3Request request); UndeleteObjectSpectraS3Response UndeleteObjectSpectraS3(UndeleteObjectSpectraS3Request request); VerifyPhysicalPlacementForObjectsSpectraS3Response VerifyPhysicalPlacementForObjectsSpectraS3(VerifyPhysicalPlacementForObjectsSpectraS3Request request); VerifyPhysicalPlacementForObjectsWithFullDetailsSpectraS3Response VerifyPhysicalPlacementForObjectsWithFullDetailsSpectraS3(VerifyPhysicalPlacementForObjectsWithFullDetailsSpectraS3Request request); CancelImportPoolSpectraS3Response CancelImportPoolSpectraS3(CancelImportPoolSpectraS3Request request); CancelVerifyPoolSpectraS3Response CancelVerifyPoolSpectraS3(CancelVerifyPoolSpectraS3Request request); CompactPoolSpectraS3Response CompactPoolSpectraS3(CompactPoolSpectraS3Request request); PutPoolPartitionSpectraS3Response PutPoolPartitionSpectraS3(PutPoolPartitionSpectraS3Request request); FormatForeignPoolSpectraS3Response FormatForeignPoolSpectraS3(FormatForeignPoolSpectraS3Request request); GetBlobsOnPoolSpectraS3Response GetBlobsOnPoolSpectraS3(GetBlobsOnPoolSpectraS3Request request); GetPoolFailuresSpectraS3Response GetPoolFailuresSpectraS3(GetPoolFailuresSpectraS3Request request); GetPoolPartitionSpectraS3Response GetPoolPartitionSpectraS3(GetPoolPartitionSpectraS3Request request); GetPoolPartitionsSpectraS3Response GetPoolPartitionsSpectraS3(GetPoolPartitionsSpectraS3Request request); GetPoolSpectraS3Response GetPoolSpectraS3(GetPoolSpectraS3Request request); GetPoolsSpectraS3Response GetPoolsSpectraS3(GetPoolsSpectraS3Request request); ImportPoolSpectraS3Response ImportPoolSpectraS3(ImportPoolSpectraS3Request request); ModifyPoolPartitionSpectraS3Response ModifyPoolPartitionSpectraS3(ModifyPoolPartitionSpectraS3Request request); ModifyPoolSpectraS3Response ModifyPoolSpectraS3(ModifyPoolSpectraS3Request request); VerifyPoolSpectraS3Response VerifyPoolSpectraS3(VerifyPoolSpectraS3Request request); PutPoolStorageDomainMemberSpectraS3Response PutPoolStorageDomainMemberSpectraS3(PutPoolStorageDomainMemberSpectraS3Request request); PutStorageDomainSpectraS3Response PutStorageDomainSpectraS3(PutStorageDomainSpectraS3Request request); PutTapeStorageDomainMemberSpectraS3Response PutTapeStorageDomainMemberSpectraS3(PutTapeStorageDomainMemberSpectraS3Request request); GetStorageDomainFailuresSpectraS3Response GetStorageDomainFailuresSpectraS3(GetStorageDomainFailuresSpectraS3Request request); GetStorageDomainMemberSpectraS3Response GetStorageDomainMemberSpectraS3(GetStorageDomainMemberSpectraS3Request request); GetStorageDomainMembersSpectraS3Response GetStorageDomainMembersSpectraS3(GetStorageDomainMembersSpectraS3Request request); GetStorageDomainSpectraS3Response GetStorageDomainSpectraS3(GetStorageDomainSpectraS3Request request); GetStorageDomainsSpectraS3Response GetStorageDomainsSpectraS3(GetStorageDomainsSpectraS3Request request); ModifyStorageDomainMemberSpectraS3Response ModifyStorageDomainMemberSpectraS3(ModifyStorageDomainMemberSpectraS3Request request); ModifyStorageDomainSpectraS3Response ModifyStorageDomainSpectraS3(ModifyStorageDomainSpectraS3Request request); GetFeatureKeysSpectraS3Response GetFeatureKeysSpectraS3(GetFeatureKeysSpectraS3Request request); GetSystemFailuresSpectraS3Response GetSystemFailuresSpectraS3(GetSystemFailuresSpectraS3Request request); GetSystemInformationSpectraS3Response GetSystemInformationSpectraS3(GetSystemInformationSpectraS3Request request); ResetInstanceIdentifierSpectraS3Response ResetInstanceIdentifierSpectraS3(ResetInstanceIdentifierSpectraS3Request request); VerifySystemHealthSpectraS3Response VerifySystemHealthSpectraS3(VerifySystemHealthSpectraS3Request request); CancelEjectOnAllTapesSpectraS3Response CancelEjectOnAllTapesSpectraS3(CancelEjectOnAllTapesSpectraS3Request request); CancelEjectTapeSpectraS3Response CancelEjectTapeSpectraS3(CancelEjectTapeSpectraS3Request request); CancelFormatOnAllTapesSpectraS3Response CancelFormatOnAllTapesSpectraS3(CancelFormatOnAllTapesSpectraS3Request request); CancelFormatTapeSpectraS3Response CancelFormatTapeSpectraS3(CancelFormatTapeSpectraS3Request request); CancelImportOnAllTapesSpectraS3Response CancelImportOnAllTapesSpectraS3(CancelImportOnAllTapesSpectraS3Request request); CancelImportTapeSpectraS3Response CancelImportTapeSpectraS3(CancelImportTapeSpectraS3Request request); CancelOnlineOnAllTapesSpectraS3Response CancelOnlineOnAllTapesSpectraS3(CancelOnlineOnAllTapesSpectraS3Request request); CancelOnlineTapeSpectraS3Response CancelOnlineTapeSpectraS3(CancelOnlineTapeSpectraS3Request request); CancelVerifyOnAllTapesSpectraS3Response CancelVerifyOnAllTapesSpectraS3(CancelVerifyOnAllTapesSpectraS3Request request); CancelVerifyTapeSpectraS3Response CancelVerifyTapeSpectraS3(CancelVerifyTapeSpectraS3Request request); CleanTapeDriveSpectraS3Response CleanTapeDriveSpectraS3(CleanTapeDriveSpectraS3Request request); PutTapeDensityDirectiveSpectraS3Response PutTapeDensityDirectiveSpectraS3(PutTapeDensityDirectiveSpectraS3Request request); EjectAllTapesSpectraS3Response EjectAllTapesSpectraS3(EjectAllTapesSpectraS3Request request); EjectStorageDomainSpectraS3Response EjectStorageDomainSpectraS3(EjectStorageDomainSpectraS3Request request); EjectTapeSpectraS3Response EjectTapeSpectraS3(EjectTapeSpectraS3Request request); FormatAllTapesSpectraS3Response FormatAllTapesSpectraS3(FormatAllTapesSpectraS3Request request); FormatTapeSpectraS3Response FormatTapeSpectraS3(FormatTapeSpectraS3Request request); GetBlobsOnTapeSpectraS3Response GetBlobsOnTapeSpectraS3(GetBlobsOnTapeSpectraS3Request request); GetTapeDensityDirectiveSpectraS3Response GetTapeDensityDirectiveSpectraS3(GetTapeDensityDirectiveSpectraS3Request request); GetTapeDensityDirectivesSpectraS3Response GetTapeDensityDirectivesSpectraS3(GetTapeDensityDirectivesSpectraS3Request request); GetTapeDriveSpectraS3Response GetTapeDriveSpectraS3(GetTapeDriveSpectraS3Request request); GetTapeDrivesSpectraS3Response GetTapeDrivesSpectraS3(GetTapeDrivesSpectraS3Request request); GetTapeFailuresSpectraS3Response GetTapeFailuresSpectraS3(GetTapeFailuresSpectraS3Request request); GetTapeLibrariesSpectraS3Response GetTapeLibrariesSpectraS3(GetTapeLibrariesSpectraS3Request request); GetTapeLibrarySpectraS3Response GetTapeLibrarySpectraS3(GetTapeLibrarySpectraS3Request request); GetTapePartitionFailuresSpectraS3Response GetTapePartitionFailuresSpectraS3(GetTapePartitionFailuresSpectraS3Request request); GetTapePartitionSpectraS3Response GetTapePartitionSpectraS3(GetTapePartitionSpectraS3Request request); GetTapePartitionWithFullDetailsSpectraS3Response GetTapePartitionWithFullDetailsSpectraS3(GetTapePartitionWithFullDetailsSpectraS3Request request); GetTapePartitionsSpectraS3Response GetTapePartitionsSpectraS3(GetTapePartitionsSpectraS3Request request); GetTapePartitionsWithFullDetailsSpectraS3Response GetTapePartitionsWithFullDetailsSpectraS3(GetTapePartitionsWithFullDetailsSpectraS3Request request); GetTapeSpectraS3Response GetTapeSpectraS3(GetTapeSpectraS3Request request); GetTapesSpectraS3Response GetTapesSpectraS3(GetTapesSpectraS3Request request); ImportTapeSpectraS3Response ImportTapeSpectraS3(ImportTapeSpectraS3Request request); InspectAllTapesSpectraS3Response InspectAllTapesSpectraS3(InspectAllTapesSpectraS3Request request); InspectTapeSpectraS3Response InspectTapeSpectraS3(InspectTapeSpectraS3Request request); MarkTapeForCompactionSpectraS3Response MarkTapeForCompactionSpectraS3(MarkTapeForCompactionSpectraS3Request request); ModifyTapeDriveSpectraS3Response ModifyTapeDriveSpectraS3(ModifyTapeDriveSpectraS3Request request); ModifyTapePartitionSpectraS3Response ModifyTapePartitionSpectraS3(ModifyTapePartitionSpectraS3Request request); ModifyTapeSpectraS3Response ModifyTapeSpectraS3(ModifyTapeSpectraS3Request request); OnlineAllTapesSpectraS3Response OnlineAllTapesSpectraS3(OnlineAllTapesSpectraS3Request request); OnlineTapeSpectraS3Response OnlineTapeSpectraS3(OnlineTapeSpectraS3Request request); RawImportTapeSpectraS3Response RawImportTapeSpectraS3(RawImportTapeSpectraS3Request request); VerifyAllTapesSpectraS3Response VerifyAllTapesSpectraS3(VerifyAllTapesSpectraS3Request request); VerifyTapeSpectraS3Response VerifyTapeSpectraS3(VerifyTapeSpectraS3Request request); PutAzureTargetBucketNameSpectraS3Response PutAzureTargetBucketNameSpectraS3(PutAzureTargetBucketNameSpectraS3Request request); PutAzureTargetReadPreferenceSpectraS3Response PutAzureTargetReadPreferenceSpectraS3(PutAzureTargetReadPreferenceSpectraS3Request request); GetAzureTargetBucketNamesSpectraS3Response GetAzureTargetBucketNamesSpectraS3(GetAzureTargetBucketNamesSpectraS3Request request); GetAzureTargetFailuresSpectraS3Response GetAzureTargetFailuresSpectraS3(GetAzureTargetFailuresSpectraS3Request request); GetAzureTargetReadPreferenceSpectraS3Response GetAzureTargetReadPreferenceSpectraS3(GetAzureTargetReadPreferenceSpectraS3Request request); GetAzureTargetReadPreferencesSpectraS3Response GetAzureTargetReadPreferencesSpectraS3(GetAzureTargetReadPreferencesSpectraS3Request request); GetAzureTargetSpectraS3Response GetAzureTargetSpectraS3(GetAzureTargetSpectraS3Request request); GetAzureTargetsSpectraS3Response GetAzureTargetsSpectraS3(GetAzureTargetsSpectraS3Request request); GetBlobsOnAzureTargetSpectraS3Response GetBlobsOnAzureTargetSpectraS3(GetBlobsOnAzureTargetSpectraS3Request request); ModifyAzureTargetSpectraS3Response ModifyAzureTargetSpectraS3(ModifyAzureTargetSpectraS3Request request); RegisterAzureTargetSpectraS3Response RegisterAzureTargetSpectraS3(RegisterAzureTargetSpectraS3Request request); VerifyAzureTargetSpectraS3Response VerifyAzureTargetSpectraS3(VerifyAzureTargetSpectraS3Request request); PutDs3TargetReadPreferenceSpectraS3Response PutDs3TargetReadPreferenceSpectraS3(PutDs3TargetReadPreferenceSpectraS3Request request); GetBlobsOnDs3TargetSpectraS3Response GetBlobsOnDs3TargetSpectraS3(GetBlobsOnDs3TargetSpectraS3Request request); GetDs3TargetDataPoliciesSpectraS3Response GetDs3TargetDataPoliciesSpectraS3(GetDs3TargetDataPoliciesSpectraS3Request request); GetDs3TargetFailuresSpectraS3Response GetDs3TargetFailuresSpectraS3(GetDs3TargetFailuresSpectraS3Request request); GetDs3TargetReadPreferenceSpectraS3Response GetDs3TargetReadPreferenceSpectraS3(GetDs3TargetReadPreferenceSpectraS3Request request); GetDs3TargetReadPreferencesSpectraS3Response GetDs3TargetReadPreferencesSpectraS3(GetDs3TargetReadPreferencesSpectraS3Request request); GetDs3TargetSpectraS3Response GetDs3TargetSpectraS3(GetDs3TargetSpectraS3Request request); GetDs3TargetsSpectraS3Response GetDs3TargetsSpectraS3(GetDs3TargetsSpectraS3Request request); ModifyDs3TargetSpectraS3Response ModifyDs3TargetSpectraS3(ModifyDs3TargetSpectraS3Request request); RegisterDs3TargetSpectraS3Response RegisterDs3TargetSpectraS3(RegisterDs3TargetSpectraS3Request request); VerifyDs3TargetSpectraS3Response VerifyDs3TargetSpectraS3(VerifyDs3TargetSpectraS3Request request); PutS3TargetBucketNameSpectraS3Response PutS3TargetBucketNameSpectraS3(PutS3TargetBucketNameSpectraS3Request request); PutS3TargetReadPreferenceSpectraS3Response PutS3TargetReadPreferenceSpectraS3(PutS3TargetReadPreferenceSpectraS3Request request); GetBlobsOnS3TargetSpectraS3Response GetBlobsOnS3TargetSpectraS3(GetBlobsOnS3TargetSpectraS3Request request); GetS3TargetBucketNamesSpectraS3Response GetS3TargetBucketNamesSpectraS3(GetS3TargetBucketNamesSpectraS3Request request); GetS3TargetFailuresSpectraS3Response GetS3TargetFailuresSpectraS3(GetS3TargetFailuresSpectraS3Request request); GetS3TargetReadPreferenceSpectraS3Response GetS3TargetReadPreferenceSpectraS3(GetS3TargetReadPreferenceSpectraS3Request request); GetS3TargetReadPreferencesSpectraS3Response GetS3TargetReadPreferencesSpectraS3(GetS3TargetReadPreferencesSpectraS3Request request); GetS3TargetSpectraS3Response GetS3TargetSpectraS3(GetS3TargetSpectraS3Request request); GetS3TargetsSpectraS3Response GetS3TargetsSpectraS3(GetS3TargetsSpectraS3Request request); ModifyS3TargetSpectraS3Response ModifyS3TargetSpectraS3(ModifyS3TargetSpectraS3Request request); RegisterS3TargetSpectraS3Response RegisterS3TargetSpectraS3(RegisterS3TargetSpectraS3Request request); VerifyS3TargetSpectraS3Response VerifyS3TargetSpectraS3(VerifyS3TargetSpectraS3Request request); DelegateCreateUserSpectraS3Response DelegateCreateUserSpectraS3(DelegateCreateUserSpectraS3Request request); GetUserSpectraS3Response GetUserSpectraS3(GetUserSpectraS3Request request); GetUsersSpectraS3Response GetUsersSpectraS3(GetUsersSpectraS3Request request); ModifyUserSpectraS3Response ModifyUserSpectraS3(ModifyUserSpectraS3Request request); RegenerateUserSecretKeySpectraS3Response RegenerateUserSecretKeySpectraS3(RegenerateUserSecretKeySpectraS3Request request); void AbortMultiPartUpload(AbortMultiPartUploadRequest request); void CompleteBlob(CompleteBlobRequest request); void PutBucket(PutBucketRequest request); void PutMultiPartUploadPart(PutMultiPartUploadPartRequest request); void PutObject(PutObjectRequest request); void DeleteBucket(DeleteBucketRequest request); void DeleteObject(DeleteObjectRequest request); void DeleteBucketAclSpectraS3(DeleteBucketAclSpectraS3Request request); void DeleteDataPolicyAclSpectraS3(DeleteDataPolicyAclSpectraS3Request request); void DeleteBucketSpectraS3(DeleteBucketSpectraS3Request request); void ForceFullCacheReclaimSpectraS3(ForceFullCacheReclaimSpectraS3Request request); void DeleteAzureDataReplicationRuleSpectraS3(DeleteAzureDataReplicationRuleSpectraS3Request request); void DeleteDataPersistenceRuleSpectraS3(DeleteDataPersistenceRuleSpectraS3Request request); void DeleteDataPolicySpectraS3(DeleteDataPolicySpectraS3Request request); void DeleteDs3DataReplicationRuleSpectraS3(DeleteDs3DataReplicationRuleSpectraS3Request request); void DeleteS3DataReplicationRuleSpectraS3(DeleteS3DataReplicationRuleSpectraS3Request request); void ClearSuspectBlobAzureTargetsSpectraS3(ClearSuspectBlobAzureTargetsSpectraS3Request request); void ClearSuspectBlobDs3TargetsSpectraS3(ClearSuspectBlobDs3TargetsSpectraS3Request request); void ClearSuspectBlobPoolsSpectraS3(ClearSuspectBlobPoolsSpectraS3Request request); void ClearSuspectBlobS3TargetsSpectraS3(ClearSuspectBlobS3TargetsSpectraS3Request request); void ClearSuspectBlobTapesSpectraS3(ClearSuspectBlobTapesSpectraS3Request request); void MarkSuspectBlobAzureTargetsAsDegradedSpectraS3(MarkSuspectBlobAzureTargetsAsDegradedSpectraS3Request request); void MarkSuspectBlobDs3TargetsAsDegradedSpectraS3(MarkSuspectBlobDs3TargetsAsDegradedSpectraS3Request request); void MarkSuspectBlobPoolsAsDegradedSpectraS3(MarkSuspectBlobPoolsAsDegradedSpectraS3Request request); void MarkSuspectBlobS3TargetsAsDegradedSpectraS3(MarkSuspectBlobS3TargetsAsDegradedSpectraS3Request request); void MarkSuspectBlobTapesAsDegradedSpectraS3(MarkSuspectBlobTapesAsDegradedSpectraS3Request request); void DeleteGroupMemberSpectraS3(DeleteGroupMemberSpectraS3Request request); void DeleteGroupSpectraS3(DeleteGroupSpectraS3Request request); void CancelActiveJobSpectraS3(CancelActiveJobSpectraS3Request request); void CancelAllActiveJobsSpectraS3(CancelAllActiveJobsSpectraS3Request request); void CancelAllJobsSpectraS3(CancelAllJobsSpectraS3Request request); void CancelJobSpectraS3(CancelJobSpectraS3Request request); void ClearAllCanceledJobsSpectraS3(ClearAllCanceledJobsSpectraS3Request request); void ClearAllCompletedJobsSpectraS3(ClearAllCompletedJobsSpectraS3Request request); void TruncateActiveJobSpectraS3(TruncateActiveJobSpectraS3Request request); void TruncateAllActiveJobsSpectraS3(TruncateAllActiveJobsSpectraS3Request request); void TruncateAllJobsSpectraS3(TruncateAllJobsSpectraS3Request request); void TruncateJobSpectraS3(TruncateJobSpectraS3Request request); void VerifySafeToCreatePutJobSpectraS3(VerifySafeToCreatePutJobSpectraS3Request request); void DeleteAzureTargetFailureNotificationRegistrationSpectraS3(DeleteAzureTargetFailureNotificationRegistrationSpectraS3Request request); void DeleteBucketChangesNotificationRegistrationSpectraS3(DeleteBucketChangesNotificationRegistrationSpectraS3Request request); void DeleteDs3TargetFailureNotificationRegistrationSpectraS3(DeleteDs3TargetFailureNotificationRegistrationSpectraS3Request request); void DeleteJobCompletedNotificationRegistrationSpectraS3(DeleteJobCompletedNotificationRegistrationSpectraS3Request request); void DeleteJobCreatedNotificationRegistrationSpectraS3(DeleteJobCreatedNotificationRegistrationSpectraS3Request request); void DeleteJobCreationFailedNotificationRegistrationSpectraS3(DeleteJobCreationFailedNotificationRegistrationSpectraS3Request request); void DeleteObjectCachedNotificationRegistrationSpectraS3(DeleteObjectCachedNotificationRegistrationSpectraS3Request request); void DeleteObjectLostNotificationRegistrationSpectraS3(DeleteObjectLostNotificationRegistrationSpectraS3Request request); void DeleteObjectPersistedNotificationRegistrationSpectraS3(DeleteObjectPersistedNotificationRegistrationSpectraS3Request request); void DeletePoolFailureNotificationRegistrationSpectraS3(DeletePoolFailureNotificationRegistrationSpectraS3Request request); void DeleteS3TargetFailureNotificationRegistrationSpectraS3(DeleteS3TargetFailureNotificationRegistrationSpectraS3Request request); void DeleteStorageDomainFailureNotificationRegistrationSpectraS3(DeleteStorageDomainFailureNotificationRegistrationSpectraS3Request request); void DeleteSystemFailureNotificationRegistrationSpectraS3(DeleteSystemFailureNotificationRegistrationSpectraS3Request request); void DeleteTapeFailureNotificationRegistrationSpectraS3(DeleteTapeFailureNotificationRegistrationSpectraS3Request request); void DeleteTapePartitionFailureNotificationRegistrationSpectraS3(DeleteTapePartitionFailureNotificationRegistrationSpectraS3Request request); void DeleteFolderRecursivelySpectraS3(DeleteFolderRecursivelySpectraS3Request request); void CancelImportOnAllPoolsSpectraS3(CancelImportOnAllPoolsSpectraS3Request request); void CancelVerifyOnAllPoolsSpectraS3(CancelVerifyOnAllPoolsSpectraS3Request request); void CompactAllPoolsSpectraS3(CompactAllPoolsSpectraS3Request request); void DeallocatePoolSpectraS3(DeallocatePoolSpectraS3Request request); void DeletePermanentlyLostPoolSpectraS3(DeletePermanentlyLostPoolSpectraS3Request request); void DeletePoolFailureSpectraS3(DeletePoolFailureSpectraS3Request request); void DeletePoolPartitionSpectraS3(DeletePoolPartitionSpectraS3Request request); void ForcePoolEnvironmentRefreshSpectraS3(ForcePoolEnvironmentRefreshSpectraS3Request request); void FormatAllForeignPoolsSpectraS3(FormatAllForeignPoolsSpectraS3Request request); void ImportAllPoolsSpectraS3(ImportAllPoolsSpectraS3Request request); void ModifyAllPoolsSpectraS3(ModifyAllPoolsSpectraS3Request request); void VerifyAllPoolsSpectraS3(VerifyAllPoolsSpectraS3Request request); void ConvertStorageDomainToDs3TargetSpectraS3(ConvertStorageDomainToDs3TargetSpectraS3Request request); void DeleteStorageDomainFailureSpectraS3(DeleteStorageDomainFailureSpectraS3Request request); void DeleteStorageDomainMemberSpectraS3(DeleteStorageDomainMemberSpectraS3Request request); void DeleteStorageDomainSpectraS3(DeleteStorageDomainSpectraS3Request request); void ForceFeatureKeyValidationSpectraS3(ForceFeatureKeyValidationSpectraS3Request request); void DeletePermanentlyLostTapeSpectraS3(DeletePermanentlyLostTapeSpectraS3Request request); void DeleteTapeDensityDirectiveSpectraS3(DeleteTapeDensityDirectiveSpectraS3Request request); void DeleteTapeDriveSpectraS3(DeleteTapeDriveSpectraS3Request request); void DeleteTapeFailureSpectraS3(DeleteTapeFailureSpectraS3Request request); void DeleteTapePartitionFailureSpectraS3(DeleteTapePartitionFailureSpectraS3Request request); void DeleteTapePartitionSpectraS3(DeleteTapePartitionSpectraS3Request request); void EjectStorageDomainBlobsSpectraS3(EjectStorageDomainBlobsSpectraS3Request request); void ForceTapeEnvironmentRefreshSpectraS3(ForceTapeEnvironmentRefreshSpectraS3Request request); void ImportAllTapesSpectraS3(ImportAllTapesSpectraS3Request request); void ModifyAllTapePartitionsSpectraS3(ModifyAllTapePartitionsSpectraS3Request request); void RawImportAllTapesSpectraS3(RawImportAllTapesSpectraS3Request request); void ForceTargetEnvironmentRefreshSpectraS3(ForceTargetEnvironmentRefreshSpectraS3Request request); void DeleteAzureTargetBucketNameSpectraS3(DeleteAzureTargetBucketNameSpectraS3Request request); void DeleteAzureTargetFailureSpectraS3(DeleteAzureTargetFailureSpectraS3Request request); void DeleteAzureTargetReadPreferenceSpectraS3(DeleteAzureTargetReadPreferenceSpectraS3Request request); void DeleteAzureTargetSpectraS3(DeleteAzureTargetSpectraS3Request request); void ImportAzureTargetSpectraS3(ImportAzureTargetSpectraS3Request request); void ModifyAllAzureTargetsSpectraS3(ModifyAllAzureTargetsSpectraS3Request request); void DeleteDs3TargetFailureSpectraS3(DeleteDs3TargetFailureSpectraS3Request request); void DeleteDs3TargetReadPreferenceSpectraS3(DeleteDs3TargetReadPreferenceSpectraS3Request request); void DeleteDs3TargetSpectraS3(DeleteDs3TargetSpectraS3Request request); void ModifyAllDs3TargetsSpectraS3(ModifyAllDs3TargetsSpectraS3Request request); void PairBackRegisteredDs3TargetSpectraS3(PairBackRegisteredDs3TargetSpectraS3Request request); void DeleteS3TargetBucketNameSpectraS3(DeleteS3TargetBucketNameSpectraS3Request request); void DeleteS3TargetFailureSpectraS3(DeleteS3TargetFailureSpectraS3Request request); void DeleteS3TargetReadPreferenceSpectraS3(DeleteS3TargetReadPreferenceSpectraS3Request request); void DeleteS3TargetSpectraS3(DeleteS3TargetSpectraS3Request request); void ImportS3TargetSpectraS3(ImportS3TargetSpectraS3Request request); void ModifyAllS3TargetsSpectraS3(ModifyAllS3TargetsSpectraS3Request request); void DelegateDeleteUserSpectraS3(DelegateDeleteUserSpectraS3Request request); GetObjectResponse GetObject(GetObjectRequest request); /// <summary> /// For multi-node support (planned), this provides a means of creating /// a client that connects to the specified node id. /// </summary> /// <param name="nodes"></param> /// <returns></returns> IDs3ClientFactory BuildFactory(IEnumerable<JobNode> nodes); } }