context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using System.Diagnostics; using System.Collections.Generic; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.ParameterInfos; using Internal.Reflection.Core.Execution; namespace System.Reflection.Runtime.MethodInfos { // // These methods implement the Get/Set methods on array types. // internal sealed partial class RuntimeSyntheticMethodInfo : RuntimeMethodInfo { private RuntimeSyntheticMethodInfo(SyntheticMethodId syntheticMethodId, String name, RuntimeTypeInfo declaringType, RuntimeTypeInfo[] parameterTypes, RuntimeTypeInfo returnType, InvokerOptions options, Func<Object, Object[], Object> invoker) { _syntheticMethodId = syntheticMethodId; _name = name; _declaringType = declaringType; _options = options; _invoker = invoker; _runtimeParameterTypes = parameterTypes; _returnType = returnType; } public sealed override MethodAttributes Attributes { get { return MethodAttributes.Public | MethodAttributes.PrivateScope; } } public sealed override CallingConventions CallingConvention { get { return CallingConventions.Standard | CallingConventions.HasThis; } } public sealed override IEnumerable<CustomAttributeData> CustomAttributes { get { return Empty<CustomAttributeData>.Enumerable; } } public sealed override bool Equals(Object obj) { RuntimeSyntheticMethodInfo other = obj as RuntimeSyntheticMethodInfo; if (other == null) return false; if (_syntheticMethodId != other._syntheticMethodId) return false; if (!(_declaringType.Equals(other._declaringType))) return false; return true; } public sealed override MethodInfo GetGenericMethodDefinition() { throw new InvalidOperationException(); } public sealed override int GetHashCode() { return _declaringType.GetHashCode(); } public sealed override bool IsConstructedGenericMethod { get { return false; } } public sealed override bool IsGenericMethod { get { return false; } } public sealed override bool IsGenericMethodDefinition { get { return false; } } public sealed override MethodInfo MakeGenericMethod(params Type[] typeArguments) { throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericMethodDefinition, this)); } public sealed override MethodBase MetadataDefinitionMethod { get { throw new NotSupportedException(); } } public sealed override MethodImplAttributes MethodImplementationFlags { get { return MethodImplAttributes.IL; } } public sealed override Module Module { get { return this.DeclaringType.Assembly.ManifestModule; } } public sealed override int MetadataToken { get { throw new InvalidOperationException(SR.NoMetadataTokenAvailable); } } public sealed override Type ReflectedType { get { // The only synthetic methods come from array types which can never be inherited from. So unless that changes, // we don't provide a way to specify the ReflectedType. return DeclaringType; } } public sealed override String ToString() { return RuntimeMethodHelpers.ComputeToString(this, Array.Empty<RuntimeTypeInfo>(), RuntimeParameters, RuntimeReturnParameter); } public sealed override RuntimeMethodHandle MethodHandle { get { throw new PlatformNotSupportedException(); } } protected sealed override MethodInvoker UncachedMethodInvoker { get { RuntimeTypeInfo[] runtimeParameterTypes = _runtimeParameterTypes; RuntimeTypeHandle[] runtimeParameterTypeHandles = new RuntimeTypeHandle[runtimeParameterTypes.Length]; for (int i = 0; i < runtimeParameterTypes.Length; i++) runtimeParameterTypeHandles[i] = runtimeParameterTypes[i].TypeHandle; return ReflectionCoreExecution.ExecutionEnvironment.GetSyntheticMethodInvoker( _declaringType.TypeHandle, runtimeParameterTypeHandles, _options, _invoker); } } internal sealed override RuntimeTypeInfo[] RuntimeGenericArgumentsOrParameters { get { return Array.Empty<RuntimeTypeInfo>(); } } internal sealed override RuntimeTypeInfo RuntimeDeclaringType { get { return _declaringType; } } internal sealed override String RuntimeName { get { return _name; } } internal sealed override RuntimeParameterInfo[] GetRuntimeParameters(RuntimeMethodInfo contextMethod, out RuntimeParameterInfo returnParameter) { RuntimeTypeInfo[] runtimeParameterTypes = _runtimeParameterTypes; RuntimeParameterInfo[] parameters = new RuntimeParameterInfo[runtimeParameterTypes.Length]; for (int i = 0; i < parameters.Length; i++) { parameters[i] = RuntimeSyntheticParameterInfo.GetRuntimeSyntheticParameterInfo(this, i, runtimeParameterTypes[i]); } returnParameter = RuntimeSyntheticParameterInfo.GetRuntimeSyntheticParameterInfo(this, -1, _returnType); return parameters; } internal sealed override RuntimeMethodInfo WithReflectedTypeSetToDeclaringType { get { Debug.Assert(ReflectedType.Equals(DeclaringType)); return this; } } private readonly String _name; private readonly SyntheticMethodId _syntheticMethodId; private readonly RuntimeTypeInfo _declaringType; private readonly RuntimeTypeInfo[] _runtimeParameterTypes; private readonly RuntimeTypeInfo _returnType; private readonly InvokerOptions _options; private readonly Func<Object, Object[], Object> _invoker; } }
// Copyright 2007-2008 The Apache Software Foundation. // // 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.Transports.Msmq.Tests { using System; using System.Threading; using Magnum.DateTimeExtensions; using MassTransit.Tests; using MassTransit.Tests.Messages; using MassTransit.Tests.TestConsumers; using NUnit.Framework; using TestFixtures; [TestFixture, Category("Integration")] public class When_a_message_is_published_to_a_transactional_queue : MsmqTransactionalEndpointTestFixture { private readonly TimeSpan _timeout = TimeSpan.FromSeconds(10); [Test] public void It_should_be_received_by_one_subscribed_consumer() { var consumer = new TestMessageConsumer<PingMessage>(); RemoteBus.Subscribe(consumer); var message = new PingMessage(); LocalBus.Publish(message); consumer.ShouldHaveReceivedMessage(message, _timeout); } [Test] public void It_should_leave_the_message_in_the_queue_if_an_exception_is_thrown() { FutureMessage<PingMessage> future = new FutureMessage<PingMessage>(); RemoteBus.Subscribe<PingMessage>(m => { future.Set(m); throw new ApplicationException("Boing!"); }); var message = new PingMessage(); LocalBus.Publish(message); future.IsAvailable(_timeout).ShouldBeTrue("Message was not received"); RemoteEndpoint.ShouldNotContain(message); } [Test] public void It_should_not_rollback_a_send_if_an_exception_is_thrown() { var consumer = new TestMessageConsumer<PongMessage>(); LocalBus.Subscribe(consumer); var message = new PingMessage(); var response = new PongMessage(message.CorrelationId); RemoteBus.Subscribe<PingMessage>(m => { RemoteBus.Publish(response); throw new ApplicationException("Boing!"); }); LocalBus.Publish(message); consumer.ShouldHaveReceivedMessage(response, _timeout); } } [TestFixture, Category("Integration")] public class When_publishing_a_message : MsmqEndpointTestFixture { [Test] public void Multiple_Local_Services_Should_Be_Available() { ManualResetEvent _updateEvent = new ManualResetEvent(false); LocalBus.Subscribe<UpdateMessage>(msg => _updateEvent.Set()); ManualResetEvent _deleteEvent = new ManualResetEvent(false); LocalBus.Subscribe<DeleteMessage>( delegate { _deleteEvent.Set(); }); DeleteMessage dm = new DeleteMessage(); LocalBus.Publish(dm); UpdateMessage um = new UpdateMessage(); LocalBus.Publish(um); Assert.That(_deleteEvent.WaitOne(TimeSpan.FromSeconds(4), true), Is.True, "Timeout expired waiting for message"); Assert.That(_updateEvent.WaitOne(TimeSpan.FromSeconds(4), true), Is.True, "Timeout expired waiting for message"); } [Test] public void Multiple_messages_should_be_delivered_to_the_appropriate_remote_subscribers() { ManualResetEvent _updateEvent = new ManualResetEvent(false); RemoteBus.Subscribe<UpdateMessage>( delegate { _updateEvent.Set(); }); ManualResetEvent _deleteEvent = new ManualResetEvent(false); RemoteBus.Subscribe<DeleteMessage>( delegate { _deleteEvent.Set(); }); DeleteMessage dm = new DeleteMessage(); LocalBus.Publish(dm); UpdateMessage um = new UpdateMessage(); LocalBus.Publish(um); Assert.That(_deleteEvent.WaitOne(TimeSpan.FromSeconds(6), true), Is.True, "Timeout expired waiting for message"); Assert.That(_updateEvent.WaitOne(TimeSpan.FromSeconds(6), true), Is.True, "Timeout expired waiting for message"); } [Test] public void The_message_should_be_delivered_to_a_local_subscriber() { ManualResetEvent _updateEvent = new ManualResetEvent(false); LocalBus.Subscribe<UpdateMessage>( delegate { _updateEvent.Set(); }); UpdateMessage um = new UpdateMessage(); LocalBus.Publish(um); Assert.That(_updateEvent.WaitOne(TimeSpan.FromSeconds(3), true), Is.True, "Timeout expired waiting for message"); } [Test] public void The_message_should_be_delivered_to_a_remote_subscriber() { ManualResetEvent _updateEvent = new ManualResetEvent(false); RemoteBus.Subscribe<UpdateMessage>( delegate { _updateEvent.Set(); }); UpdateMessage um = new UpdateMessage(); LocalBus.Publish(um); Assert.That(_updateEvent.WaitOne(TimeSpan.FromSeconds(3), true), Is.True, "Timeout expired waiting for message"); } [Test] public void The_message_should_be_delivered_to_a_remote_subscriber_with_a_reply() { ManualResetEvent _updateEvent = new ManualResetEvent(false); Action<UpdateMessage> handler = msg => { _updateEvent.Set(); RemoteBus.Publish(new UpdateAcceptedMessage()); }; ManualResetEvent _repliedEvent = new ManualResetEvent(false); RemoteBus.Subscribe(handler); LocalBus.Subscribe<UpdateAcceptedMessage>( delegate { _repliedEvent.Set(); }); UpdateMessage um = new UpdateMessage(); LocalBus.Publish(um); Assert.That(_updateEvent.WaitOne(TimeSpan.FromSeconds(3), true), Is.True, "Timeout expired waiting for message"); Assert.That(_repliedEvent.WaitOne(TimeSpan.FromSeconds(3), true), Is.True, "NO response message received"); } } [TestFixture, Category("Integration")] public class When_an_accept_method_throws_an_exception : MsmqEndpointTestFixture { [Test] public void The_exception_should_not_disrupt_the_flow_of_messages() { CrashingService service = new CrashingService(); LocalBus.Subscribe(service); LocalEndpoint.Send(new BogusMessage()); CrashingService.Received.WaitOne(5.Seconds(), true).ShouldBeTrue("No message received"); CrashingService.Received.Reset(); LocalEndpoint.Send(new LegitMessage()); CrashingService.LegitReceived.WaitOne(5.Seconds(), true).ShouldBeTrue("No message received"); } internal class CrashingService : Consumes<BogusMessage>.All, Consumes<LegitMessage>.All { public static ManualResetEvent Received { get { return _received; } } private static readonly ManualResetEvent _received = new ManualResetEvent(false); public static ManualResetEvent LegitReceived { get { return _legitReceived; } } private static readonly ManualResetEvent _legitReceived = new ManualResetEvent(false); public void Consume(BogusMessage message) { _received.Set(); throw new ApplicationException("Consumer goes boom!"); } public void Consume(LegitMessage message) { _legitReceived.Set(); } } [Serializable] internal class BogusMessage { } [Serializable] internal class LegitMessage { } } [TestFixture, Category("Integration")] public class When_receiving_messages_slowly : MsmqEndpointTestFixture { private readonly TimeSpan _timeout = TimeSpan.FromSeconds(10); [Test] public void It_should_be_received_by_one_subscribed_consumer() { var consumer = new TestMessageConsumer<PingMessage>(); RemoteBus.Subscribe(consumer); Thread.Sleep(5.Seconds()); var message = new PingMessage(); LocalBus.Publish(message); consumer.ShouldHaveReceivedMessage(message, _timeout); } } }
using System; using System.Net; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Orleans; using Orleans.Configuration; using Orleans.Configuration.Internal; using Orleans.Configuration.Validators; using Orleans.Hosting; using Orleans.Runtime; using Orleans.Statistics; using UnitTests.Grains; using Xunit; namespace NonSilo.Tests { public class NoOpMembershipTable : IMembershipTable { public Task CleanupDefunctSiloEntries(DateTimeOffset beforeDate) { return Task.CompletedTask; } public Task DeleteMembershipTableEntries(string clusterId) { return Task.CompletedTask; } public Task InitializeMembershipTable(bool tryInitTableVersion) { return Task.CompletedTask; } public Task<bool> InsertRow(MembershipEntry entry, TableVersion tableVersion) { return Task.FromResult(true); } public Task<MembershipTableData> ReadAll() { throw new NotImplementedException(); } public Task<MembershipTableData> ReadRow(SiloAddress key) { throw new NotImplementedException(); } public Task UpdateIAmAlive(MembershipEntry entry) { return Task.CompletedTask; } public Task<bool> UpdateRow(MembershipEntry entry, string etag, TableVersion tableVersion) { return Task.FromResult(true); } } /// <summary> /// Tests for <see cref="ISiloBuilder"/>. /// </summary> [TestCategory("BVT")] [TestCategory("Hosting")] public class SiloBuilderTests { [Fact] public void SiloBuilderTest() { var host = new HostBuilder() .UseOrleans((ctx, siloBuilder) => { siloBuilder .UseLocalhostClustering() .Configure<ClusterOptions>(options => options.ClusterId = "someClusterId") .Configure<EndpointOptions>(options => options.AdvertisedIPAddress = IPAddress.Loopback); }) .UseDefaultServiceProvider((context, options) => { options.ValidateScopes = true; options.ValidateOnBuild = true; }) .Build(); var clusterClient = host.Services.GetRequiredService<IClusterClient>(); } /// <summary> /// Tests that a silo cannot be created without specifying a ClusterId and a ServiceId. /// </summary> [Fact] public async Task SiloBuilder_ClusterOptionsTest() { await Assert.ThrowsAsync<OrleansConfigurationException>(async () => { await new HostBuilder().UseOrleans(siloBuilder => { siloBuilder .Configure<EndpointOptions>(options => options.AdvertisedIPAddress = IPAddress.Loopback) .ConfigureServices(services => services.AddSingleton<IMembershipTable, NoOpMembershipTable>()); }).RunConsoleAsync(); }); await Assert.ThrowsAsync<OrleansConfigurationException>(async () => { await new HostBuilder().UseOrleans(siloBuilder => { siloBuilder .Configure<ClusterOptions>(options => options.ClusterId = "someClusterId") .Configure<EndpointOptions>(options => options.AdvertisedIPAddress = IPAddress.Loopback) .ConfigureServices(services => services.AddSingleton<IMembershipTable, NoOpMembershipTable>()); }).RunConsoleAsync(); }); await Assert.ThrowsAsync<OrleansConfigurationException>(async () => { await new HostBuilder().UseOrleans(siloBuilder => { siloBuilder .Configure<ClusterOptions>(options => options.ServiceId = "someServiceId") .Configure<EndpointOptions>(options => options.AdvertisedIPAddress = IPAddress.Loopback) .ConfigureServices(services => services.AddSingleton<IMembershipTable, NoOpMembershipTable>()); }).RunConsoleAsync(); }); } /// <summary> /// Grain's CollectionAgeLimit must be > 0 minutes. /// </summary> [Fact] public async Task SiloBuilder_GrainCollectionOptionsForZeroSecondsAgeLimitTest() { await Assert.ThrowsAsync<OrleansConfigurationException>(async () => { await new HostBuilder().UseOrleans(siloBuilder => { siloBuilder .Configure<ClusterOptions>(options => { options.ClusterId = "GrainCollectionClusterId"; options.ServiceId = "GrainCollectionServiceId"; }) .Configure<EndpointOptions>(options => options.AdvertisedIPAddress = IPAddress.Loopback) .ConfigureServices(services => services.AddSingleton<IMembershipTable, NoOpMembershipTable>()) .Configure<GrainCollectionOptions>(options => options .ClassSpecificCollectionAge .Add(typeof(CollectionSpecificAgeLimitForZeroSecondsActivationGcTestGrain).FullName, TimeSpan.Zero)); }).RunConsoleAsync(); }); } /// <summary> /// Ensures <see cref="LoadSheddingValidator"/> fails when LoadSheddingLimit greater than 100. /// </summary> [Fact] public async Task SiloBuilder_LoadSheddingValidatorAbove100ShouldFail() { await Assert.ThrowsAsync<OrleansConfigurationException>(async () => { await new HostBuilder().UseOrleans(siloBuilder => { siloBuilder .ConfigureDefaults() .UseLocalhostClustering() .Configure<ClusterOptions>(options => options.ClusterId = "someClusterId") .Configure<EndpointOptions>(options => options.AdvertisedIPAddress = IPAddress.Loopback) .ConfigureServices(services => services.AddSingleton<IMembershipTable, NoOpMembershipTable>()) .Configure<LoadSheddingOptions>(options => { options.LoadSheddingEnabled = true; options.LoadSheddingLimit = 101; }) .ConfigureServices(svcCollection => { svcCollection.AddSingleton<FakeHostEnvironmentStatistics>(); svcCollection.AddFromExisting<IHostEnvironmentStatistics, FakeHostEnvironmentStatistics>(); svcCollection.AddTransient<IConfigurationValidator, LoadSheddingValidator>(); }); }).RunConsoleAsync(); }); } /// <summary> /// Ensures <see cref="LoadSheddingValidator"/> fails validation when invalid/no instance of /// <see cref="IHostEnvironmentStatistics"/> is registered using otherwise valid <see cref="LoadSheddingOptions"/>. /// </summary> [Fact] public async Task SiloBuilder_LoadSheddingValidatorFailsWithNoRegisteredHostEnvironmentStatistics() { await Assert.ThrowsAsync<OrleansConfigurationException>(async () => { await new HostBuilder().UseOrleans(siloBuilder => { siloBuilder .ConfigureDefaults() .UseLocalhostClustering() .Configure<ClusterOptions>(options => options.ClusterId = "someClusterId") .Configure<EndpointOptions>(options => options.AdvertisedIPAddress = IPAddress.Loopback) .ConfigureServices(services => services.AddSingleton<IMembershipTable, NoOpMembershipTable>()) .Configure<LoadSheddingOptions>(options => { options.LoadSheddingEnabled = true; options.LoadSheddingLimit = 95; }).ConfigureServices(svcCollection => { svcCollection.AddTransient<IConfigurationValidator, LoadSheddingValidator>(); }); }).RunConsoleAsync(); }); } [Fact] public async Task SiloBuilderThrowsDuringStartupIfNoGrainsAdded() { using var host = new HostBuilder() .UseOrleans(siloBuilder => { // Add only an assembly with generated serializers but no grain interfaces or grain classes siloBuilder.UseLocalhostClustering() .Configure<GrainTypeOptions>(options => { options.Classes.Clear(); options.Interfaces.Clear(); }); }).Build(); await Assert.ThrowsAsync<OrleansConfigurationException>(() => host.StartAsync()); } private class FakeHostEnvironmentStatistics : IHostEnvironmentStatistics { public long? TotalPhysicalMemory => 0; public float? CpuUsage => 0; public long? AvailableMemory => 0; } private class MyService { public int Id { get; set; } } } }
using System; using System.ComponentModel; #if __UNIFIED__ using CoreAnimation; using CoreGraphics; using Foundation; using UIKit; #else using MonoTouch.CoreAnimation; using MonoTouch.CoreGraphics; using MonoTouch.Foundation; using MonoTouch.UIKit; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using nfloat = System.Single; #endif namespace PullToBounce { [DesignTimeVisible(true), Category("Controls")] [Register("PullToBounceWrapper")] public class PullToBounceWrapper : UIView { private static NSString observerContext = new NSString(); private static NSString contentOffsetKeyPath = (NSString)"contentOffset"; private BounceView bounceView; private nfloat pullDistance; private UIScrollView scrollView; public PullToBounceWrapper() { Setup(); } public PullToBounceWrapper(IntPtr handle) : base(handle) { Setup(); } public PullToBounceWrapper(NSCoder coder) : base(coder) { Setup(); } public PullToBounceWrapper(CGRect frame) : base(frame) { Setup(); } private void Setup() { bounceView = new BounceView(); AddSubview(bounceView); WaveBounceDuration = 0.8; BallSize = 36f; PullDistance = 96f; BendDistance = 40f; BallMovementTimingFunction = CAMediaTimingFunction.FromControlPoints(0.49f, 0.13f, 0.29f, 1.61f); BallMoveUpDuration = 0.25; } public override void SubviewAdded(UIView uiview) { base.SubviewAdded(uiview); var scroll = uiview as UIScrollView; if (scroll != null) { if (scrollView != null) { throw new InvalidOperationException("Cannot add multiple UIScrollView sub views to PullToBounceWrapper."); } scrollView = scroll; scrollView.AddObserver(this, contentOffsetKeyPath, NSKeyValueObservingOptions.Initial, observerContext.Handle); } } public override void WillRemoveSubview(UIView uiview) { if (uiview == scrollView) { scrollView.RemoveObserver(this, contentOffsetKeyPath, observerContext.Handle); scrollView = null; } base.WillRemoveSubview(uiview); } [Browsable(true)] [Export("BallColor")] public UIColor BallColor { get { return bounceView.BallColor; } set { bounceView.BallColor = value; } } [Browsable(true)] [Export("WaveColor")] public UIColor WaveColor { get { return bounceView.WaveColor; } set { bounceView.WaveColor = value; } } [Browsable(true)] [Export("WaveBounceDuration")] public double WaveBounceDuration { get { return bounceView.WaveBounceDuration; } set { bounceView.WaveBounceDuration = value; } } [Browsable(true)] [Export("BallMoveUpDuration")] public double BallMoveUpDuration { get { return bounceView.BallMoveUpDuration; } set { bounceView.BallMoveUpDuration = value; } } public CAMediaTimingFunction BallMovementTimingFunction { get { return bounceView.BallMovementTimingFunction; } set { bounceView.BallMovementTimingFunction = value; } } [Browsable(true)] [Export("BallSize")] public nfloat BallSize { get { return bounceView.BallSize; } set { bounceView.BallSize = value; bounceView.BallMoveUpDistance = BallMoveUpDistance; } } [Browsable(true)] [Export("PullDistance")] public nfloat PullDistance { get { return pullDistance; } set { pullDistance = value; bounceView.BallMoveUpDistance = BallMoveUpDistance; } } [Browsable(true)] [Export("BendDistance")] public nfloat BendDistance { get; set; } private nfloat StopPosition { get { return PullDistance + BendDistance; } } private nfloat BallMoveUpDistance { get { return PullDistance / 2f + BallSize / 2f; } } public UIScrollView ScrollView { get { return scrollView; } } public event EventHandler RefreshStarted; public override void LayoutSubviews() { base.LayoutSubviews(); SendSubviewToBack(bounceView); bounceView.Frame = new CGRect(CGPoint.Empty, Frame.Size); } protected override void Dispose(bool disposing) { if (scrollView != null) { scrollView.RemoveObserver(this, contentOffsetKeyPath, observerContext.Handle); } base.Dispose(disposing); } protected virtual void OnRefreshStarted() { var handler = RefreshStarted; if (handler != null) { handler(this, EventArgs.Empty); } } private void ScrollViewDidScroll() { if (ScrollView != null) { if (ScrollView.ContentOffset.Y < 0) { var y = -ScrollView.ContentOffset.Y; if (y < PullDistance) { bounceView.Frame = new CGRect(new CGPoint(bounceView.Frame.X, y), bounceView.Frame.Size); bounceView.Wave(0); ScrollView.Alpha = (PullDistance - y) / PullDistance; } else if (y < StopPosition) { bounceView.Wave(y - PullDistance); ScrollView.Alpha = 0; } else if (y > StopPosition) { ScrollView.ScrollEnabled = false; ScrollView.SetContentOffset(new CGPoint(ScrollView.ContentOffset.X, -StopPosition), false); bounceView.Frame = new CGRect(new CGPoint(bounceView.Frame.X, PullDistance), bounceView.Frame.Size); bounceView.Wave(StopPosition - PullDistance); bounceView.DidRelease(StopPosition - PullDistance); OnRefreshStarted(); ScrollView.Alpha = 0; } } else { bounceView.Frame = new CGRect(new CGPoint(bounceView.Frame.X, 0), bounceView.Frame.Size); ScrollView.Alpha = 1; } } } public void StopLoadingAnimation() { bounceView.EndingAnimation(() => { if (ScrollView != null) { ScrollView.SetContentOffset(new CGPoint(0, 0), true); ScrollView.ScrollEnabled = true; } }); } public override void ObserveValue(NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context) { if (observerContext.Handle == context && keyPath == contentOffsetKeyPath && ofObject == ScrollView) { ScrollViewDidScroll(); } else { base.ObserveValue(keyPath, ofObject, change, context); } } } }
// Copyright 2015-2016 Google Inc. All Rights Reserved. // Licensed under the Apache License Version 2.0. using Google.Apis.Compute.v1.Data; using Google.PowerShell.Common; using System.Collections; using System.Collections.Generic; using System.Management.Automation; namespace Google.PowerShell.ComputeEngine { /// <summary> /// This abstract class describes all of the information needed to create an instance template description. /// It is extended by AddGceInstanceTemplateCmdlet, which sends an instance template description to the /// server, and by GceInstanceDescriptionCmdlet to provide a unifed set of parameters for instances and /// instance templates. /// </summary> public abstract class GceTemplateDescriptionCmdlet : GceConcurrentCmdlet { /// <summary> /// The name of the instance or instance template. /// </summary> public abstract string Name { get; set; } /// <summary> /// The name of the machine type for the instances. /// </summary> public abstract string MachineType { get; set; } /// <summary> /// Enables instances to send and receive packets for IP addresses other than their own. Switch on if /// this instance will be used as an IP gateway or it will be set as the next-hop in a Route /// resource. /// </summary> public abstract SwitchParameter CanIpForward { get; set; } /// <summary> /// Human readable description. /// </summary> public abstract string Description { get; set; } /// <summary> /// The the image used to create the boot disk. Use Get-GceImage to get one of these. /// </summary> public abstract Image BootDiskImage { get; set; } /// <summary> /// An existing disk to attach. It will be attached in read-only mode. /// </summary> public abstract Disk[] ExtraDisk { get; set; } /// <summary> /// An AttachedDisk object specifying a disk to attach. Do not specify `-BootDiskImage` or /// `-BootDiskSnapshot` if this is a boot disk. You can build one using New-GceAttachedDiskConfig. /// </summary> public abstract AttachedDisk[] Disk { get; set; } /// <summary> /// <para type="description"> /// The keys and values of the Metadata of this instance. /// </para> /// </summary> public abstract IDictionary Metadata { get; set; } /// <summary> /// The name of the network to use. If not specified, it is global/networks/default. /// </summary> public abstract string Network { get; set; } /// <summary> /// The region of the subnetwork. /// </summary> public abstract string Region { get; set; } /// <summary> /// (Optional) The name of the subnetwork to use. /// </summary> public abstract string Subnetwork { get; set; } /// <summary> /// If set, the instance will not have an external ip address. /// </summary> public abstract SwitchParameter NoExternalIp { get; set; } /// <summary> /// If set, the instance will be preemptible, and AutomaticRestart will be false. /// </summary> public abstract SwitchParameter Preemptible { get; set; } /// <summary> /// If set, the instance will not restart when shut down by Google Compute Engine. /// </summary> public abstract bool AutomaticRestart { get; set; } /// <summary> /// If set, the instance will terminate rather than migrate when the host undergoes maintenance. /// </summary> public abstract SwitchParameter TerminateOnMaintenance { get; set; } /// <summary> /// The ServiceAccount used to specify access tokens. Use New-GceServiceAccountConfig to build one. /// </summary> public abstract ServiceAccount[] ServiceAccount { get; set; } /// <summary> /// A tag of this instance. /// </summary> public abstract string[] Tag { get; set; } /// <summary> /// Builds a network interface given the Network and NoExternalIp parameters. /// </summary> /// <returns> /// The NetworkInsterface object to use in the instance template description. /// </returns> protected virtual NetworkInterface BuildNetworkInterfaces() { var accessConfigs = new List<AccessConfig>(); if (!NoExternalIp) { accessConfigs.Add(new AccessConfig { Name = "External NAT", Type = "ONE_TO_ONE_NAT" }); } string networkUri = Network; if (string.IsNullOrEmpty(networkUri)) { networkUri = "default"; } networkUri = ConstructNetworkName(networkUri, Project); NetworkInterface result = new NetworkInterface { Network = networkUri, AccessConfigs = accessConfigs }; if (Subnetwork != null) { if (!Subnetwork.Contains($"regions/{Region}/subnetworks/")) { Subnetwork = $"regions/{Region}/subnetworks/{Subnetwork}"; } result.Subnetwork = Subnetwork; } return result; } /// <summary> /// Creates a list of AttachedDisk objects form Disk, BootDiskImage, and ExtraDis. /// </summary> /// <returns> /// A list of AttachedDisk objects to be used in the instance template description. /// </returns> protected virtual IList<AttachedDisk> BuildAttachedDisks() { var disks = new List<AttachedDisk>(); if (Disk != null) { disks.AddRange(Disk); } if (BootDiskImage != null) { disks.Add(new AttachedDisk { Boot = true, AutoDelete = true, InitializeParams = new AttachedDiskInitializeParams { SourceImage = BootDiskImage.SelfLink } }); } if (ExtraDisk != null) { foreach (Disk disk in ExtraDisk) { disks.Add(new AttachedDisk { Source = disk.SelfLink, Mode = "READ_ONLY" }); } } return disks; } /// <summary> /// Builds an InstanceTemplate from parameter values. /// </summary> /// <returns> /// An InstanceTemplate to be sent to Google Compute Engine as part of a insert instance template /// request. /// </returns> protected InstanceTemplate BuildInstanceTemplate() { return new InstanceTemplate { Name = Name, Description = Description, Properties = new InstanceProperties { CanIpForward = CanIpForward, Description = Description, Disks = BuildAttachedDisks(), MachineType = MachineType, Metadata = InstanceMetadataPSConverter.BuildMetadata(Metadata), NetworkInterfaces = new List<NetworkInterface> { BuildNetworkInterfaces() }, Scheduling = new Scheduling { AutomaticRestart = AutomaticRestart && !Preemptible, Preemptible = Preemptible, OnHostMaintenance = TerminateOnMaintenance ? "TERMINATE" : "MIGRATE" }, ServiceAccounts = ServiceAccount, Tags = new Tags { Items = Tag } } }; } } /// <summary> /// Base cmdlet class indicating what parameters are needed to describe an instance. Used by /// NewGceInstanceConfigCmdlet and AdGceInstanceCmdlet to provide a unified way to build an instance /// description. /// </summary> public abstract class GceInstanceDescriptionCmdlet : GceTemplateDescriptionCmdlet { /// <summary> /// The persistant disk to use as a boot disk. Use Get-GceDisk to get one of these. /// </summary> public abstract Disk BootDisk { get; set; } /// <summary> /// <para type="description"> /// The static ip address this instance will have. /// </para> /// </summary> public abstract string Address { get; set; } /// <summary> /// Extend the parent BuildAttachedDisks by optionally appending a disk from the BootDisk attribute. /// </summary> /// <returns> /// A list of AttachedDisk objects to be used in the instance description. /// </returns> protected override IList<AttachedDisk> BuildAttachedDisks() { IList<AttachedDisk> disks = base.BuildAttachedDisks(); if (BootDisk != null) { disks.Add(new AttachedDisk { Boot = true, AutoDelete = false, Source = BootDisk.SelfLink }); } return disks; } /// <summary> /// Extends the parent BuildnetworkInterfaces by adding the static address to the network interface. /// </summary> /// <returns> /// The NetworkInsterface object to use in the instance description. /// </returns> protected override NetworkInterface BuildNetworkInterfaces() { NetworkInterface networkInterface = base.BuildNetworkInterfaces(); networkInterface.NetworkIP = Address; return networkInterface; } /// <summary> /// Builds the instance description based on the cmdlet parameters. /// </summary> /// <returns> /// An Instance object to be sent to Google Compute Engine as part of an insert instance request. /// </returns> protected Instance BuildInstance() { return new Instance { Name = Name, CanIpForward = CanIpForward, Description = Description, Disks = BuildAttachedDisks(), MachineType = MachineType, Metadata = InstanceMetadataPSConverter.BuildMetadata(Metadata), NetworkInterfaces = new List<NetworkInterface> { BuildNetworkInterfaces() }, Scheduling = new Scheduling { AutomaticRestart = AutomaticRestart && !Preemptible, Preemptible = Preemptible, OnHostMaintenance = TerminateOnMaintenance ? "TERMINATE" : "MIGRATE" }, ServiceAccounts = ServiceAccount, Tags = new Tags { Items = Tag } }; } } }
/* * (c) 2008 MOSA - The Managed Operating System Alliance * * Licensed under the terms of the New BSD License. * * Authors: * Phil Garcia (tgiphil) <[email protected]> * Simon Wollwage (rootnode) <[email protected]> */ using System.Diagnostics; using Mosa.Compiler.Framework; using Mosa.Compiler.Framework.Platform; namespace Mosa.Platform.x86.Stages { /// <summary> /// /// </summary> public sealed class SimplePeepholeOptimizationStage : BaseTransformationStage, IMethodCompilerStage, IPlatformStage { #region Window Class /// <summary> /// Window Class /// </summary> public class Window { private int _length; private Context[] _history; private int _size; /// <summary> /// Initializes a new instance of the <see cref="Window"/> class. /// </summary> /// <param name="length">The length.</param> public Window(int length) { _length = length; _history = new Context[length]; _size = 0; } /// <summary> /// Gets the size. /// </summary> /// <value>The size.</value> public int Size { get { return _size; } } /// <summary> /// Nexts the specified CTX. /// </summary> /// <param name="ctx">The CTX.</param> public void Add(Context ctx) { for (int i = _length - 1; i > 0; i--) _history[i] = _history[i - 1]; _history[0] = ctx.Clone(); if (_size < _length) _size++; } /// <summary> /// Deletes the current. /// </summary> public void DeleteCurrent() { _history[0].Remove(); _size--; for (int i = 0; i < _size; i++) _history[i] = _history[i + 1]; } /// <summary> /// Deletes the previous. /// </summary> public void DeletePrevious() { _history[1].Remove(); _size--; for (int i = 1; i < _size; i++) _history[i] = _history[i + 1]; } /// <summary> /// Deletes the previous previous. /// </summary> public void DeletePreviousPrevious() { _history[2].Remove(); _size--; for (int i = 2; i < _size; i++) _history[i] = _history[i + 1]; } /// <summary> /// Gets the current. /// </summary> /// <value>The current.</value> public Context Current { get { if (_size == 0) return null; else return _history[0]; } } /// <summary> /// Gets the previous. /// </summary> /// <value>The previous.</value> public Context Previous { get { if (_size < 2) return null; else return _history[1]; } } /// <summary> /// Gets the previous previous. /// </summary> /// <value>The previous previous.</value> public Context PreviousPrevious { get { if (_size < 3) return null; else return _history[2]; } } } #endregion Window Class #region IMethodCompilerStage Members /// <summary> /// Performs stage specific processing on the compiler context. /// </summary> void IMethodCompilerStage.Run() { Window window = new Window(5); foreach (BasicBlock block in basicBlocks) for (Context ctx = CreateContext(block); !ctx.EndOfInstruction; ctx.GotoNext()) if (!ctx.IsEmpty) { window.Add(ctx); RemoveNop(window); RemoveMultipleStores(window); RemoveSingleLineJump(window); ImproveBranchAndJump(window); } } #endregion IMethodCompilerStage Members /// <summary> /// Removes the nop. /// </summary> /// <param name="window">The window.</param> /// <returns></returns> private bool RemoveNop(Window window) { if (window.Size < 1) return false; if (!(window.Current.Instruction is Instructions.Nop)) return false; window.DeleteCurrent(); return true; } /// <summary> /// Remove multiple occuring stores, for e.g. before: /// <code> /// mov eax, operand /// mov operand, eax /// </code> /// after: /// <code> /// mov eax, operand /// </code> /// </summary> /// <param name="window">The window.</param> /// <returns>True if an instruction has been removed</returns> private bool RemoveMultipleStores(Window window) { if (window.Size < 2) return false; if (window.Current.BasicBlock != window.Previous.BasicBlock) return false; if (!(window.Current.Instruction is Instructions.Mov && window.Previous.Instruction is Instructions.Mov)) return false; if (!(window.Previous.Result == window.Current.Operand1 && window.Previous.Operand1 == window.Current.Result)) return false; window.DeleteCurrent(); return true; } /// <summary> /// Removes the single line jump. /// </summary> /// <param name="window">The window.</param> /// <returns></returns> private bool RemoveSingleLineJump(Window window) { if (window.Size < 2) return false; if (!(window.Previous.Instruction is Instructions.Jmp)) return false; if (window.Current.BasicBlock == window.Previous.BasicBlock) return false; if (window.Previous.BranchTargets[0] != window.Current.BasicBlock.Label) return false; window.DeletePrevious(); return true; } /// <summary> /// Improves the branch and jump. /// </summary> /// <param name="window">The window.</param> /// <returns></returns> private bool ImproveBranchAndJump(Window window) { if (window.Size < 3) return false; if (!(window.Previous.Instruction is Instructions.Jmp)) return false; if (!(window.PreviousPrevious.Instruction is Instructions.Branch)) return false; if (window.Previous.BasicBlock != window.PreviousPrevious.BasicBlock) return false; if (window.Current.BasicBlock == window.Previous.BasicBlock) return false; if (window.PreviousPrevious.BranchTargets[0] != window.Current.BasicBlock.Label) return false; Debug.Assert(window.PreviousPrevious.BranchTargets.Length == 1); // Negate branch condition window.PreviousPrevious.ConditionCode = GetOppositeConditionCode(window.PreviousPrevious.ConditionCode); // Change branch target window.PreviousPrevious.BranchTargets[0] = window.Previous.BranchTargets[0]; // Delete jump window.DeletePrevious(); return true; } } }
namespace android.telephony { [global::MonoJavaBridge.JavaClass()] public partial class ServiceState : java.lang.Object, android.os.Parcelable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static ServiceState() { InitJNI(); } protected ServiceState(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _equals7405; public override bool equals(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.telephony.ServiceState._equals7405, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.telephony.ServiceState.staticClass, global::android.telephony.ServiceState._equals7405, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toString7406; public override global::java.lang.String toString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.telephony.ServiceState._toString7406)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.telephony.ServiceState.staticClass, global::android.telephony.ServiceState._toString7406)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _hashCode7407; public override int hashCode() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.telephony.ServiceState._hashCode7407); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.telephony.ServiceState.staticClass, global::android.telephony.ServiceState._hashCode7407); } internal static global::MonoJavaBridge.MethodId _getState7408; public virtual int getState() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.telephony.ServiceState._getState7408); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.telephony.ServiceState.staticClass, global::android.telephony.ServiceState._getState7408); } internal static global::MonoJavaBridge.MethodId _setState7409; public virtual void setState(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.telephony.ServiceState._setState7409, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.telephony.ServiceState.staticClass, global::android.telephony.ServiceState._setState7409, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _writeToParcel7410; public virtual void writeToParcel(android.os.Parcel arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.telephony.ServiceState._writeToParcel7410, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.telephony.ServiceState.staticClass, global::android.telephony.ServiceState._writeToParcel7410, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _describeContents7411; public virtual int describeContents() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.telephony.ServiceState._describeContents7411); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.telephony.ServiceState.staticClass, global::android.telephony.ServiceState._describeContents7411); } internal static global::MonoJavaBridge.MethodId _copyFrom7412; protected virtual void copyFrom(android.telephony.ServiceState arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.telephony.ServiceState._copyFrom7412, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.telephony.ServiceState.staticClass, global::android.telephony.ServiceState._copyFrom7412, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getRoaming7413; public virtual bool getRoaming() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.telephony.ServiceState._getRoaming7413); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.telephony.ServiceState.staticClass, global::android.telephony.ServiceState._getRoaming7413); } internal static global::MonoJavaBridge.MethodId _getOperatorAlphaLong7414; public virtual global::java.lang.String getOperatorAlphaLong() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.telephony.ServiceState._getOperatorAlphaLong7414)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.telephony.ServiceState.staticClass, global::android.telephony.ServiceState._getOperatorAlphaLong7414)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getOperatorAlphaShort7415; public virtual global::java.lang.String getOperatorAlphaShort() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.telephony.ServiceState._getOperatorAlphaShort7415)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.telephony.ServiceState.staticClass, global::android.telephony.ServiceState._getOperatorAlphaShort7415)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getOperatorNumeric7416; public virtual global::java.lang.String getOperatorNumeric() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.telephony.ServiceState._getOperatorNumeric7416)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.telephony.ServiceState.staticClass, global::android.telephony.ServiceState._getOperatorNumeric7416)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getIsManualSelection7417; public virtual bool getIsManualSelection() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.telephony.ServiceState._getIsManualSelection7417); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.telephony.ServiceState.staticClass, global::android.telephony.ServiceState._getIsManualSelection7417); } internal static global::MonoJavaBridge.MethodId _setStateOutOfService7418; public virtual void setStateOutOfService() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.telephony.ServiceState._setStateOutOfService7418); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.telephony.ServiceState.staticClass, global::android.telephony.ServiceState._setStateOutOfService7418); } internal static global::MonoJavaBridge.MethodId _setStateOff7419; public virtual void setStateOff() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.telephony.ServiceState._setStateOff7419); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.telephony.ServiceState.staticClass, global::android.telephony.ServiceState._setStateOff7419); } internal static global::MonoJavaBridge.MethodId _setRoaming7420; public virtual void setRoaming(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.telephony.ServiceState._setRoaming7420, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.telephony.ServiceState.staticClass, global::android.telephony.ServiceState._setRoaming7420, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setOperatorName7421; public virtual void setOperatorName(java.lang.String arg0, java.lang.String arg1, java.lang.String arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.telephony.ServiceState._setOperatorName7421, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.telephony.ServiceState.staticClass, global::android.telephony.ServiceState._setOperatorName7421, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _setIsManualSelection7422; public virtual void setIsManualSelection(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.telephony.ServiceState._setIsManualSelection7422, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.telephony.ServiceState.staticClass, global::android.telephony.ServiceState._setIsManualSelection7422, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _ServiceState7423; public ServiceState() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.telephony.ServiceState.staticClass, global::android.telephony.ServiceState._ServiceState7423); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _ServiceState7424; public ServiceState(android.telephony.ServiceState arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.telephony.ServiceState.staticClass, global::android.telephony.ServiceState._ServiceState7424, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _ServiceState7425; public ServiceState(android.os.Parcel arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.telephony.ServiceState.staticClass, global::android.telephony.ServiceState._ServiceState7425, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } public static int STATE_IN_SERVICE { get { return 0; } } public static int STATE_OUT_OF_SERVICE { get { return 1; } } public static int STATE_EMERGENCY_ONLY { get { return 2; } } public static int STATE_POWER_OFF { get { return 3; } } internal static global::MonoJavaBridge.FieldId _CREATOR7426; public static global::android.os.Parcelable_Creator CREATOR { get { return default(global::android.os.Parcelable_Creator); } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.telephony.ServiceState.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/telephony/ServiceState")); global::android.telephony.ServiceState._equals7405 = @__env.GetMethodIDNoThrow(global::android.telephony.ServiceState.staticClass, "equals", "(Ljava/lang/Object;)Z"); global::android.telephony.ServiceState._toString7406 = @__env.GetMethodIDNoThrow(global::android.telephony.ServiceState.staticClass, "toString", "()Ljava/lang/String;"); global::android.telephony.ServiceState._hashCode7407 = @__env.GetMethodIDNoThrow(global::android.telephony.ServiceState.staticClass, "hashCode", "()I"); global::android.telephony.ServiceState._getState7408 = @__env.GetMethodIDNoThrow(global::android.telephony.ServiceState.staticClass, "getState", "()I"); global::android.telephony.ServiceState._setState7409 = @__env.GetMethodIDNoThrow(global::android.telephony.ServiceState.staticClass, "setState", "(I)V"); global::android.telephony.ServiceState._writeToParcel7410 = @__env.GetMethodIDNoThrow(global::android.telephony.ServiceState.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V"); global::android.telephony.ServiceState._describeContents7411 = @__env.GetMethodIDNoThrow(global::android.telephony.ServiceState.staticClass, "describeContents", "()I"); global::android.telephony.ServiceState._copyFrom7412 = @__env.GetMethodIDNoThrow(global::android.telephony.ServiceState.staticClass, "copyFrom", "(Landroid/telephony/ServiceState;)V"); global::android.telephony.ServiceState._getRoaming7413 = @__env.GetMethodIDNoThrow(global::android.telephony.ServiceState.staticClass, "getRoaming", "()Z"); global::android.telephony.ServiceState._getOperatorAlphaLong7414 = @__env.GetMethodIDNoThrow(global::android.telephony.ServiceState.staticClass, "getOperatorAlphaLong", "()Ljava/lang/String;"); global::android.telephony.ServiceState._getOperatorAlphaShort7415 = @__env.GetMethodIDNoThrow(global::android.telephony.ServiceState.staticClass, "getOperatorAlphaShort", "()Ljava/lang/String;"); global::android.telephony.ServiceState._getOperatorNumeric7416 = @__env.GetMethodIDNoThrow(global::android.telephony.ServiceState.staticClass, "getOperatorNumeric", "()Ljava/lang/String;"); global::android.telephony.ServiceState._getIsManualSelection7417 = @__env.GetMethodIDNoThrow(global::android.telephony.ServiceState.staticClass, "getIsManualSelection", "()Z"); global::android.telephony.ServiceState._setStateOutOfService7418 = @__env.GetMethodIDNoThrow(global::android.telephony.ServiceState.staticClass, "setStateOutOfService", "()V"); global::android.telephony.ServiceState._setStateOff7419 = @__env.GetMethodIDNoThrow(global::android.telephony.ServiceState.staticClass, "setStateOff", "()V"); global::android.telephony.ServiceState._setRoaming7420 = @__env.GetMethodIDNoThrow(global::android.telephony.ServiceState.staticClass, "setRoaming", "(Z)V"); global::android.telephony.ServiceState._setOperatorName7421 = @__env.GetMethodIDNoThrow(global::android.telephony.ServiceState.staticClass, "setOperatorName", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); global::android.telephony.ServiceState._setIsManualSelection7422 = @__env.GetMethodIDNoThrow(global::android.telephony.ServiceState.staticClass, "setIsManualSelection", "(Z)V"); global::android.telephony.ServiceState._ServiceState7423 = @__env.GetMethodIDNoThrow(global::android.telephony.ServiceState.staticClass, "<init>", "()V"); global::android.telephony.ServiceState._ServiceState7424 = @__env.GetMethodIDNoThrow(global::android.telephony.ServiceState.staticClass, "<init>", "(Landroid/telephony/ServiceState;)V"); global::android.telephony.ServiceState._ServiceState7425 = @__env.GetMethodIDNoThrow(global::android.telephony.ServiceState.staticClass, "<init>", "(Landroid/os/Parcel;)V"); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Kudu.Services.Web.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int DefaultCollectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, DefaultCollectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, DefaultCollectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { {typeof(Boolean), index => true}, {typeof(Byte), index => (Byte)64}, {typeof(Char), index => (Char)65}, {typeof(DateTime), index => DateTime.Now}, {typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now)}, {typeof(DBNull), index => DBNull.Value}, {typeof(Decimal), index => (Decimal)index}, {typeof(Double), index => (Double)(index + 0.1)}, {typeof(Guid), index => Guid.NewGuid()}, {typeof(Int16), index => (Int16)(index % Int16.MaxValue)}, {typeof(Int32), index => (Int32)(index % Int32.MaxValue)}, {typeof(Int64), index => (Int64)index}, {typeof(Object), index => new object()}, {typeof(SByte), index => (SByte)64}, {typeof(Single), index => (Single)(index + 0.1)}, {typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); }}, {typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); }}, {typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue)}, {typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue)}, {typeof(UInt64), index => (UInt64)index}, {typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); }}, }; } private long _index = 0; public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using GitMind.Common.ProgressHandling; using GitMind.GitModel; using GitMind.MainWindowViews; using GitMind.Utils; using GitMind.Utils.Git; namespace GitMind.Features.StatusHandling.Private { [SingleInstance] internal class StatusService : IStatusService { private static readonly IReadOnlyList<string> None = Enumerable.Empty<string>().ToReadOnlyList(); private readonly IFolderMonitorService folderMonitorService; private readonly IMainWindowService mainWindowService; private readonly IGitStatusService gitStatusService; private readonly IProgressService progress; private readonly Lazy<IRepositoryService> repositoryService; private bool isPaused = false; private Task currentStatusTask = Task.CompletedTask; private int currentStatusCheckCount = 0; private Task currentRepoTask = Task.CompletedTask; private int currentRepoCheckCount = 0; public StatusService( IFolderMonitorService folderMonitorService, IMainWindowService mainWindowService, IGitStatusService gitStatusService, IProgressService progress, Lazy<IRepositoryService> repositoryService) { this.folderMonitorService = folderMonitorService; this.mainWindowService = mainWindowService; this.gitStatusService = gitStatusService; this.progress = progress; this.repositoryService = repositoryService; folderMonitorService.FileChanged += (s, e) => OnFileChanged(e); folderMonitorService.RepoChanged += (s, e) => OnRepoChanged(e); } public event EventHandler<StatusChangedEventArgs> StatusChanged; public event EventHandler<RepoChangedEventArgs> RepoChanged; public bool IsPaused => isPaused; public void Monitor(string workingFolder) { folderMonitorService.Monitor(workingFolder); } public Task<GitStatus> GetStatusAsync() { return GetFreshStatusAsync(); } public Task<IReadOnlyList<string>> GetRepoIdsAsync() { return GetFreshBranchIdsAsync(); } //public IReadOnlyList<string> GetRepoIds() //{ // return GetFreshRepoIds(); //} public IDisposable PauseStatusNotifications(Refresh refresh = Refresh.None) { Log.Debug("Pause status"); isPaused = true; return new Disposable(() => { mainWindowService.SetMainWindowFocus(); ShowStatusProgressAsync(refresh).RunInBackground(); }); } private async Task ShowStatusProgressAsync(Refresh refresh) { try { using (progress.ShowDialog("Updating view ... ")) { bool useFreshRepository = refresh == Refresh.Repo; await repositoryService.Value.RefreshAfterCommandAsync(useFreshRepository); } } catch (Exception e) when (e.IsNotFatal()) { Log.Exception(e, "Failed to check status"); } finally { isPaused = false; } } private void OnFileChanged(FileEventArgs fileEventArgs) { if (!isPaused) { StartCheckStatusAsync(fileEventArgs).RunInBackground(); } else { Log.Debug("paused status"); } } private void OnRepoChanged(FileEventArgs fileEventArgs) { if (!isPaused) { StartCheckRepoAsync(fileEventArgs).RunInBackground(); } else { Log.Debug("paused status"); } } private async Task StartCheckStatusAsync(FileEventArgs fileEventArgs) { Log.Debug($"Checking status change at {fileEventArgs.DateTime} ..."); if (await IsStatusCheckStartedAsync()) { return; } Task<GitStatus> newStatusTask = GetFreshStatusAsync(); currentStatusTask = newStatusTask; GitStatus newStatus = await newStatusTask; TriggerStatusChanged(fileEventArgs, newStatus); } private async Task StartCheckRepoAsync(FileEventArgs fileEventArgs) { Log.Debug($"Checking repo change at {fileEventArgs.DateTime} ..."); if (await IsRepoCheckStartedAsync()) { return; } Task<IReadOnlyList<string>> newRepoTask = GetFreshBranchIdsAsync(); currentRepoTask = newRepoTask; IReadOnlyList<string> newBranchIds = await newRepoTask; TriggerRepoChanged(fileEventArgs, newBranchIds); } private async Task<bool> IsStatusCheckStartedAsync() { int checkStatusCount = ++currentStatusCheckCount; await currentStatusTask; if (checkStatusCount != currentStatusCheckCount) { // Some other trigger will handle the check Log.Debug("Status already being checked"); return true; } return false; } private async Task<bool> IsRepoCheckStartedAsync() { int checkRepoCount = ++currentRepoCheckCount; await currentRepoTask; if (checkRepoCount != currentRepoCheckCount) { // Some other trigger will handle the check Log.Debug("Repo already being checked"); return true; } return false; } private async Task<IReadOnlyList<string>> GetFreshBranchIdsAsync() { Timing t = new Timing(); R<IReadOnlyList<string>> branchIds = await gitStatusService.GetRefsIdsAsync(CancellationToken.None); t.Log($"Got {branchIds.Or(None).Count} branch ids"); if (branchIds.IsFaulted) { Log.Error($"Failed to get branch ids {branchIds.AllMessages}"); return new List<string>(); } return branchIds.Value; } private async Task<GitStatus> GetFreshStatusAsync() { Log.Debug("Getting status ..."); Timing t = new Timing(); R<GitStatus> status = await gitStatusService.GetStatusAsync(CancellationToken.None); t.Log($"Got status {status}"); if (status.IsFaulted) { Log.Error("Failed to read status"); return GitStatus.Default; } return status.Value; } private void TriggerStatusChanged(FileEventArgs fileEventArgs, GitStatus newStatus) { StatusChanged?.Invoke(this, new StatusChangedEventArgs(newStatus, fileEventArgs.DateTime)); } private void TriggerRepoChanged(FileEventArgs fileEventArgs, IReadOnlyList<string> newBranchIds) { RepoChanged?.Invoke(this, new RepoChangedEventArgs(fileEventArgs.DateTime, newBranchIds)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Linq; using Xunit; namespace System.IO.MemoryMappedFiles.Tests { /// <summary> /// Tests for MemoryMappedFile.CreateNew. /// </summary> public class MemoryMappedFileTests_CreateNew : MemoryMappedFilesTestBase { /// <summary> /// Tests invalid arguments to the CreateNew mapName parameter. /// </summary> [Fact] public void InvalidArguments_MapName() { // Empty string is an invalid map name Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateNew(string.Empty, 4096)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateNew(string.Empty, 4096, MemoryMappedFileAccess.ReadWrite)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateNew(string.Empty, 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None)); } /// <summary> /// Tests invalid arguments to the CreateNew capacity parameter. /// </summary> [Theory] [InlineData(0)] // default size is invalid with CreateNew as there's nothing to expand to match [InlineData(-100)] // negative values don't make sense public void InvalidArguments_Capacity(int capacity) { Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateNew(null, capacity)); Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateNew(null, capacity, MemoryMappedFileAccess.ReadWrite)); Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateNew(null, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None)); } /// <summary> /// Tests invalid arguments to the CreateNew access parameter. /// </summary> [Theory] [InlineData((MemoryMappedFileAccess)42)] [InlineData((MemoryMappedFileAccess)(-2))] public void InvalidArguments_Access(MemoryMappedFileAccess access) { // Out of range values Assert.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateNew(null, 4096, access)); Assert.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateNew(null, 4096, access, MemoryMappedFileOptions.None, HandleInheritability.None)); } /// <summary> /// Tests invalid arguments to the CreateNew access parameter, specifically MemoryMappedFileAccess.Write. /// </summary> [Fact] public void InvalidArguments_WriteAccess() { // Write-only access isn't allowed, as it'd be useless Assert.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateNew(null, 4096, MemoryMappedFileAccess.Write)); } /// <summary> /// Tests invalid arguments to the CreateNew options parameter. /// </summary> [Theory] [InlineData((MemoryMappedFileOptions)42)] [InlineData((MemoryMappedFileOptions)(-2))] public void InvalidArguments_Options(MemoryMappedFileOptions options) { Assert.Throws<ArgumentOutOfRangeException>("options", () => MemoryMappedFile.CreateNew(null, 4096, MemoryMappedFileAccess.Read, options, HandleInheritability.None)); } /// <summary> /// Tests invalid arguments to the CreateNew inheritability parameter. /// </summary> [Theory] [InlineData((HandleInheritability)42)] [InlineData((HandleInheritability)(-2))] public void InvalidArguments_Inheritability(HandleInheritability inheritability) { Assert.Throws<ArgumentOutOfRangeException>("inheritability", () => MemoryMappedFile.CreateNew(null, 4096, MemoryMappedFileAccess.Read, MemoryMappedFileOptions.None, inheritability)); } /// <summary> /// Test the exceptional behavior when attempting to create a map so large it's not supported. /// </summary> [PlatformSpecific(PlatformID.Windows)] [Fact] public void TooLargeCapacity_Windows() { if (IntPtr.Size == 4) { Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateNew(null, 1 + (long)uint.MaxValue)); } else { Assert.Throws<IOException>(() => MemoryMappedFile.CreateNew(null, long.MaxValue)); } } /// <summary> /// Test the exceptional behavior when attempting to create a map so large it's not supported. /// </summary> [PlatformSpecific(PlatformID.AnyUnix & ~PlatformID.OSX)] // Because of the file-based backing, OS X pops up a warning dialog about being out-of-space (even though we clean up immediately) [Fact] public void TooLargeCapacity_Unix() { // On Windows we fail with too large a capacity as part of the CreateNew call. // On Unix that exception may happen a bit later, as part of creating the view, // due to differences in OS behaviors and Unix not actually having a notion of // a view separate from a map. It could also come from CreateNew, depending // on what backing store is being used. Assert.Throws<IOException>(() => { using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, long.MaxValue)) { mmf.CreateViewAccessor().Dispose(); } }); } /// <summary> /// Test to verify that map names are left unsupported on Unix. /// </summary> [PlatformSpecific(PlatformID.AnyUnix)] [Theory] [MemberData(nameof(CreateValidMapNames))] public void MapNamesNotSupported_Unix(string mapName) { Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateNew(mapName, 4096)); Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateNew(mapName, 4096, MemoryMappedFileAccess.Read)); Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateNew(mapName, 4096, MemoryMappedFileAccess.Read, MemoryMappedFileOptions.None, HandleInheritability.None)); } /// <summary> /// Test to verify a variety of map names work correctly on Windows. /// </summary> [PlatformSpecific(PlatformID.Windows)] [Theory] [MemberData(nameof(CreateValidMapNames))] [InlineData(null)] public void ValidMapNames_Windows(string name) { using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(name, 4096)) { ValidateMemoryMappedFile(mmf, 4096); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(name, 4096, MemoryMappedFileAccess.Read)) { ValidateMemoryMappedFile(mmf, 4096, MemoryMappedFileAccess.Read); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(name, 4096, MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileOptions.DelayAllocatePages, HandleInheritability.Inheritable)) { ValidateMemoryMappedFile(mmf, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.Inheritable); } } /// <summary> /// Test to verify map names are handled appropriately, causing a conflict when they're active but /// reusable in a sequential manner. /// </summary> [PlatformSpecific(PlatformID.Windows)] [Theory] [MemberData(nameof(CreateValidMapNames))] public void ReusingNames_Windows(string name) { using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(name, 4096)) { ValidateMemoryMappedFile(mmf, 4096); Assert.Throws<IOException>(() => MemoryMappedFile.CreateNew(name, 4096)); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(name, 4096)) { ValidateMemoryMappedFile(mmf, 4096, MemoryMappedFileAccess.ReadWrite); } } /// <summary> /// Test various combinations of arguments to CreateNew, validating the created maps each time they're created. /// </summary> [Theory] [MemberData(nameof(MemberData_ValidArgumentCombinations), new string[] { null, "CreateUniqueMapName()" }, new long[] { 1, 256, -1 /*pagesize*/, 10000 }, new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.CopyOnWrite }, new MemoryMappedFileOptions[] { MemoryMappedFileOptions.None, MemoryMappedFileOptions.DelayAllocatePages }, new HandleInheritability[] { HandleInheritability.None, HandleInheritability.Inheritable })] public void ValidArgumentCombinations( string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity)) { ValidateMemoryMappedFile(mmf, capacity); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access)) { ValidateMemoryMappedFile(mmf, capacity, access); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access, options, inheritability)) { ValidateMemoryMappedFile(mmf, capacity, access, inheritability); } } /// <summary> /// Provides input data to the ValidArgumentCombinations tests, yielding the full matrix /// of combinations of input values provided, except for those that are known to be unsupported /// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders /// listed in the MemberData attribute (e.g. actual system page size instead of -1). /// </summary> /// <param name="mapNames"> /// The names to yield. /// non-null may be excluded based on platform. /// "CreateUniqueMapName()" will be translated to an invocation of that method. /// </param> /// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param> /// <param name="accesses">The accesses to yield</param> /// <param name="options">The options to yield.</param> /// <param name="inheritabilities">The inheritabilities to yield.</param> public static IEnumerable<object[]> MemberData_ValidArgumentCombinations( string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses, MemoryMappedFileOptions[] options, HandleInheritability[] inheritabilities) { foreach (string tmpMapName in mapNames) { if (tmpMapName != null && !MapNamesSupported) { continue; } foreach (long tmpCapacity in capacities) { long capacity = tmpCapacity == -1 ? s_pageSize.Value : tmpCapacity; foreach (MemoryMappedFileAccess access in accesses) { foreach (MemoryMappedFileOptions option in options) { foreach (HandleInheritability inheritability in inheritabilities) { string mapName = tmpMapName == "CreateUniqueMapName()" ? CreateUniqueMapName() : tmpMapName; yield return new object[] { mapName, capacity, access, option, inheritability }; } } } } } } /// <summary> /// Test to verify that two unrelated maps don't share data. /// </summary> [PlatformSpecific(PlatformID.Windows)] [Theory] [MemberData(nameof(CreateValidMapNames))] [InlineData(null)] public void DataNotPersistedBetweenMaps_Windows(string name) { // Write some data to a map newly created with the specified name using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(name, 4096)) using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor()) { accessor.Write(0, 42); } // After it's closed, open a map with the same name again and verify the data's gone using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(name, 4096)) using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor()) { // Data written to previous map should not be here Assert.Equal(0, accessor.ReadByte(0)); } } /// <summary> /// Test to verify that two unrelated maps don't share data. /// </summary> [Fact] public void DataNotPersistedBetweenMaps_Unix() { // same as the Windows test, but for Unix we only validate null, as other names aren't allowed DataNotPersistedBetweenMaps_Windows(null); } /// <summary> /// Test to verify that we can have many maps open at the same time. /// </summary> [Fact] public void ManyConcurrentMaps() { const int NumMaps = 100, Capacity = 4096; var mmfs = new List<MemoryMappedFile>(Enumerable.Range(0, NumMaps).Select(_ => MemoryMappedFile.CreateNew(null, Capacity))); try { mmfs.ForEach(mmf => ValidateMemoryMappedFile(mmf, Capacity)); } finally { mmfs.ForEach(mmf => mmf.Dispose()); } } /// <summary> /// Test to verify expected capacity with regards to page size and automatically rounding up to the nearest. /// </summary> [PlatformSpecific(PlatformID.Windows)] [Fact] public void RoundedUpCapacity_Windows() { // On both Windows and Unix, capacity is rounded up to the nearest page size. However, // the amount of capacity actually usable by the developer is supposed to be limited // to that specified. That's not currently the case with the MMF APIs on Windows; // it is the case on Unix. const int CapacityLessThanPageSize = 1; using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, CapacityLessThanPageSize)) using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor()) { Assert.Equal(s_pageSize.Value, acc.Capacity); } } /// <summary> /// Test to verify expected capacity with regards to page size and automatically rounding up to the nearest. /// </summary> [PlatformSpecific(PlatformID.AnyUnix)] [Fact] public void RoundedUpCapacity_Unix() { // The capacity of the view should match the capacity specified when creating the map, // even though under the covers the map's capacity is rounded up to the nearest page size. const int CapacityLessThanPageSize = 1; using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, CapacityLessThanPageSize)) using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor()) { Assert.Equal(CapacityLessThanPageSize, acc.Capacity); } } /// <summary> /// Test to verify we can dispose of a map multiple times. /// </summary> [Fact] public void DoubleDispose() { MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, 4096); mmf.Dispose(); mmf.Dispose(); } /// <summary> /// Test to verify we can't create new views after the map has been disposed. /// </summary> [Fact] public void UnusableAfterDispose() { MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, 4096); SafeMemoryMappedFileHandle handle = mmf.SafeMemoryMappedFileHandle; Assert.False(handle.IsClosed); mmf.Dispose(); Assert.True(handle.IsClosed); Assert.Throws<ObjectDisposedException>(() => mmf.CreateViewAccessor()); Assert.Throws<ObjectDisposedException>(() => mmf.CreateViewStream()); } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoadSoftDelete.Business.ERLevel { /// <summary> /// G03_Continent_ReChild (editable child object).<br/> /// This is a generated base class of <see cref="G03_Continent_ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="G02_Continent"/> collection. /// </remarks> [Serializable] public partial class G03_Continent_ReChild : BusinessBase<G03_Continent_ReChild> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Continent_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Continent_Child_NameProperty = RegisterProperty<string>(p => p.Continent_Child_Name, "SubContinents Child Name"); /// <summary> /// Gets or sets the SubContinents Child Name. /// </summary> /// <value>The SubContinents Child Name.</value> public string Continent_Child_Name { get { return GetProperty(Continent_Child_NameProperty); } set { SetProperty(Continent_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="G03_Continent_ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="G03_Continent_ReChild"/> object.</returns> internal static G03_Continent_ReChild NewG03_Continent_ReChild() { return DataPortal.CreateChild<G03_Continent_ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="G03_Continent_ReChild"/> object, based on given parameters. /// </summary> /// <param name="continent_ID2">The Continent_ID2 parameter of the G03_Continent_ReChild to fetch.</param> /// <returns>A reference to the fetched <see cref="G03_Continent_ReChild"/> object.</returns> internal static G03_Continent_ReChild GetG03_Continent_ReChild(int continent_ID2) { return DataPortal.FetchChild<G03_Continent_ReChild>(continent_ID2); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="G03_Continent_ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public G03_Continent_ReChild() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="G03_Continent_ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="G03_Continent_ReChild"/> object from the database, based on given criteria. /// </summary> /// <param name="continent_ID2">The Continent ID2.</param> protected void Child_Fetch(int continent_ID2) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetG03_Continent_ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Continent_ID2", continent_ID2).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, continent_ID2); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } // check all object rules and property rules BusinessRules.CheckRules(); } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="G03_Continent_ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Continent_Child_NameProperty, dr.GetString("Continent_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="G03_Continent_ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(G02_Continent parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddG03_Continent_ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Continent_ID2", parent.Continent_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Continent_Child_Name", ReadProperty(Continent_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="G03_Continent_ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(G02_Continent parent) { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateG03_Continent_ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Continent_ID2", parent.Continent_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Continent_Child_Name", ReadProperty(Continent_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="G03_Continent_ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(G02_Continent parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteG03_Continent_ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Continent_ID2", parent.Continent_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; namespace ProCharts { public class PointCollection : SortableCollectionBase, ICustomTypeDescriptor { #region CollectionBase implementation public PointCollection() { //In your collection class constructor add this line. //set the SortObjectType for sorting. base.SortObjectType = typeof(PointHelper); } public PointHelper this[int index] { get { return ((PointHelper)List[index]); } set { List[index] = value; } } public int Add(PointHelper value) { return (List.Add(value)); } public int IndexOf(PointHelper value) { return (List.IndexOf(value)); } public void Insert(int index, PointHelper value) { List.Insert(index, value); } public void Remove(PointHelper value) { List.Remove(value); } public bool Contains(PointHelper value) { // If value is not of type Int16, this will return false. return (List.Contains(value)); } protected override void OnInsert(int index, Object value) { // Insert additional code to be run only when inserting values. } protected override void OnRemove(int index, Object value) { // Insert additional code to be run only when removing values. } protected override void OnSet(int index, Object oldValue, Object newValue) { // Insert additional code to be run only when setting values. } protected override void OnValidate(Object value) { } #endregion [TypeConverter(typeof(PointCollectionConverter))] public PointCollection Symbols { get { return this; } } internal class SymbolConverter : ExpandableObjectConverter { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { if (destType == typeof(string) && value is PointHelper) { // Cast the value to an Employee type PointHelper pp = (PointHelper)value; return pp.Channelname + ", " + pp.Pointvalue ; } return base.ConvertTo(context, culture, value, destType); } } // This is a special type converter which will be associated with the EmployeeCollection class. // It converts an EmployeeCollection object to a string representation for use in a property grid. internal class PointCollectionConverter : ExpandableObjectConverter { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { if (destType == typeof(string) && value is PointCollection) { // Return department and department role separated by comma. return "PointHelper"; } return base.ConvertTo(context, culture, value, destType); } } #region ICustomTypeDescriptor impl public String GetClassName() { return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } public String GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } public TypeConverter GetConverter() { return TypeDescriptor.GetConverter(this, true); } public EventDescriptor GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } public PropertyDescriptor GetDefaultProperty() { return TypeDescriptor.GetDefaultProperty(this, true); } public object GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } public EventDescriptorCollection GetEvents() { return TypeDescriptor.GetEvents(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) { return this; } /// <summary> /// Called to get the properties of this type. Returns properties with certain /// attributes. this restriction is not implemented here. /// </summary> /// <param name="attributes"></param> /// <returns></returns> public PropertyDescriptorCollection GetProperties(Attribute[] attributes) { return GetProperties(); } /// <summary> /// Called to get the properties of this type. /// </summary> /// <returns></returns> public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list of employees for (int i = 0; i < this.List.Count; i++) { // Create a property descriptor for the employee item and add to the property descriptor collection PointCollectionPropertyDescriptor pd = new PointCollectionPropertyDescriptor(this, i); pds.Add(pd); } // return the property descriptor collection return pds; } #endregion public class PointCollectionPropertyDescriptor : PropertyDescriptor { private PointCollection collection = null; private int index = -1; public PointCollectionPropertyDescriptor(PointCollection coll, int idx) : base("#" + idx.ToString(), null) { this.collection = coll; this.index = idx; } public override AttributeCollection Attributes { get { return new AttributeCollection(null); } } public override bool CanResetValue(object component) { return true; } public override Type ComponentType { get { return this.collection.GetType(); } } public override string DisplayName { get { PointHelper emp = this.collection[index]; return (string)(emp.Pointvalue.ToString()); } } public override string Description { get { PointHelper emp = this.collection[index]; StringBuilder sb = new StringBuilder(); sb.Append(emp.Pointvalue.ToString()); sb.Append(", "); sb.Append(emp.Channelname); return sb.ToString(); } } public override object GetValue(object component) { return this.collection[index]; } public override bool IsReadOnly { get { return false; } } public override string Name { get { return "#" + index.ToString(); } } public override Type PropertyType { get { return this.collection[index].GetType(); } } public override void ResetValue(object component) { } public override bool ShouldSerializeValue(object component) { return true; } public override void SetValue(object component, object value) { // this.collection[index] = value; } } } }
// *********************************************************************** // Copyright (c) 2010-2014 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using NUnit.Compatibility; using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal { /// <summary> /// The TestResult class represents the result of a test. /// </summary> public abstract class TestResult : LongLivedMarshalByRefObject, ITestResult { #region Fields /// <summary> /// Error message for when child tests have errors /// </summary> internal static readonly string CHILD_ERRORS_MESSAGE = "One or more child tests had errors"; /// <summary> /// Error message for when child tests have warnings /// </summary> internal static readonly string CHILD_WARNINGS_MESSAGE = "One or more child tests had warnings"; /// <summary> /// Error message for when child tests are ignored /// </summary> internal static readonly string CHILD_IGNORE_MESSAGE = "One or more child tests were ignored"; /// <summary> /// The minimum duration for tests /// </summary> internal const double MIN_DURATION = 0.000001d; // static Logger log = InternalTrace.GetLogger("TestResult"); private readonly StringBuilder _output = new StringBuilder(); private double _duration; /// <summary> /// Aggregate assertion count /// </summary> protected int InternalAssertCount; private ResultState _resultState; private string _message; private string _stackTrace; private readonly List<AssertionResult> _assertionResults = new List<AssertionResult>(); private readonly List<TestAttachment> _testAttachments = new List<TestAttachment>(); #if PARALLEL /// <summary> /// ReaderWriterLock /// </summary> protected ReaderWriterLockSlim RwLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); #endif #endregion #region Constructor /// <summary> /// Construct a test result given a Test /// </summary> /// <param name="test">The test to be used</param> public TestResult(ITest test) { Test = test; ResultState = ResultState.Inconclusive; #if !PARALLEL OutWriter = new StringWriter(_output); #else OutWriter = TextWriter.Synchronized(new StringWriter(_output)); #endif } #endregion #region ITestResult Members /// <summary> /// Gets the test with which this result is associated. /// </summary> public ITest Test { get; } /// <summary> /// Gets the ResultState of the test result, which /// indicates the success or failure of the test. /// </summary> public ResultState ResultState { get { #if PARALLEL RwLock.EnterReadLock(); #endif try { return _resultState; } finally { #if PARALLEL RwLock.ExitReadLock(); #endif } } private set { _resultState = value; } } /// <summary> /// Gets the name of the test result /// </summary> public virtual string Name { get { return Test.Name; } } /// <summary> /// Gets the full name of the test result /// </summary> public virtual string FullName { get { return Test.FullName; } } /// <summary> /// Gets or sets the elapsed time for running the test in seconds /// </summary> public double Duration { get { return _duration; } set { _duration = value >= MIN_DURATION ? value : MIN_DURATION; } } /// <summary> /// Gets or sets the time the test started running. /// </summary> public DateTime StartTime { get; set; } /// <summary> /// Gets or sets the time the test finished running. /// </summary> public DateTime EndTime { get; set; } /// <summary> /// Adds a test attachment to the test result /// </summary> /// <param name="attachment">The TestAttachment object to attach</param> internal void AddTestAttachment(TestAttachment attachment) { _testAttachments.Add(attachment); } /// <summary> /// Gets the collection of files attached to the test /// </summary> public ICollection<TestAttachment> TestAttachments => new ReadOnlyCollection<TestAttachment>(_testAttachments); /// <summary> /// Gets the message associated with a test /// failure or with not running the test /// </summary> public string Message { get { #if PARALLEL RwLock.EnterReadLock(); #endif try { return _message; } finally { #if PARALLEL RwLock.ExitReadLock(); #endif } } private set { _message = value; } } /// <summary> /// Gets any stack trace associated with an /// error or failure. /// </summary> public virtual string StackTrace { get { #if PARALLEL RwLock.EnterReadLock(); #endif try { return _stackTrace; } finally { #if PARALLEL RwLock.ExitReadLock(); #endif } } private set { _stackTrace = value; } } /// <summary> /// Gets or sets the count of asserts executed /// when running the test. /// </summary> public int AssertCount { get { #if PARALLEL RwLock.EnterReadLock(); #endif try { return InternalAssertCount; } finally { #if PARALLEL RwLock.ExitReadLock (); #endif } } internal set { InternalAssertCount = value; } } /// <summary> /// Gets the number of test cases that failed /// when running the test and all its children. /// </summary> public abstract int FailCount { get; } /// <summary> /// Gets the number of test cases that had warnings /// when running the test and all its children. /// </summary> public abstract int WarningCount { get; } /// <summary> /// Gets the number of test cases that passed /// when running the test and all its children. /// </summary> public abstract int PassCount { get; } /// <summary> /// Gets the number of test cases that were skipped /// when running the test and all its children. /// </summary> public abstract int SkipCount { get; } /// <summary> /// Gets the number of test cases that were inconclusive /// when running the test and all its children. /// </summary> public abstract int InconclusiveCount { get; } /// <summary> /// Indicates whether this result has any child results. /// </summary> public abstract bool HasChildren { get; } /// <summary> /// Gets the collection of child results. /// </summary> public abstract IEnumerable<ITestResult> Children { get; } /// <summary> /// Gets a TextWriter, which will write output to be included in the result. /// </summary> public TextWriter OutWriter { get; } /// <summary> /// Gets any text output written to this result. /// </summary> public string Output { get { #if PARALLEL lock (OutWriter) { return _output.ToString(); } #else return _output.ToString(); #endif } } /// <summary> /// Gets a list of assertion results associated with the test. /// </summary> public IList<AssertionResult> AssertionResults { get { return _assertionResults; } } #endregion #region IXmlNodeBuilder Members /// <summary> /// Returns the XML representation of the result. /// </summary> /// <param name="recursive">If true, descendant results are included</param> /// <returns>An XmlNode representing the result</returns> public TNode ToXml(bool recursive) { return AddToXml(new TNode("dummy"), recursive); } /// <summary> /// Adds the XML representation of the result as a child of the /// supplied parent node.. /// </summary> /// <param name="parentNode">The parent node.</param> /// <param name="recursive">If true, descendant results are included</param> /// <returns></returns> public virtual TNode AddToXml(TNode parentNode, bool recursive) { // A result node looks like a test node with extra info added TNode thisNode = Test.AddToXml(parentNode, false); thisNode.AddAttribute("result", ResultState.Status.ToString()); if (ResultState.Label != string.Empty) // && ResultState.Label != ResultState.Status.ToString()) thisNode.AddAttribute("label", ResultState.Label); if (ResultState.Site != FailureSite.Test) thisNode.AddAttribute("site", ResultState.Site.ToString()); thisNode.AddAttribute("start-time", StartTime.ToString("u")); thisNode.AddAttribute("end-time", EndTime.ToString("u")); thisNode.AddAttribute("duration", Duration.ToString("0.000000", NumberFormatInfo.InvariantInfo)); if (Test is TestSuite) { thisNode.AddAttribute("total", (PassCount + FailCount + SkipCount + InconclusiveCount).ToString()); thisNode.AddAttribute("passed", PassCount.ToString()); thisNode.AddAttribute("failed", FailCount.ToString()); thisNode.AddAttribute("warnings", WarningCount.ToString()); thisNode.AddAttribute("inconclusive", InconclusiveCount.ToString()); thisNode.AddAttribute("skipped", SkipCount.ToString()); } thisNode.AddAttribute("asserts", AssertCount.ToString()); switch (ResultState.Status) { case TestStatus.Failed: AddFailureElement(thisNode); break; case TestStatus.Skipped: case TestStatus.Passed: case TestStatus.Inconclusive: case TestStatus.Warning: if (Message != null && Message.Trim().Length > 0) AddReasonElement(thisNode); break; } if (Output.Length > 0) AddOutputElement(thisNode); if (AssertionResults.Count > 0) AddAssertionsElement(thisNode); if (_testAttachments.Count > 0) AddAttachmentsElement(thisNode); if (recursive && HasChildren) foreach (TestResult child in Children) child.AddToXml(thisNode, recursive); return thisNode; } #endregion #region Other Public Properties /// <summary> /// Gets a count of pending failures (from Multiple Assert) /// </summary> public int PendingFailures { get { return AssertionResults.Count(ar => ar.Status == AssertionStatus.Failed); } } /// <summary> /// Gets the worst assertion status (highest enum) in all the assertion results /// </summary> public AssertionStatus WorstAssertionStatus { get { return AssertionResults.Aggregate((ar1, ar2) => ar1.Status > ar2.Status ? ar1 : ar2).Status; } } #endregion #region Other Public Methods /// <summary> /// Set the result of the test /// </summary> /// <param name="resultState">The ResultState to use in the result</param> public void SetResult(ResultState resultState) { SetResult(resultState, null, null); } /// <summary> /// Set the result of the test /// </summary> /// <param name="resultState">The ResultState to use in the result</param> /// <param name="message">A message associated with the result state</param> public void SetResult(ResultState resultState, string message) { SetResult(resultState, message, null); } /// <summary> /// Set the result of the test /// </summary> /// <param name="resultState">The ResultState to use in the result</param> /// <param name="message">A message associated with the result state</param> /// <param name="stackTrace">Stack trace giving the location of the command</param> public void SetResult(ResultState resultState, string message, string stackTrace) { #if PARALLEL RwLock.EnterWriteLock(); #endif try { ResultState = resultState; Message = message; StackTrace = stackTrace; } finally { #if PARALLEL RwLock.ExitWriteLock(); #endif } } /// <summary> /// Set the test result based on the type of exception thrown /// </summary> /// <param name="ex">The exception that was thrown</param> public void RecordException(Exception ex) { var result = new ExceptionResult(ex, FailureSite.Test); SetResult(result.ResultState, result.Message, result.StackTrace); if (AssertionResults.Count > 0 && result.ResultState == ResultState.Error) { // Add pending failures to the legacy result message Message += CreateLegacyFailureMessage(); // Add to the list of assertion errors, so that newer runners will see it AssertionResults.Add(new AssertionResult(AssertionStatus.Error, result.Message, result.StackTrace)); } } /// <summary> /// Set the test result based on the type of exception thrown /// </summary> /// <param name="ex">The exception that was thrown</param> /// <param name="site">The FailureSite to use in the result</param> public void RecordException(Exception ex, FailureSite site) { var result = new ExceptionResult(ex, site); SetResult(result.ResultState, result.Message, result.StackTrace); } /// <summary> /// RecordTearDownException appends the message and stack trace /// from an exception arising during teardown of the test /// to any previously recorded information, so that any /// earlier failure information is not lost. Note that /// calling Assert.Ignore, Assert.Inconclusive, etc. during /// teardown is treated as an error. If the current result /// represents a suite, it may show a teardown error even /// though all contained tests passed. /// </summary> /// <param name="ex">The Exception to be recorded</param> public void RecordTearDownException(Exception ex) { ex = ValidateAndUnwrap(ex); ResultState resultState = ResultState == ResultState.Cancelled ? ResultState.Cancelled : ResultState.Error; if (Test.IsSuite) resultState = resultState.WithSite(FailureSite.TearDown); string message = "TearDown : " + ExceptionHelper.BuildMessage(ex); if (Message != null) message = Message + Environment.NewLine + message; string stackTrace = "--TearDown" + Environment.NewLine + ExceptionHelper.BuildStackTrace(ex); if (StackTrace != null) stackTrace = StackTrace + Environment.NewLine + stackTrace; SetResult(resultState, message, stackTrace); } private static Exception ValidateAndUnwrap(Exception ex) { Guard.ArgumentNotNull(ex, nameof(ex)); if ((ex is NUnitException || ex is TargetInvocationException) && ex.InnerException != null) return ex.InnerException; return ex; } private struct ExceptionResult { public ResultState ResultState { get; } public string Message { get; } public string StackTrace { get; } public ExceptionResult(Exception ex, FailureSite site) { ex = ValidateAndUnwrap(ex); if (ex is ResultStateException) { ResultState = ((ResultStateException)ex).ResultState.WithSite(site); Message = ex.Message; StackTrace = StackFilter.DefaultFilter.Filter(ex.StackTrace); } #if THREAD_ABORT else if (ex is ThreadAbortException) { ResultState = ResultState.Cancelled.WithSite(site); Message = "Test cancelled by user"; StackTrace = ex.StackTrace; } #endif else { ResultState = ResultState.Error.WithSite(site); Message = ExceptionHelper.BuildMessage(ex); StackTrace = ExceptionHelper.BuildStackTrace(ex); } } } /// <summary> /// Update overall test result, including legacy Message, based /// on AssertionResults that have been saved to this point. /// </summary> public void RecordTestCompletion() { switch (AssertionResults.Count) { case 0: SetResult(ResultState.Success); break; case 1: SetResult( AssertionStatusToResultState(AssertionResults[0].Status), AssertionResults[0].Message, AssertionResults[0].StackTrace); break; default: SetResult( AssertionStatusToResultState(WorstAssertionStatus), CreateLegacyFailureMessage()); break; } } /// <summary> /// Record an assertion result /// </summary> public void RecordAssertion(AssertionResult assertion) { _assertionResults.Add(assertion); } /// <summary> /// Record an assertion result /// </summary> public void RecordAssertion(AssertionStatus status, string message, string stackTrace) { RecordAssertion(new AssertionResult(status, message, stackTrace)); } /// <summary> /// Record an assertion result /// </summary> public void RecordAssertion(AssertionStatus status, string message) { RecordAssertion(status, message, null); } /// <summary> /// Creates a failure message incorporating failures /// from a Multiple Assert block for use by runners /// that don't know about AssertionResults. /// </summary> /// <returns>Message as a string</returns> private string CreateLegacyFailureMessage() { var writer = new StringWriter(); if (AssertionResults.Count > 1) writer.WriteLine("Multiple failures or warnings in test:"); int counter = 0; foreach (var assertion in AssertionResults) writer.WriteLine(string.Format(" {0}) {1}", ++counter, assertion.Message)); return writer.ToString(); } #endregion #region Helper Methods /// <summary> /// Adds a reason element to a node and returns it. /// </summary> /// <param name="targetNode">The target node.</param> /// <returns>The new reason element.</returns> private TNode AddReasonElement(TNode targetNode) { TNode reasonNode = targetNode.AddElement("reason"); return reasonNode.AddElementWithCDATA("message", Message); } /// <summary> /// Adds a failure element to a node and returns it. /// </summary> /// <param name="targetNode">The target node.</param> /// <returns>The new failure element.</returns> private TNode AddFailureElement(TNode targetNode) { TNode failureNode = targetNode.AddElement("failure"); if (Message != null && Message.Trim().Length > 0) failureNode.AddElementWithCDATA("message", Message); if (StackTrace != null && StackTrace.Trim().Length > 0) failureNode.AddElementWithCDATA("stack-trace", StackTrace); return failureNode; } private TNode AddOutputElement(TNode targetNode) { return targetNode.AddElementWithCDATA("output", Output); } private TNode AddAssertionsElement(TNode targetNode) { var assertionsNode = targetNode.AddElement("assertions"); foreach (var assertion in AssertionResults) { TNode assertionNode = assertionsNode.AddElement("assertion"); assertionNode.AddAttribute("result", assertion.Status.ToString()); if (assertion.Message != null) assertionNode.AddElementWithCDATA("message", assertion.Message); if (assertion.StackTrace != null) assertionNode.AddElementWithCDATA("stack-trace", assertion.StackTrace); } return assertionsNode; } private ResultState AssertionStatusToResultState(AssertionStatus status) { switch (status) { case AssertionStatus.Inconclusive: return ResultState.Inconclusive; default: case AssertionStatus.Passed: return ResultState.Success; case AssertionStatus.Warning: return ResultState.Warning; case AssertionStatus.Failed: return ResultState.Failure; case AssertionStatus.Error: return ResultState.Error; } } /// <summary> /// Adds an attachments element to a node and returns it. /// </summary> /// <param name="targetNode">The target node.</param> /// <returns>The new attachments element.</returns> private TNode AddAttachmentsElement(TNode targetNode) { TNode attachmentsNode = targetNode.AddElement("attachments"); foreach (var attachment in _testAttachments) { var attachmentNode = attachmentsNode.AddElement("attachment"); attachmentNode.AddElement("filePath", attachment.FilePath); if (attachment.Description != null) attachmentNode.AddElementWithCDATA("description", attachment.Description); } return attachmentsNode; } #endregion } }
using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.Runtime; using Orleans.Runtime.Scheduler; using TestExtensions; using UnitTests.TesterInternal; using Xunit; using Xunit.Abstractions; using Orleans.TestingHost.Utils; using Orleans.Internal; using Orleans; using System.Collections.Generic; // ReSharper disable ConvertToConstant.Local namespace UnitTests.SchedulerTests { internal class UnitTestSchedulingContext : IGrainContext { public GrainReference GrainReference => throw new NotImplementedException(); public GrainId GrainId => throw new NotImplementedException(); public IAddressable GrainInstance => throw new NotImplementedException(); public ActivationId ActivationId => throw new NotImplementedException(); public ActivationAddress Address => throw new NotImplementedException(); public IServiceProvider ActivationServices => throw new NotImplementedException(); public IDictionary<object, object> Items => throw new NotImplementedException(); public IGrainLifecycle ObservableLifecycle => throw new NotImplementedException(); IAddressable IGrainContext.GrainInstance => throw new NotImplementedException(); public TComponent GetComponent<TComponent>() => throw new NotImplementedException(); public void SetComponent<TComponent>(TComponent value) => throw new NotImplementedException(); bool IEquatable<IGrainContext>.Equals(IGrainContext other) => ReferenceEquals(this, other); } [TestCategory("BVT"), TestCategory("Scheduler")] public class OrleansTaskSchedulerBasicTests : IDisposable { private readonly ITestOutputHelper output; private static readonly object Lockable = new object(); private readonly UnitTestSchedulingContext rootContext; private readonly OrleansTaskScheduler scheduler; private readonly ILoggerFactory loggerFactory; public OrleansTaskSchedulerBasicTests(ITestOutputHelper output) { this.output = output; SynchronizationContext.SetSynchronizationContext(null); this.loggerFactory = InitSchedulerLogging(); this.rootContext = new UnitTestSchedulingContext(); this.scheduler = TestInternalHelper.InitializeSchedulerForTesting(this.rootContext, this.loggerFactory); } public void Dispose() { SynchronizationContext.SetSynchronizationContext(null); this.scheduler.Stop(); } [Fact, TestCategory("AsynchronyPrimitives")] public void Async_Task_Start_ActivationTaskScheduler() { ActivationTaskScheduler activationScheduler = this.scheduler.GetWorkItemGroup(this.rootContext).TaskScheduler; int expected = 2; bool done = false; Task<int> t = new Task<int>(() => { done = true; return expected; }); t.Start(activationScheduler); int received = t.Result; Assert.True(t.IsCompleted, "Task should have completed"); Assert.False(t.IsFaulted, "Task should not thrown exception: " + t.Exception); Assert.True(done, "Task should be done"); Assert.Equal(expected, received); } [Fact] public void Sched_SimpleFifoTest() { // This is not a great test because there's a 50/50 shot that it will work even if the scheduling // is completely and thoroughly broken and both closures are executed "simultaneously" ActivationTaskScheduler activationScheduler = this.scheduler.GetWorkItemGroup(this.rootContext).TaskScheduler; int n = 0; // ReSharper disable AccessToModifiedClosure Action item1 = () => { n = n + 5; }; Action item2 = () => { n = n * 3; }; // ReSharper restore AccessToModifiedClosure this.scheduler.QueueAction(item1, this.rootContext); this.scheduler.QueueAction(item2, this.rootContext); // Pause to let things run Thread.Sleep(1000); // N should be 15, because the two tasks should execute in order Assert.True(n != 0, "Work items did not get executed"); Assert.Equal(15, n); this.output.WriteLine("Test executed OK."); } [Fact] public async Task Sched_Task_TplFifoTest() { // This is not a great test because there's a 50/50 shot that it will work even if the scheduling // is completely and thoroughly broken and both closures are executed "simultaneously" ActivationTaskScheduler activationScheduler = this.scheduler.GetWorkItemGroup(this.rootContext).TaskScheduler; int n = 0; // ReSharper disable AccessToModifiedClosure Task task1 = new Task(() => { Thread.Sleep(1000); n = n + 5; }); Task task2 = new Task(() => { n = n * 3; }); // ReSharper restore AccessToModifiedClosure task1.Start(activationScheduler); task2.Start(activationScheduler); await Task.WhenAll(task1, task2).WithTimeout(TimeSpan.FromSeconds(5)); // N should be 15, because the two tasks should execute in order Assert.True(n != 0, "Work items did not get executed"); Assert.Equal(15, n); } [Fact] public void Sched_Task_ClosureWorkItem_Wait() { const int NumTasks = 10; ManualResetEvent[] flags = new ManualResetEvent[NumTasks]; for (int i = 0; i < NumTasks; i++) { flags[i] = new ManualResetEvent(false); } Task[] tasks = new Task[NumTasks]; for (int i = 0; i < NumTasks; i++) { int taskNum = i; // Capture tasks[i] = new Task(() => { this.output.WriteLine("Inside Task-" + taskNum); flags[taskNum].WaitOne(); }); } Action[] workItems = new Action[NumTasks]; for (int i = 0; i < NumTasks; i++) { int taskNum = i; // Capture workItems[i] = () => { this.output.WriteLine("Inside ClosureWorkItem-" + taskNum); tasks[taskNum].Start(TaskScheduler.Default); bool ok = tasks[taskNum].Wait(TimeSpan.FromMilliseconds(NumTasks * 100)); Assert.True(ok, "Wait completed successfully inside ClosureWorkItem-" + taskNum); }; } foreach (var workItem in workItems) this.scheduler.QueueAction(workItem, this.rootContext); foreach (var flag in flags) flag.Set(); for (int i = 0; i < tasks.Length; i++) { bool ok = tasks[i].Wait(TimeSpan.FromMilliseconds(NumTasks * 150)); Assert.True(ok, "Wait completed successfully for Task-" + i); } for (int i = 0; i < tasks.Length; i++) { Assert.False(tasks[i].IsFaulted, "Task.IsFaulted-" + i + " Exception=" + tasks[i].Exception); Assert.True(tasks[i].IsCompleted, "Task.IsCompleted-" + i); } } [Fact] public async Task Sched_Task_TaskWorkItem_CurrentScheduler() { ActivationTaskScheduler activationScheduler = this.scheduler.GetWorkItemGroup(this.rootContext).TaskScheduler; var result0 = new TaskCompletionSource<bool>(); var result1 = new TaskCompletionSource<bool>(); Task t1 = null; this.scheduler.QueueAction(() => { try { this.output.WriteLine("#0 - TaskWorkItem - SynchronizationContext.Current={0} TaskScheduler.Current={1}", SynchronizationContext.Current, TaskScheduler.Current); Assert.Equal(activationScheduler, TaskScheduler.Current); // t1 = new Task(() => { this.output.WriteLine("#1 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}", SynchronizationContext.Current, TaskScheduler.Current); Assert.Equal(activationScheduler, TaskScheduler.Current); // "TaskScheduler.Current #1" result1.SetResult(true); }); t1.Start(); result0.SetResult(true); } catch (Exception exc) { result0.SetException(exc); } }, this.rootContext); await result0.Task.WithTimeout(TimeSpan.FromMinutes(1)); Assert.True(result0.Task.Exception == null, "Task-0 should not throw exception: " + result0.Task.Exception); Assert.True(result0.Task.Result, "Task-0 completed"); Assert.NotNull(t1); // Task-1 started await result1.Task.WithTimeout(TimeSpan.FromMinutes(1)); // give a minimum extra chance to yield after result0 has been set, as it might not have finished the t1 task await t1.WithTimeout(TimeSpan.FromMilliseconds(1)); Assert.True(t1.IsCompleted, "Task-1 completed"); Assert.False(t1.IsFaulted, "Task-1 faulted: " + t1.Exception); Assert.True(result1.Task.Result, "Task-1 completed"); } [Fact] public async Task Sched_Task_SubTaskExecutionSequencing() { UnitTestSchedulingContext context = new UnitTestSchedulingContext(); this.scheduler.RegisterWorkContext(context); LogContext("Main-task " + Task.CurrentId); int n = 0; TaskCompletionSource<int> finished = new TaskCompletionSource<int>(); var numCompleted = new[] {0}; Action closure = () => { LogContext("ClosureWorkItem-task " + Task.CurrentId); for (int i = 0; i < 10; i++) { int id = -1; Action action = () => { id = Task.CurrentId.HasValue ? (int)Task.CurrentId : -1; // ReSharper disable AccessToModifiedClosure LogContext("Sub-task " + id + " n=" + n); int k = n; this.output.WriteLine("Sub-task " + id + " sleeping"); Thread.Sleep(100); this.output.WriteLine("Sub-task " + id + " awake"); n = k + 1; // ReSharper restore AccessToModifiedClosure }; Task.Factory.StartNew(action).ContinueWith(tsk => { LogContext("Sub-task " + id + "-ContinueWith"); this.output.WriteLine("Sub-task " + id + " Done"); if (Interlocked.Increment(ref numCompleted[0]) == 10) { finished.SetResult(0); } }); } }; this.scheduler.QueueAction(closure, context); // Pause to let things run this.output.WriteLine("Main-task sleeping"); await Task.WhenAny(Task.Delay(TimeSpan.FromSeconds(10)), finished.Task); this.output.WriteLine("Main-task awake"); // N should be 10, because all tasks should execute serially Assert.True(n != 0, "Work items did not get executed"); Assert.Equal(10, n); // "Work items executed concurrently" this.scheduler.Stop(); } [Fact] public void Sched_AC_RequestContext_StartNew_ContinueWith() { const string key = "A"; int val = TestConstants.random.Next(); RequestContext.Set(key, val); this.output.WriteLine("Initial - SynchronizationContext.Current={0} TaskScheduler.Current={1}", SynchronizationContext.Current, TaskScheduler.Current); Assert.Equal(val, RequestContext.Get(key)); // "RequestContext.Get Initial" Task t0 = Task.Factory.StartNew(() => { this.output.WriteLine("#0 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}", SynchronizationContext.Current, TaskScheduler.Current); Assert.Equal(val, RequestContext.Get(key)); // "RequestContext.Get #0" Task t1 = Task.Factory.StartNew(() => { this.output.WriteLine("#1 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}", SynchronizationContext.Current, TaskScheduler.Current); Assert.Equal(val, RequestContext.Get(key)); // "RequestContext.Get #1" }); Task t2 = t1.ContinueWith((_) => { this.output.WriteLine("#2 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}", SynchronizationContext.Current, TaskScheduler.Current); Assert.Equal(val, RequestContext.Get(key)); // "RequestContext.Get #2" }); t2.Wait(TimeSpan.FromSeconds(5)); }); t0.Wait(TimeSpan.FromSeconds(10)); Assert.True(t0.IsCompleted, "Task #0 FAULTED=" + t0.Exception); } [Fact] public async Task RequestContextProtectedInQueuedTasksTest() { string key = Guid.NewGuid().ToString(); string value = Guid.NewGuid().ToString(); // Caller RequestContext is protected from clear within QueueTask RequestContext.Set(key, value); await this.scheduler.QueueTask(() => AsyncCheckClearRequestContext(key), this.rootContext); Assert.Equal(value, (string)RequestContext.Get(key)); // Caller RequestContext is protected from clear within QueueTask even if work is not actually asynchronous. await this.scheduler.QueueTask(() => NonAsyncCheckClearRequestContext(key), this.rootContext); Assert.Equal(value, (string)RequestContext.Get(key)); // Caller RequestContext is protected from clear when work is asynchronous. Func<Task> asyncCheckClearRequestContext = async () => { RequestContext.Clear(); Assert.Null(RequestContext.Get(key)); await Task.Delay(TimeSpan.Zero); }; await asyncCheckClearRequestContext(); Assert.Equal(value, (string)RequestContext.Get(key)); // Caller RequestContext is NOT protected from clear when work is not asynchronous. Func<Task> nonAsyncCheckClearRequestContext = () => { RequestContext.Clear(); Assert.Null(RequestContext.Get(key)); return Task.CompletedTask; }; await nonAsyncCheckClearRequestContext(); Assert.Null(RequestContext.Get(key)); } private async Task AsyncCheckClearRequestContext(string key) { Assert.Null(RequestContext.Get(key)); await Task.Delay(TimeSpan.Zero); } private Task NonAsyncCheckClearRequestContext(string key) { Assert.Null(RequestContext.Get(key)); return Task.CompletedTask; } private void LogContext(string what) { lock (Lockable) { this.output.WriteLine( "{0}\n" + " TaskScheduler.Current={1}\n" + " Task.Factory.Scheduler={2}\n" + " SynchronizationContext.Current={3}\n" + " Orleans-RuntimeContext.Current={4}", what, (TaskScheduler.Current == null ? "null" : TaskScheduler.Current.ToString()), (Task.Factory.Scheduler == null ? "null" : Task.Factory.Scheduler.ToString()), (SynchronizationContext.Current == null ? "null" : SynchronizationContext.Current.ToString()), (RuntimeContext.Current == null ? "null" : RuntimeContext.Current.ToString()) ); //var st = new StackTrace(); //output.WriteLine("Backtrace: " + st); } } internal static ILoggerFactory InitSchedulerLogging() { var filters = new LoggerFilterOptions(); filters.AddFilter("Scheduler", LogLevel.Trace); filters.AddFilter("Scheduler.WorkerPoolThread", LogLevel.Trace); var loggerFactory = TestingUtils.CreateDefaultLoggerFactory(TestingUtils.CreateTraceFileName("Silo", DateTime.Now.ToString("yyyyMMdd_hhmmss")), filters); return loggerFactory; } } } // ReSharper restore ConvertToConstant.Local
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace webapi_eval.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
namespace Projections { partial class LocalCartesianPanel { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.m_toolTip = new System.Windows.Forms.ToolTip(this.components); this.m_setButton = new System.Windows.Forms.Button(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.m_flatteningTextBox = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.m_majorRadiusTextBox = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.m_altitudeTextBox = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.m_longitudeTextBox = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.m_latitudeTextBox = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.m_latTextBox = new System.Windows.Forms.TextBox(); this.m_lonTextBox = new System.Windows.Forms.TextBox(); this.m_altTextBox = new System.Windows.Forms.TextBox(); this.m_XTextBox = new System.Windows.Forms.TextBox(); this.m_YTextBox = new System.Windows.Forms.TextBox(); this.m_ZTextBox = new System.Windows.Forms.TextBox(); this.m_functionComboBox = new System.Windows.Forms.ComboBox(); this.label12 = new System.Windows.Forms.Label(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.m_textBox22 = new System.Windows.Forms.TextBox(); this.m_textBox20 = new System.Windows.Forms.TextBox(); this.m_textBox21 = new System.Windows.Forms.TextBox(); this.m_textBox12 = new System.Windows.Forms.TextBox(); this.m_textBox10 = new System.Windows.Forms.TextBox(); this.m_textBox11 = new System.Windows.Forms.TextBox(); this.m_textBox02 = new System.Windows.Forms.TextBox(); this.m_textBox00 = new System.Windows.Forms.TextBox(); this.m_textBox01 = new System.Windows.Forms.TextBox(); this.button3 = new System.Windows.Forms.Button(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox3.SuspendLayout(); this.SuspendLayout(); // // m_setButton // this.m_setButton.Location = new System.Drawing.Point(12, 107); this.m_setButton.Name = "m_setButton"; this.m_setButton.Size = new System.Drawing.Size(75, 23); this.m_setButton.TabIndex = 4; this.m_setButton.Text = "Set"; this.m_toolTip.SetToolTip(this.m_setButton, "Sets the Ellipsoid Parameters"); this.m_setButton.UseVisualStyleBackColor = true; this.m_setButton.Click += new System.EventHandler(this.OnSetEllipsoid); // // button1 // this.button1.Location = new System.Drawing.Point(16, 150); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 6; this.button1.Text = "Set"; this.m_toolTip.SetToolTip(this.button1, "Sets the reference coordinates"); this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.OnSetReference); // // button2 // this.button2.Location = new System.Drawing.Point(517, 163); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(75, 23); this.button2.TabIndex = 22; this.button2.Text = "Convert"; this.m_toolTip.SetToolTip(this.button2, "Executes the current function"); this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.OnConvert); // // groupBox1 // this.groupBox1.Controls.Add(this.m_setButton); this.groupBox1.Controls.Add(this.m_flatteningTextBox); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.m_majorRadiusTextBox); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Location = new System.Drawing.Point(3, 3); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(146, 140); this.groupBox1.TabIndex = 6; this.groupBox1.TabStop = false; this.groupBox1.Text = "Ellipsoid Parameters"; // // m_flatteningTextBox // this.m_flatteningTextBox.Location = new System.Drawing.Point(12, 83); this.m_flatteningTextBox.Name = "m_flatteningTextBox"; this.m_flatteningTextBox.Size = new System.Drawing.Size(125, 20); this.m_flatteningTextBox.TabIndex = 3; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 25); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(109, 13); this.label1.TabIndex = 0; this.label1.Text = "Major Radius (meters)"; // // m_majorRadiusTextBox // this.m_majorRadiusTextBox.Location = new System.Drawing.Point(12, 42); this.m_majorRadiusTextBox.Name = "m_majorRadiusTextBox"; this.m_majorRadiusTextBox.Size = new System.Drawing.Size(125, 20); this.m_majorRadiusTextBox.TabIndex = 2; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(12, 66); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(53, 13); this.label2.TabIndex = 1; this.label2.Text = "Flattening"; // // groupBox2 // this.groupBox2.Controls.Add(this.button1); this.groupBox2.Controls.Add(this.m_altitudeTextBox); this.groupBox2.Controls.Add(this.label5); this.groupBox2.Controls.Add(this.m_longitudeTextBox); this.groupBox2.Controls.Add(this.label4); this.groupBox2.Controls.Add(this.m_latitudeTextBox); this.groupBox2.Controls.Add(this.label3); this.groupBox2.Location = new System.Drawing.Point(155, 6); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(128, 178); this.groupBox2.TabIndex = 7; this.groupBox2.TabStop = false; this.groupBox2.Text = "Origin"; // // m_altitudeTextBox // this.m_altitudeTextBox.Location = new System.Drawing.Point(16, 123); this.m_altitudeTextBox.Name = "m_altitudeTextBox"; this.m_altitudeTextBox.Size = new System.Drawing.Size(100, 20); this.m_altitudeTextBox.TabIndex = 5; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(13, 106); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(82, 13); this.label5.TabIndex = 4; this.label5.Text = "Altitude (meters)"; // // m_longitudeTextBox // this.m_longitudeTextBox.Location = new System.Drawing.Point(13, 79); this.m_longitudeTextBox.Name = "m_longitudeTextBox"; this.m_longitudeTextBox.Size = new System.Drawing.Size(100, 20); this.m_longitudeTextBox.TabIndex = 3; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(10, 63); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(101, 13); this.label4.TabIndex = 2; this.label4.Text = "Longitude (degrees)"; // // m_latitudeTextBox // this.m_latitudeTextBox.Location = new System.Drawing.Point(10, 38); this.m_latitudeTextBox.Name = "m_latitudeTextBox"; this.m_latitudeTextBox.Size = new System.Drawing.Size(100, 20); this.m_latitudeTextBox.TabIndex = 1; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(7, 22); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(92, 13); this.label3.TabIndex = 0; this.label3.Text = "Latitude (degrees)"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(295, 10); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(92, 13); this.label6.TabIndex = 8; this.label6.Text = "Latitude (degrees)"; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(295, 36); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(101, 13); this.label7.TabIndex = 9; this.label7.Text = "Longitude (degrees)"; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(295, 62); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(82, 13); this.label8.TabIndex = 10; this.label8.Text = "Altitude (meters)"; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(295, 88); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(54, 13); this.label9.TabIndex = 11; this.label9.Text = "X (meters)"; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(295, 114); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(54, 13); this.label10.TabIndex = 12; this.label10.Text = "Y (meters)"; // // label11 // this.label11.AutoSize = true; this.label11.Location = new System.Drawing.Point(295, 140); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(54, 13); this.label11.TabIndex = 13; this.label11.Text = "Z (meters)"; // // m_latTextBox // this.m_latTextBox.Location = new System.Drawing.Point(405, 6); this.m_latTextBox.Name = "m_latTextBox"; this.m_latTextBox.Size = new System.Drawing.Size(100, 20); this.m_latTextBox.TabIndex = 14; // // m_lonTextBox // this.m_lonTextBox.Location = new System.Drawing.Point(405, 32); this.m_lonTextBox.Name = "m_lonTextBox"; this.m_lonTextBox.Size = new System.Drawing.Size(100, 20); this.m_lonTextBox.TabIndex = 15; // // m_altTextBox // this.m_altTextBox.Location = new System.Drawing.Point(405, 58); this.m_altTextBox.Name = "m_altTextBox"; this.m_altTextBox.Size = new System.Drawing.Size(100, 20); this.m_altTextBox.TabIndex = 16; // // m_XTextBox // this.m_XTextBox.Location = new System.Drawing.Point(405, 84); this.m_XTextBox.Name = "m_XTextBox"; this.m_XTextBox.Size = new System.Drawing.Size(100, 20); this.m_XTextBox.TabIndex = 17; // // m_YTextBox // this.m_YTextBox.Location = new System.Drawing.Point(405, 110); this.m_YTextBox.Name = "m_YTextBox"; this.m_YTextBox.Size = new System.Drawing.Size(100, 20); this.m_YTextBox.TabIndex = 18; // // m_ZTextBox // this.m_ZTextBox.Location = new System.Drawing.Point(405, 136); this.m_ZTextBox.Name = "m_ZTextBox"; this.m_ZTextBox.Size = new System.Drawing.Size(100, 20); this.m_ZTextBox.TabIndex = 19; // // m_functionComboBox // this.m_functionComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.m_functionComboBox.FormattingEnabled = true; this.m_functionComboBox.Items.AddRange(new object[] { "Forward", "Reverse"}); this.m_functionComboBox.Location = new System.Drawing.Point(405, 163); this.m_functionComboBox.Name = "m_functionComboBox"; this.m_functionComboBox.Size = new System.Drawing.Size(100, 21); this.m_functionComboBox.TabIndex = 20; this.m_functionComboBox.SelectedIndexChanged += new System.EventHandler(this.OnNewFunction); // // label12 // this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(295, 167); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(48, 13); this.label12.TabIndex = 21; this.label12.Text = "Function"; // // groupBox3 // this.groupBox3.Controls.Add(this.m_textBox22); this.groupBox3.Controls.Add(this.m_textBox20); this.groupBox3.Controls.Add(this.m_textBox21); this.groupBox3.Controls.Add(this.m_textBox12); this.groupBox3.Controls.Add(this.m_textBox10); this.groupBox3.Controls.Add(this.m_textBox11); this.groupBox3.Controls.Add(this.m_textBox02); this.groupBox3.Controls.Add(this.m_textBox00); this.groupBox3.Controls.Add(this.m_textBox01); this.groupBox3.Location = new System.Drawing.Point(511, 10); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(325, 99); this.groupBox3.TabIndex = 25; this.groupBox3.TabStop = false; this.groupBox3.Text = "Rotation Matrix"; // // m_textBox22 // this.m_textBox22.Location = new System.Drawing.Point(218, 74); this.m_textBox22.Name = "m_textBox22"; this.m_textBox22.ReadOnly = true; this.m_textBox22.Size = new System.Drawing.Size(100, 20); this.m_textBox22.TabIndex = 30; // // m_textBox20 // this.m_textBox20.Location = new System.Drawing.Point(6, 74); this.m_textBox20.Name = "m_textBox20"; this.m_textBox20.ReadOnly = true; this.m_textBox20.Size = new System.Drawing.Size(100, 20); this.m_textBox20.TabIndex = 28; // // m_textBox21 // this.m_textBox21.Location = new System.Drawing.Point(112, 74); this.m_textBox21.Name = "m_textBox21"; this.m_textBox21.ReadOnly = true; this.m_textBox21.Size = new System.Drawing.Size(100, 20); this.m_textBox21.TabIndex = 29; // // m_textBox12 // this.m_textBox12.Location = new System.Drawing.Point(218, 50); this.m_textBox12.Name = "m_textBox12"; this.m_textBox12.ReadOnly = true; this.m_textBox12.Size = new System.Drawing.Size(100, 20); this.m_textBox12.TabIndex = 27; // // m_textBox10 // this.m_textBox10.Location = new System.Drawing.Point(6, 50); this.m_textBox10.Name = "m_textBox10"; this.m_textBox10.ReadOnly = true; this.m_textBox10.Size = new System.Drawing.Size(100, 20); this.m_textBox10.TabIndex = 25; // // m_textBox11 // this.m_textBox11.Location = new System.Drawing.Point(112, 50); this.m_textBox11.Name = "m_textBox11"; this.m_textBox11.ReadOnly = true; this.m_textBox11.Size = new System.Drawing.Size(100, 20); this.m_textBox11.TabIndex = 26; // // m_textBox02 // this.m_textBox02.Location = new System.Drawing.Point(218, 25); this.m_textBox02.Name = "m_textBox02"; this.m_textBox02.ReadOnly = true; this.m_textBox02.Size = new System.Drawing.Size(100, 20); this.m_textBox02.TabIndex = 24; // // m_textBox00 // this.m_textBox00.Location = new System.Drawing.Point(6, 25); this.m_textBox00.Name = "m_textBox00"; this.m_textBox00.ReadOnly = true; this.m_textBox00.Size = new System.Drawing.Size(100, 20); this.m_textBox00.TabIndex = 22; // // m_textBox01 // this.m_textBox01.Location = new System.Drawing.Point(112, 25); this.m_textBox01.Name = "m_textBox01"; this.m_textBox01.ReadOnly = true; this.m_textBox01.Size = new System.Drawing.Size(100, 20); this.m_textBox01.TabIndex = 23; // // button3 // this.button3.Location = new System.Drawing.Point(18, 155); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(75, 23); this.button3.TabIndex = 26; this.button3.Text = "Validate"; this.m_toolTip.SetToolTip(this.button3, "Verifies LocalCartesian Interfaces"); this.button3.UseVisualStyleBackColor = true; this.button3.Click += new System.EventHandler(this.OnValidate); // // LocalCartesianPanel // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.button3); this.Controls.Add(this.groupBox3); this.Controls.Add(this.button2); this.Controls.Add(this.label12); this.Controls.Add(this.m_functionComboBox); this.Controls.Add(this.m_ZTextBox); this.Controls.Add(this.m_YTextBox); this.Controls.Add(this.m_XTextBox); this.Controls.Add(this.m_altTextBox); this.Controls.Add(this.m_lonTextBox); this.Controls.Add(this.m_latTextBox); this.Controls.Add(this.label11); this.Controls.Add(this.label10); this.Controls.Add(this.label9); this.Controls.Add(this.label8); this.Controls.Add(this.label7); this.Controls.Add(this.label6); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Name = "LocalCartesianPanel"; this.Size = new System.Drawing.Size(842, 295); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ToolTip m_toolTip; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Button m_setButton; private System.Windows.Forms.TextBox m_flatteningTextBox; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox m_majorRadiusTextBox; private System.Windows.Forms.Label label2; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox m_altitudeTextBox; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox m_longitudeTextBox; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox m_latitudeTextBox; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label11; private System.Windows.Forms.TextBox m_latTextBox; private System.Windows.Forms.TextBox m_lonTextBox; private System.Windows.Forms.TextBox m_altTextBox; private System.Windows.Forms.TextBox m_XTextBox; private System.Windows.Forms.TextBox m_YTextBox; private System.Windows.Forms.TextBox m_ZTextBox; private System.Windows.Forms.ComboBox m_functionComboBox; private System.Windows.Forms.Label label12; private System.Windows.Forms.Button button2; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.TextBox m_textBox22; private System.Windows.Forms.TextBox m_textBox20; private System.Windows.Forms.TextBox m_textBox21; private System.Windows.Forms.TextBox m_textBox12; private System.Windows.Forms.TextBox m_textBox10; private System.Windows.Forms.TextBox m_textBox11; private System.Windows.Forms.TextBox m_textBox02; private System.Windows.Forms.TextBox m_textBox00; private System.Windows.Forms.TextBox m_textBox01; private System.Windows.Forms.Button button3; } }
// 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.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DevTestLabs { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for ArtifactSourceOperations. /// </summary> public static partial class ArtifactSourceOperationsExtensions { /// <summary> /// List artifact sources in a given lab. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static IPage<ArtifactSource> List(this IArtifactSourceOperations operations, string resourceGroupName, string labName, ODataQuery<ArtifactSource> odataQuery = default(ODataQuery<ArtifactSource>)) { return Task.Factory.StartNew(s => ((IArtifactSourceOperations)s).ListAsync(resourceGroupName, labName, odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// List artifact sources in a given lab. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ArtifactSource>> ListAsync(this IArtifactSourceOperations operations, string resourceGroupName, string labName, ODataQuery<ArtifactSource> odataQuery = default(ODataQuery<ArtifactSource>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, labName, odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get artifact source. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the artifact source. /// </param> public static ArtifactSource GetResource(this IArtifactSourceOperations operations, string resourceGroupName, string labName, string name) { return Task.Factory.StartNew(s => ((IArtifactSourceOperations)s).GetResourceAsync(resourceGroupName, labName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get artifact source. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the artifact source. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ArtifactSource> GetResourceAsync(this IArtifactSourceOperations operations, string resourceGroupName, string labName, string name, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetResourceWithHttpMessagesAsync(resourceGroupName, labName, name, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Create or replace an existing artifact source. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the artifact source. /// </param> /// <param name='artifactSource'> /// </param> public static ArtifactSource CreateOrUpdateResource(this IArtifactSourceOperations operations, string resourceGroupName, string labName, string name, ArtifactSource artifactSource) { return Task.Factory.StartNew(s => ((IArtifactSourceOperations)s).CreateOrUpdateResourceAsync(resourceGroupName, labName, name, artifactSource), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create or replace an existing artifact source. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the artifact source. /// </param> /// <param name='artifactSource'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ArtifactSource> CreateOrUpdateResourceAsync(this IArtifactSourceOperations operations, string resourceGroupName, string labName, string name, ArtifactSource artifactSource, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateResourceWithHttpMessagesAsync(resourceGroupName, labName, name, artifactSource, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Delete artifact source. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the artifact source. /// </param> public static void DeleteResource(this IArtifactSourceOperations operations, string resourceGroupName, string labName, string name) { Task.Factory.StartNew(s => ((IArtifactSourceOperations)s).DeleteResourceAsync(resourceGroupName, labName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete artifact source. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the artifact source. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteResourceAsync(this IArtifactSourceOperations operations, string resourceGroupName, string labName, string name, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteResourceWithHttpMessagesAsync(resourceGroupName, labName, name, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Modify properties of artifact sources. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the artifact source. /// </param> /// <param name='artifactSource'> /// </param> public static ArtifactSource PatchResource(this IArtifactSourceOperations operations, string resourceGroupName, string labName, string name, ArtifactSource artifactSource) { return Task.Factory.StartNew(s => ((IArtifactSourceOperations)s).PatchResourceAsync(resourceGroupName, labName, name, artifactSource), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Modify properties of artifact sources. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='name'> /// The name of the artifact source. /// </param> /// <param name='artifactSource'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ArtifactSource> PatchResourceAsync(this IArtifactSourceOperations operations, string resourceGroupName, string labName, string name, ArtifactSource artifactSource, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PatchResourceWithHttpMessagesAsync(resourceGroupName, labName, name, artifactSource, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// List artifact sources in a given lab. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<ArtifactSource> ListNext(this IArtifactSourceOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IArtifactSourceOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// List artifact sources in a given lab. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ArtifactSource>> ListNextAsync(this IArtifactSourceOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// Static class that contains static glm functions /// </summary> public static partial class glm { /// <summary> /// Returns an array with all values /// </summary> public static float[] Values(quat q) => q.Values; /// <summary> /// Returns an enumerator that iterates through all components. /// </summary> public static IEnumerator<float> GetEnumerator(quat q) => q.GetEnumerator(); /// <summary> /// Returns a string representation of this quaternion using ', ' as a seperator. /// </summary> public static string ToString(quat q) => q.ToString(); /// <summary> /// Returns a string representation of this quaternion using a provided seperator. /// </summary> public static string ToString(quat q, string sep) => q.ToString(sep); /// <summary> /// Returns a string representation of this quaternion using a provided seperator and a format provider for each component. /// </summary> public static string ToString(quat q, string sep, IFormatProvider provider) => q.ToString(sep, provider); /// <summary> /// Returns a string representation of this quaternion using a provided seperator and a format for each component. /// </summary> public static string ToString(quat q, string sep, string format) => q.ToString(sep, format); /// <summary> /// Returns a string representation of this quaternion using a provided seperator and a format and format provider for each component. /// </summary> public static string ToString(quat q, string sep, string format, IFormatProvider provider) => q.ToString(sep, format, provider); /// <summary> /// Returns the number of components (4). /// </summary> public static int Count(quat q) => q.Count; /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool Equals(quat q, quat rhs) => q.Equals(rhs); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public static bool Equals(quat q, object obj) => q.Equals(obj); /// <summary> /// Returns a hash code for this instance. /// </summary> public static int GetHashCode(quat q) => q.GetHashCode(); /// <summary> /// Returns a bvec4 from component-wise application of IsInfinity (float.IsInfinity(v)). /// </summary> public static bvec4 IsInfinity(quat v) => quat.IsInfinity(v); /// <summary> /// Returns a bvec4 from component-wise application of IsFinite (!float.IsNaN(v) &amp;&amp; !float.IsInfinity(v)). /// </summary> public static bvec4 IsFinite(quat v) => quat.IsFinite(v); /// <summary> /// Returns a bvec4 from component-wise application of IsNaN (float.IsNaN(v)). /// </summary> public static bvec4 IsNaN(quat v) => quat.IsNaN(v); /// <summary> /// Returns a bvec4 from component-wise application of IsNegativeInfinity (float.IsNegativeInfinity(v)). /// </summary> public static bvec4 IsNegativeInfinity(quat v) => quat.IsNegativeInfinity(v); /// <summary> /// Returns a bvec4 from component-wise application of IsPositiveInfinity (float.IsPositiveInfinity(v)). /// </summary> public static bvec4 IsPositiveInfinity(quat v) => quat.IsPositiveInfinity(v); /// <summary> /// Returns a bvec4 from component-wise application of Equal (lhs == rhs). /// </summary> public static bvec4 Equal(quat lhs, quat rhs) => quat.Equal(lhs, rhs); /// <summary> /// Returns a bvec4 from component-wise application of NotEqual (lhs != rhs). /// </summary> public static bvec4 NotEqual(quat lhs, quat rhs) => quat.NotEqual(lhs, rhs); /// <summary> /// Returns a bvec4 from component-wise application of GreaterThan (lhs &gt; rhs). /// </summary> public static bvec4 GreaterThan(quat lhs, quat rhs) => quat.GreaterThan(lhs, rhs); /// <summary> /// Returns a bvec4 from component-wise application of GreaterThanEqual (lhs &gt;= rhs). /// </summary> public static bvec4 GreaterThanEqual(quat lhs, quat rhs) => quat.GreaterThanEqual(lhs, rhs); /// <summary> /// Returns a bvec4 from component-wise application of LesserThan (lhs &lt; rhs). /// </summary> public static bvec4 LesserThan(quat lhs, quat rhs) => quat.LesserThan(lhs, rhs); /// <summary> /// Returns a bvec4 from component-wise application of LesserThanEqual (lhs &lt;= rhs). /// </summary> public static bvec4 LesserThanEqual(quat lhs, quat rhs) => quat.LesserThanEqual(lhs, rhs); /// <summary> /// Returns the inner product (dot product, scalar product) of the two quaternions. /// </summary> public static float Dot(quat lhs, quat rhs) => quat.Dot(lhs, rhs); /// <summary> /// Returns the euclidean length of this quaternion. /// </summary> public static float Length(quat q) => q.Length; /// <summary> /// Returns the squared euclidean length of this quaternion. /// </summary> public static float LengthSqr(quat q) => q.LengthSqr; /// <summary> /// Returns a copy of this quaternion with length one (undefined if this has zero length). /// </summary> public static quat Normalized(quat q) => q.Normalized; /// <summary> /// Returns a copy of this quaternion with length one (returns zero if length is zero). /// </summary> public static quat NormalizedSafe(quat q) => q.NormalizedSafe; /// <summary> /// Returns the represented angle of this quaternion. /// </summary> public static double Angle(quat q) => q.Angle; /// <summary> /// Returns the represented axis of this quaternion. /// </summary> public static vec3 Axis(quat q) => q.Axis; /// <summary> /// Returns the represented yaw angle of this quaternion. /// </summary> public static double Yaw(quat q) => q.Yaw; /// <summary> /// Returns the represented pitch angle of this quaternion. /// </summary> public static double Pitch(quat q) => q.Pitch; /// <summary> /// Returns the represented roll angle of this quaternion. /// </summary> public static double Roll(quat q) => q.Roll; /// <summary> /// Returns the represented euler angles (pitch, yaw, roll) of this quaternion. /// </summary> public static dvec3 EulerAngles(quat q) => q.EulerAngles; /// <summary> /// Rotates this quaternion from an axis and an angle (in radians). /// </summary> public static quat Rotated(quat q, float angle, vec3 v) => q.Rotated(angle, v); /// <summary> /// Creates a mat3 that realizes the rotation of this quaternion /// </summary> public static mat3 ToMat3(quat q) => q.ToMat3; /// <summary> /// Creates a mat4 that realizes the rotation of this quaternion /// </summary> public static mat4 ToMat4(quat q) => q.ToMat4; /// <summary> /// Returns the conjugated quaternion /// </summary> public static quat Conjugate(quat q) => q.Conjugate; /// <summary> /// Returns the inverse quaternion /// </summary> public static quat Inverse(quat q) => q.Inverse; /// <summary> /// Returns the cross product between two quaternions. /// </summary> public static quat Cross(quat q1, quat q2) => quat.Cross(q1, q2); /// <summary> /// Calculates a proper spherical interpolation between two quaternions (only works for normalized quaternions). /// </summary> public static quat Mix(quat x, quat y, float a) => quat.Mix(x, y, a); /// <summary> /// Calculates a proper spherical interpolation between two quaternions (only works for normalized quaternions). /// </summary> public static quat SLerp(quat x, quat y, float a) => quat.SLerp(x, y, a); /// <summary> /// Applies squad interpolation of these quaternions /// </summary> public static quat Squad(quat q1, quat q2, quat s1, quat s2, float h) => quat.Squad(q1, q2, s1, s2, h); /// <summary> /// Returns a quat from component-wise application of Lerp (min * (1-a) + max * a). /// </summary> public static quat Lerp(quat min, quat max, quat a) => quat.Lerp(min, max, a); } }
// 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.Text; using System.Diagnostics; using System.Collections.Generic; namespace System.Xml { internal partial class XmlWellFormedWriter : XmlWriter { // // Private types // private class NamespaceResolverProxy : IXmlNamespaceResolver { private XmlWellFormedWriter _wfWriter; internal NamespaceResolverProxy(XmlWellFormedWriter wfWriter) { _wfWriter = wfWriter; } IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope) { throw NotImplemented.ByDesign; } string IXmlNamespaceResolver.LookupNamespace(string prefix) { return _wfWriter.LookupNamespace(prefix); } string IXmlNamespaceResolver.LookupPrefix(string namespaceName) { return _wfWriter.LookupPrefix(namespaceName); } } private partial struct ElementScope { internal int prevNSTop; internal string prefix; internal string localName; internal string namespaceUri; internal XmlSpace xmlSpace; internal string xmlLang; internal void Set(string prefix, string localName, string namespaceUri, int prevNSTop) { this.prevNSTop = prevNSTop; this.prefix = prefix; this.namespaceUri = namespaceUri; this.localName = localName; this.xmlSpace = (System.Xml.XmlSpace)(int)-1; this.xmlLang = null; } internal void WriteEndElement(XmlRawWriter rawWriter) { rawWriter.WriteEndElement(prefix, localName, namespaceUri); } internal void WriteFullEndElement(XmlRawWriter rawWriter) { rawWriter.WriteFullEndElement(prefix, localName, namespaceUri); } } private enum NamespaceKind { Written, NeedToWrite, Implied, Special, } private partial struct Namespace { internal string prefix; internal string namespaceUri; internal NamespaceKind kind; internal int prevNsIndex; internal void Set(string prefix, string namespaceUri, NamespaceKind kind) { this.prefix = prefix; this.namespaceUri = namespaceUri; this.kind = kind; this.prevNsIndex = -1; } internal void WriteDecl(XmlWriter writer, XmlRawWriter rawWriter) { Debug.Assert(kind == NamespaceKind.NeedToWrite); if (null != rawWriter) { rawWriter.WriteNamespaceDeclaration(prefix, namespaceUri); } else { if (prefix.Length == 0) { writer.WriteStartAttribute(string.Empty, "xmlns", XmlReservedNs.NsXmlNs); } else { writer.WriteStartAttribute("xmlns", prefix, XmlReservedNs.NsXmlNs); } writer.WriteString(namespaceUri); writer.WriteEndAttribute(); } } } private struct AttrName { internal string prefix; internal string namespaceUri; internal string localName; internal int prev; internal void Set(string prefix, string localName, string namespaceUri) { this.prefix = prefix; this.namespaceUri = namespaceUri; this.localName = localName; this.prev = 0; } internal bool IsDuplicate(string prefix, string localName, string namespaceUri) { return ((this.localName == localName) && ((this.prefix == prefix) || (this.namespaceUri == namespaceUri))); } } private enum SpecialAttribute { No = 0, DefaultXmlns, PrefixedXmlns, XmlSpace, XmlLang } private partial class AttributeValueCache { private enum ItemType { EntityRef, CharEntity, SurrogateCharEntity, Whitespace, String, StringChars, Raw, RawChars, ValueString, } private class Item { internal ItemType type; internal object data; internal Item() { } internal void Set(ItemType type, object data) { this.type = type; this.data = data; } } private class BufferChunk { internal char[] buffer; internal int index; internal int count; internal BufferChunk(char[] buffer, int index, int count) { this.buffer = buffer; this.index = index; this.count = count; } } private StringBuilder _stringValue = new StringBuilder(); private string _singleStringValue; // special-case for a single WriteString call private Item[] _items; private int _firstItem; private int _lastItem = -1; internal string StringValue { get { if (_singleStringValue != null) { return _singleStringValue; } else { return _stringValue.ToString(); } } } internal void WriteEntityRef(string name) { if (_singleStringValue != null) { StartComplexValue(); } switch (name) { case "lt": _stringValue.Append('<'); break; case "gt": _stringValue.Append('>'); break; case "quot": _stringValue.Append('"'); break; case "apos": _stringValue.Append('\''); break; case "amp": _stringValue.Append('&'); break; default: _stringValue.Append('&'); _stringValue.Append(name); _stringValue.Append(';'); break; } AddItem(ItemType.EntityRef, name); } internal void WriteCharEntity(char ch) { if (_singleStringValue != null) { StartComplexValue(); } _stringValue.Append(ch); AddItem(ItemType.CharEntity, ch); } internal void WriteSurrogateCharEntity(char lowChar, char highChar) { if (_singleStringValue != null) { StartComplexValue(); } _stringValue.Append(highChar); _stringValue.Append(lowChar); AddItem(ItemType.SurrogateCharEntity, new char[] { lowChar, highChar }); } internal void WriteWhitespace(string ws) { if (_singleStringValue != null) { StartComplexValue(); } _stringValue.Append(ws); AddItem(ItemType.Whitespace, ws); } internal void WriteString(string text) { if (_singleStringValue != null) { StartComplexValue(); } else { // special-case for a single WriteString if (_lastItem == -1) { _singleStringValue = text; return; } } _stringValue.Append(text); AddItem(ItemType.String, text); } internal void WriteChars(char[] buffer, int index, int count) { if (_singleStringValue != null) { StartComplexValue(); } _stringValue.Append(buffer, index, count); AddItem(ItemType.StringChars, new BufferChunk(buffer, index, count)); } internal void WriteRaw(char[] buffer, int index, int count) { if (_singleStringValue != null) { StartComplexValue(); } _stringValue.Append(buffer, index, count); AddItem(ItemType.RawChars, new BufferChunk(buffer, index, count)); } internal void WriteRaw(string data) { if (_singleStringValue != null) { StartComplexValue(); } _stringValue.Append(data); AddItem(ItemType.Raw, data); } internal void WriteValue(string value) { if (_singleStringValue != null) { StartComplexValue(); } _stringValue.Append(value); AddItem(ItemType.ValueString, value); } internal void Replay(XmlWriter writer) { if (_singleStringValue != null) { writer.WriteString(_singleStringValue); return; } BufferChunk bufChunk; for (int i = _firstItem; i <= _lastItem; i++) { Item item = _items[i]; switch (item.type) { case ItemType.EntityRef: writer.WriteEntityRef((string)item.data); break; case ItemType.CharEntity: writer.WriteCharEntity((char)item.data); break; case ItemType.SurrogateCharEntity: char[] chars = (char[])item.data; writer.WriteSurrogateCharEntity(chars[0], chars[1]); break; case ItemType.Whitespace: writer.WriteWhitespace((string)item.data); break; case ItemType.String: writer.WriteString((string)item.data); break; case ItemType.StringChars: bufChunk = (BufferChunk)item.data; writer.WriteChars(bufChunk.buffer, bufChunk.index, bufChunk.count); break; case ItemType.Raw: writer.WriteRaw((string)item.data); break; case ItemType.RawChars: bufChunk = (BufferChunk)item.data; writer.WriteChars(bufChunk.buffer, bufChunk.index, bufChunk.count); break; case ItemType.ValueString: writer.WriteValue((string)item.data); break; default: Debug.Assert(false, "Unexpected ItemType value."); break; } } } // This method trims whitespaces from the beginnig and the end of the string and cached writer events internal void Trim() { // if only one string value -> trim the write spaces directly if (_singleStringValue != null) { _singleStringValue = XmlConvert.TrimString(_singleStringValue); return; } // trim the string in StringBuilder string valBefore = _stringValue.ToString(); string valAfter = XmlConvert.TrimString(valBefore); if (valBefore != valAfter) { _stringValue = new StringBuilder(valAfter); } // trim the beginning of the recorded writer events XmlCharType xmlCharType = XmlCharType.Instance; int i = _firstItem; while (i == _firstItem && i <= _lastItem) { Item item = _items[i]; switch (item.type) { case ItemType.Whitespace: _firstItem++; break; case ItemType.String: case ItemType.Raw: case ItemType.ValueString: item.data = XmlConvert.TrimStringStart((string)item.data); if (((string)item.data).Length == 0) { // no characters left -> move the firstItem index to exclude it from the Replay _firstItem++; } break; case ItemType.StringChars: case ItemType.RawChars: BufferChunk bufChunk = (BufferChunk)item.data; int endIndex = bufChunk.index + bufChunk.count; while (bufChunk.index < endIndex && xmlCharType.IsWhiteSpace(bufChunk.buffer[bufChunk.index])) { bufChunk.index++; bufChunk.count--; } if (bufChunk.index == endIndex) { // no characters left -> move the firstItem index to exclude it from the Replay _firstItem++; } break; } i++; } // trim the end of the recorded writer events i = _lastItem; while (i == _lastItem && i >= _firstItem) { Item item = _items[i]; switch (item.type) { case ItemType.Whitespace: _lastItem--; break; case ItemType.String: case ItemType.Raw: case ItemType.ValueString: item.data = XmlConvert.TrimStringEnd((string)item.data); if (((string)item.data).Length == 0) { // no characters left -> move the lastItem index to exclude it from the Replay _lastItem--; } break; case ItemType.StringChars: case ItemType.RawChars: BufferChunk bufChunk = (BufferChunk)item.data; while (bufChunk.count > 0 && xmlCharType.IsWhiteSpace(bufChunk.buffer[bufChunk.index + bufChunk.count - 1])) { bufChunk.count--; } if (bufChunk.count == 0) { // no characters left -> move the lastItem index to exclude it from the Replay _lastItem--; } break; } i--; } } internal void Clear() { _singleStringValue = null; _lastItem = -1; _firstItem = 0; _stringValue.Length = 0; } private void StartComplexValue() { Debug.Assert(_singleStringValue != null); Debug.Assert(_lastItem == -1); _stringValue.Append(_singleStringValue); AddItem(ItemType.String, _singleStringValue); _singleStringValue = null; } private void AddItem(ItemType type, object data) { int newItemIndex = _lastItem + 1; if (_items == null) { _items = new Item[4]; } else if (_items.Length == newItemIndex) { Item[] newItems = new Item[newItemIndex * 2]; Array.Copy(_items, 0, newItems, 0, newItemIndex); _items = newItems; } if (_items[newItemIndex] == null) { _items[newItemIndex] = new Item(); } _items[newItemIndex].Set(type, data); _lastItem = newItemIndex; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; namespace System.Net.Http.Headers { public class MediaTypeHeaderValue : ICloneable { private const string charSet = "charset"; private ObjectCollection<NameValueHeaderValue> _parameters; private string _mediaType; public string CharSet { get { NameValueHeaderValue charSetParameter = NameValueHeaderValue.Find(_parameters, charSet); if (charSetParameter != null) { return charSetParameter.Value; } return null; } set { // We don't prevent a user from setting whitespace-only charsets. Like we can't prevent a user from // setting a non-existing charset. NameValueHeaderValue charSetParameter = NameValueHeaderValue.Find(_parameters, charSet); if (string.IsNullOrEmpty(value)) { // Remove charset parameter if (charSetParameter != null) { _parameters.Remove(charSetParameter); } } else { if (charSetParameter != null) { charSetParameter.Value = value; } else { Parameters.Add(new NameValueHeaderValue(charSet, value)); } } } } public ICollection<NameValueHeaderValue> Parameters { get { if (_parameters == null) { _parameters = new ObjectCollection<NameValueHeaderValue>(); } return _parameters; } } public string MediaType { get { return _mediaType; } set { CheckMediaTypeFormat(value, "value"); _mediaType = value; } } internal MediaTypeHeaderValue() { // Used by the parser to create a new instance of this type. } protected MediaTypeHeaderValue(MediaTypeHeaderValue source) { Debug.Assert(source != null); _mediaType = source._mediaType; if (source._parameters != null) { foreach (var parameter in source._parameters) { this.Parameters.Add((NameValueHeaderValue)((ICloneable)parameter).Clone()); } } } public MediaTypeHeaderValue(string mediaType) { CheckMediaTypeFormat(mediaType, "mediaType"); _mediaType = mediaType; } public override string ToString() { return _mediaType + NameValueHeaderValue.ToString(_parameters, ';', true); } public override bool Equals(object obj) { MediaTypeHeaderValue other = obj as MediaTypeHeaderValue; if (other == null) { return false; } return string.Equals(_mediaType, other._mediaType, StringComparison.OrdinalIgnoreCase) && HeaderUtilities.AreEqualCollections(_parameters, other._parameters); } public override int GetHashCode() { // The media-type string is case-insensitive. return StringComparer.OrdinalIgnoreCase.GetHashCode(_mediaType) ^ NameValueHeaderValue.GetHashCode(_parameters); } public static MediaTypeHeaderValue Parse(string input) { int index = 0; return (MediaTypeHeaderValue)MediaTypeHeaderParser.SingleValueParser.ParseValue(input, null, ref index); } public static bool TryParse(string input, out MediaTypeHeaderValue parsedValue) { int index = 0; object output; parsedValue = null; if (MediaTypeHeaderParser.SingleValueParser.TryParseValue(input, null, ref index, out output)) { parsedValue = (MediaTypeHeaderValue)output; return true; } return false; } internal static int GetMediaTypeLength(string input, int startIndex, Func<MediaTypeHeaderValue> mediaTypeCreator, out MediaTypeHeaderValue parsedValue) { Debug.Assert(mediaTypeCreator != null); Debug.Assert(startIndex >= 0); parsedValue = null; if (string.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return 0; } // Caller must remove leading whitespace. If not, we'll return 0. string mediaType = null; int mediaTypeLength = MediaTypeHeaderValue.GetMediaTypeExpressionLength(input, startIndex, out mediaType); if (mediaTypeLength == 0) { return 0; } int current = startIndex + mediaTypeLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); MediaTypeHeaderValue mediaTypeHeader = null; // If we're not done and we have a parameter delimiter, then we have a list of parameters. if ((current < input.Length) && (input[current] == ';')) { mediaTypeHeader = mediaTypeCreator(); mediaTypeHeader._mediaType = mediaType; current++; // skip delimiter. int parameterLength = NameValueHeaderValue.GetNameValueListLength(input, current, ';', (ObjectCollection<NameValueHeaderValue>)mediaTypeHeader.Parameters); if (parameterLength == 0) { return 0; } parsedValue = mediaTypeHeader; return current + parameterLength - startIndex; } // We have a media type without parameters. mediaTypeHeader = mediaTypeCreator(); mediaTypeHeader._mediaType = mediaType; parsedValue = mediaTypeHeader; return current - startIndex; } private static int GetMediaTypeExpressionLength(string input, int startIndex, out string mediaType) { Debug.Assert((input != null) && (input.Length > 0) && (startIndex < input.Length)); // This method just parses the "type/subtype" string, it does not parse parameters. mediaType = null; // Parse the type, i.e. <type> in media type string "<type>/<subtype>; param1=value1; param2=value2" int typeLength = HttpRuleParser.GetTokenLength(input, startIndex); if (typeLength == 0) { return 0; } int current = startIndex + typeLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); // Parse the separator between type and subtype if ((current >= input.Length) || (input[current] != '/')) { return 0; } current++; // skip delimiter. current = current + HttpRuleParser.GetWhitespaceLength(input, current); // Parse the subtype, i.e. <subtype> in media type string "<type>/<subtype>; param1=value1; param2=value2" int subtypeLength = HttpRuleParser.GetTokenLength(input, current); if (subtypeLength == 0) { return 0; } // If there are no whitespace between <type> and <subtype> in <type>/<subtype> get the media type using // one Substring call. Otherwise get substrings for <type> and <subtype> and combine them. int mediatTypeLength = current + subtypeLength - startIndex; if (typeLength + subtypeLength + 1 == mediatTypeLength) { mediaType = input.Substring(startIndex, mediatTypeLength); } else { mediaType = input.Substring(startIndex, typeLength) + "/" + input.Substring(current, subtypeLength); } return mediatTypeLength; } private static void CheckMediaTypeFormat(string mediaType, string parameterName) { if (string.IsNullOrEmpty(mediaType)) { throw new ArgumentException(SR.net_http_argument_empty_string, parameterName); } // When adding values using strongly typed objects, no leading/trailing LWS (whitespace) are allowed. // Also no LWS between type and subtype are allowed. string tempMediaType; int mediaTypeLength = GetMediaTypeExpressionLength(mediaType, 0, out tempMediaType); if ((mediaTypeLength == 0) || (tempMediaType.Length != mediaType.Length)) { throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, mediaType)); } } // Implement ICloneable explicitly to allow derived types to "override" the implementation. object ICloneable.Clone() { return new MediaTypeHeaderValue(this); } } }
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- #pragma warning disable 618 namespace System.Activities.Presentation { using System.Activities.Presentation.Internal.PropertyEditing; using System.Activities.Presentation.Model; using System.Activities.Presentation.Services; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Runtime; using System.Windows; using System.Windows.Automation.Peers; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Threading; using System.Activities.Presentation.View; using System.Windows.Shapes; // This is similar to the WorkflowItemPresenter , but its an edit box for collections. It supports drag drop, and delete. // it auto refreshes the collection on collection changed events. public class WorkflowItemsPresenter : ContentControl, IMultipleDragEnabledCompositeView { public static readonly DependencyProperty HintTextProperty = DependencyProperty.Register("HintText", typeof(string), typeof(WorkflowItemsPresenter), new UIPropertyMetadata(String.Empty, new PropertyChangedCallback(WorkflowItemsPresenter.OnHintTextChanged))); public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register("Items", typeof(ModelItemCollection), typeof(WorkflowItemsPresenter), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(WorkflowItemsPresenter.OnItemsChanged))); public static readonly DependencyProperty SpacerTemplateProperty = DependencyProperty.Register("SpacerTemplate", typeof(DataTemplate), typeof(WorkflowItemsPresenter), new UIPropertyMetadata(null)); public static readonly DependencyProperty HeaderTemplateProperty = DependencyProperty.Register("HeaderTemplate", typeof(DataTemplate), typeof(WorkflowItemsPresenter), new UIPropertyMetadata(null)); public static readonly DependencyProperty FooterTemplateProperty = DependencyProperty.Register("FooterTemplate", typeof(DataTemplate), typeof(WorkflowItemsPresenter), new UIPropertyMetadata(null)); public static readonly DependencyProperty ItemsPanelProperty = DependencyProperty.Register("ItemsPanel", typeof(ItemsPanelTemplate), typeof(WorkflowItemsPresenter), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(WorkflowItemsPresenter.OnItemsPanelChanged))); public static readonly DependencyProperty IndexProperty = DependencyProperty.RegisterAttached("Index", typeof(int), typeof(WorkflowItemsPresenter), new UIPropertyMetadata(addAtEndMarker)); public static readonly DependencyProperty AllowedItemTypeProperty = DependencyProperty.Register("AllowedItemType", typeof(Type), typeof(WorkflowItemsPresenter), new UIPropertyMetadata(typeof(object))); public static readonly DependencyProperty IsDefaultContainerProperty = DependencyProperty.Register("IsDefaultContainer", typeof(bool), typeof(WorkflowItemsPresenter), new UIPropertyMetadata(false)); public static readonly DependencyProperty DroppingTypeResolvingOptionsProperty = DependencyProperty.Register("DroppingTypeResolvingOptions", typeof(TypeResolvingOptions), typeof(WorkflowItemsPresenter)); const int addAtEndMarker = -2; int selectedSpacerIndex; ItemsControl panel; Grid hintTextGrid; EditingContext context = null; bool isRegisteredWithParent = false; bool populateOnLoad = false; bool handleSpacerGotKeyboardFocus = false; Grid outerGrid; public WorkflowItemsPresenter() { panel = new ItemsControl(); panel.Focusable = false; hintTextGrid = new Grid(); hintTextGrid.Focusable = false; hintTextGrid.Background = Brushes.Transparent; hintTextGrid.DataContext = this; hintTextGrid.SetBinding(Grid.MinHeightProperty, "MinHeight"); hintTextGrid.SetBinding(Grid.MinWidthProperty, "MinWidth"); TextBlock text = new TextBlock(); text.Focusable = false; text.SetBinding(TextBlock.TextProperty, "HintText"); text.HorizontalAlignment = HorizontalAlignment.Center; text.VerticalAlignment = VerticalAlignment.Center; text.DataContext = this; text.Foreground = new SolidColorBrush(SystemColors.GrayTextColor); text.FontStyle = FontStyles.Italic; ((IAddChild)hintTextGrid).AddChild(text); this.outerGrid = new Grid() { RowDefinitions = { new RowDefinition(), new RowDefinition() }, ColumnDefinitions = { new ColumnDefinition() } }; Grid.SetRow(this.panel, 0); Grid.SetColumn(this.panel, 0); Grid.SetRow(this.hintTextGrid, 1); Grid.SetColumn(this.hintTextGrid, 0); this.outerGrid.Children.Add(panel); this.outerGrid.Children.Add(hintTextGrid); } public Type AllowedItemType { get { return (Type)GetValue(AllowedItemTypeProperty); } set { SetValue(AllowedItemTypeProperty, value); } } public string HintText { get { return (string)GetValue(HintTextProperty); } set { SetValue(HintTextProperty, value); } } [Fx.Tag.KnownXamlExternal] public DataTemplate SpacerTemplate { get { return (DataTemplate)GetValue(SpacerTemplateProperty); } set { SetValue(SpacerTemplateProperty, value); } } [Fx.Tag.KnownXamlExternal] public DataTemplate HeaderTemplate { get { return (DataTemplate)GetValue(HeaderTemplateProperty); } set { SetValue(HeaderTemplateProperty, value); } } [Fx.Tag.KnownXamlExternal] public DataTemplate FooterTemplate { get { return (DataTemplate)GetValue(FooterTemplateProperty); } set { SetValue(FooterTemplateProperty, value); } } [Fx.Tag.KnownXamlExternal] public ItemsPanelTemplate ItemsPanel { get { return (ItemsPanelTemplate)GetValue(ItemsPanelProperty); } set { SetValue(ItemsPanelProperty, value); } } [SuppressMessage(FxCop.Category.Usage, FxCop.Rule.CollectionPropertiesShouldBeReadOnly, Justification = "Setter is provided to enable setting this property in code.")] [Fx.Tag.KnownXamlExternal] public ModelItemCollection Items { get { return (ModelItemCollection)GetValue(ItemsProperty); } set { SetValue(ItemsProperty, value); } } EditingContext Context { get { if (context == null) { IModelTreeItem modelTreeItem = this.Items as IModelTreeItem; if (modelTreeItem != null) { this.context = modelTreeItem.ModelTreeManager.Context; } } return context; } } public bool IsDefaultContainer { get { return (bool)GetValue(IsDefaultContainerProperty); } set { SetValue(IsDefaultContainerProperty, value); } } [Fx.Tag.KnownXamlExternal] public TypeResolvingOptions DroppingTypeResolvingOptions { get { return (TypeResolvingOptions)GetValue(DroppingTypeResolvingOptionsProperty); } set { SetValue(DroppingTypeResolvingOptionsProperty, value); } } static void OnHintTextChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { WorkflowItemsPresenter itemsPresenter = (WorkflowItemsPresenter)dependencyObject; itemsPresenter.UpdateHintTextVisibility(e.NewValue as string); } static void OnItemsChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { WorkflowItemsPresenter itemsPresenter = (WorkflowItemsPresenter)dependencyObject; itemsPresenter.OnItemsChanged((ModelItemCollection)e.OldValue, (ModelItemCollection)e.NewValue); } static void OnItemsPanelChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { WorkflowItemsPresenter itemsPresenter = (WorkflowItemsPresenter)dependencyObject; itemsPresenter.panel.ItemsPanel = (ItemsPanelTemplate)e.NewValue; } void OnItemsChanged(ModelItemCollection oldItemsCollection, ModelItemCollection newItemsCollection) { if (oldItemsCollection != null) { oldItemsCollection.CollectionChanged -= this.OnCollectionChanged; } if (newItemsCollection != null) { newItemsCollection.CollectionChanged += this.OnCollectionChanged; } if (!isRegisteredWithParent) { CutCopyPasteHelper.RegisterWithParentViewElement(this); isRegisteredWithParent = true; } populateOnLoad = false; PopulateContent(); } void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { // if this.Items is null, and we are getting a collection changed that // means this event some how happened before this can get the unloaded event // and unsubscribe from this event. if (this.Items == null) { return; } bool fullRepopulateNeeded = true; // when one item is dropped into this items presenter focus on the new view element for it. if (e.Action == NotifyCollectionChangedAction.Add && e.NewItems != null && e.NewItems.Count == 1) { // insert itemview and spacer fullRepopulateNeeded = false; int itemViewIndex = GetViewIndexForItem(e.NewStartingIndex); VirtualizedContainerService containerService = this.Context.Services.GetService<VirtualizedContainerService>(); UIElement itemView = containerService.GetContainer((ModelItem)e.NewItems[0], this); this.panel.Items.Insert(itemViewIndex, itemView as UIElement); // index 2 + i*2 + 1 is spacer i+1 FrameworkElement spacer = CreateSpacer(); this.panel.Items.Insert(itemViewIndex + 1, spacer); ModelItem insertedItem = (ModelItem)e.NewItems[0]; this.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, (Action)(() => { UIElement view = (UIElement)insertedItem.View; if (view != null) { Keyboard.Focus(view); } })); } else if (e.Action == NotifyCollectionChangedAction.Remove) { if (e.OldItems != null && e.OldItems.Count == 1) { fullRepopulateNeeded = false; int itemViewIndex = GetViewIndexForItem(e.OldStartingIndex); this.panel.Items.RemoveAt(itemViewIndex); //remove spacer also this.panel.Items.RemoveAt(itemViewIndex); } if (this.Items.Count == 0) { fullRepopulateNeeded = true; } // deselect removed items if (this.Context != null) { IList<ModelItem> selectedItems = this.Context.Items.GetValue<Selection>().SelectedObjects.ToList(); foreach (ModelItem selectedAndRemovedItem in selectedItems.Intersect(e.OldItems.Cast<ModelItem>())) { Selection.Toggle(this.Context, selectedAndRemovedItem); } } } if (this.Items.Count > 0) { this.hintTextGrid.Visibility = Visibility.Collapsed; } else { this.hintTextGrid.Visibility = Visibility.Visible; } if (fullRepopulateNeeded) { PopulateContent(); } } protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); this.AllowDrop = true; this.Content = outerGrid; if (this.ItemsPanel != null) { this.panel.ItemsPanel = this.ItemsPanel; } ICompositeViewEvents containerEvents = null; bool isDefault = false; this.Loaded += (s, eventArgs) => { isDefault = this.IsDefaultContainer; selectedSpacerIndex = addAtEndMarker; DependencyObject parent = VisualTreeHelper.GetParent(this); while (null != parent && !typeof(ICompositeViewEvents).IsAssignableFrom(parent.GetType())) { parent = VisualTreeHelper.GetParent(parent); } containerEvents = parent as ICompositeViewEvents; if (null != containerEvents) { if (isDefault) { containerEvents.RegisterDefaultCompositeView(this); } else { containerEvents.RegisterCompositeView(this); } } if (this.Items != null) { //UnRegistering because of 137896: Inside tab control multiple Loaded events happen without an Unloaded event. this.Items.CollectionChanged -= new NotifyCollectionChangedEventHandler(OnCollectionChanged); this.Items.CollectionChanged += new NotifyCollectionChangedEventHandler(OnCollectionChanged); } if (populateOnLoad) { this.PopulateContent(); } }; this.Unloaded += (s, eventArgs) => { if (null != containerEvents) { if (isDefault) { containerEvents.UnregisterDefaultCompositeView(this); } else { containerEvents.UnregisterCompositeView(this); } } if (this.Items != null) { this.Items.CollectionChanged -= new NotifyCollectionChangedEventHandler(OnCollectionChanged); } populateOnLoad = true; }; } void PopulateContent() { this.panel.Items.Clear(); if (this.Items != null) { // index 0 is header. ContentControl header = new ContentControl(); header.Focusable = false; header.ContentTemplate = this.HeaderTemplate; header.SetValue(IndexProperty, 0); header.Drop += new DragEventHandler(OnSpacerDrop); this.panel.Items.Add(header); // index 1 is first spacer FrameworkElement startSpacer = CreateSpacer(); this.panel.Items.Add(startSpacer); foreach (ModelItem item in this.Items) { // index 2 + i*2 is itemView i VirtualizedContainerService containerService = this.Context.Services.GetService<VirtualizedContainerService>(); UIElement itemView = containerService.GetContainer(item, this); this.panel.Items.Add(itemView as UIElement); // index 2 + i*2 + 1 is spacer i+1 FrameworkElement spacer = CreateSpacer(); this.panel.Items.Add(spacer); } // index 2 + count*2 is footer ContentControl footer = new ContentControl(); footer.ContentTemplate = this.FooterTemplate; footer.Focusable = true; footer.IsHitTestVisible = true; footer.IsTabStop = true; footer.SetValue(IndexProperty, addAtEndMarker); footer.Drop += new DragEventHandler(OnSpacerDrop); footer.LostFocus += new RoutedEventHandler(OnSpacerLostFocus); footer.GotFocus += new RoutedEventHandler(OnSpacerGotFocus); this.panel.Items.Add(footer); footer.Focusable = false; } UpdateHintTextVisibility(HintText); } int GetViewIndexForItem(int itemIndex) { return 2 + itemIndex * 2; } int GetViewIndexForSpacer(int spacerIndex) { return 2 + spacerIndex * 2 + 1; } int GetSpacerIndex(int viewIndex) { if (viewIndex == 1) { return 0; } else { return (viewIndex - 3) / 2 + 1; } } void UpdateHintTextVisibility(string hintText) { if (this.hintTextGrid != null && this.Items != null) { this.hintTextGrid.Visibility = (this.Items.Count == 0 && !string.IsNullOrEmpty(hintText)) ? Visibility.Visible : Visibility.Collapsed; } } private IList<object> GetOrderMetaData(List<ModelItem> items) { List<ModelItem> sortedList = this.SortSelectedItems(new List<ModelItem>(items)); this.CheckListConsistentAndThrow(items, sortedList); return sortedList.Select((m) => m.GetCurrentValue()).ToList(); } private FrameworkElement CreateSpacer() { FrameworkElement spacer = (this.SpacerTemplate != null) ? (FrameworkElement)this.SpacerTemplate.LoadContent() : new Rectangle(); spacer.IsHitTestVisible = true; Control spacerControl = spacer as Control; if (spacerControl != null) { spacerControl.IsTabStop = true; } spacer.Drop += new DragEventHandler(OnSpacerDrop); spacer.LostFocus += new RoutedEventHandler(OnSpacerLostFocus); spacer.GotFocus += new RoutedEventHandler(OnSpacerGotFocus); spacer.GotKeyboardFocus += new KeyboardFocusChangedEventHandler(OnSpacerGotKeyboardFocus); spacer.MouseDown += new MouseButtonEventHandler(OnSpacerMouseDown); return spacer; } void OnSpacerDrop(object sender, DragEventArgs e) { int index = GetSpacerIndexFromView(sender); OnItemsDropped(e, index); } private int GetSpacerIndexFromView(object sender) { if (((DependencyObject)sender).ReadLocalValue(IndexProperty) != DependencyProperty.UnsetValue) { int index = (int)((DependencyObject)sender).GetValue(IndexProperty); return index; } else { return GetSpacerIndex(this.panel.Items.IndexOf(sender)); } } void OnSpacerGotFocus(object sender, RoutedEventArgs e) { int index = GetSpacerIndexFromView(sender); selectedSpacerIndex = index; } void OnSpacerGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { // Handle the event so that it won't be routed to the containing designer to affect selection if (handleSpacerGotKeyboardFocus) { e.Handled = true; } } void OnSpacerLostFocus(object sender, RoutedEventArgs e) { int index = GetSpacerIndexFromView(sender); selectedSpacerIndex = addAtEndMarker; } void OnSpacerMouseDown(object sender, MouseButtonEventArgs e) { // do not move focus if it's a ctrl right click. if (e.RightButton == MouseButtonState.Pressed) { if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) { return; } } // Schedule the Keyboard.Focus command to let it execute later than WorkflowViewElement.OnMouseDown this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { this.handleSpacerGotKeyboardFocus = true; Keyboard.Focus((FrameworkElement)sender); this.handleSpacerGotKeyboardFocus = false; })); } private bool ShouldMoveItems(List<ModelItem> sortedModelItems, int index) { if (sortedModelItems.Count == 0) { return false; } // Should move if the items are not next to each other if (!AreItemsConsecutive(sortedModelItems)) { return true; } // Should not move if the new position is just before the first item or just after the last item or between them. return index < this.Items.IndexOf(sortedModelItems[0]) || index > this.Items.IndexOf(sortedModelItems.Last()) + 1; } private bool AreItemsConsecutive(List<ModelItem> sortedModelItems) { Fx.Assert(sortedModelItems.Count > 0, "Should have at least one item."); int oldIndex = this.Items.IndexOf(sortedModelItems[0]); foreach (ModelItem item in sortedModelItems) { if (oldIndex != this.Items.IndexOf(item)) { return false; } oldIndex++; } return true; } public List<ModelItem> SortSelectedItems(List<ModelItem> selectedItems) { if (selectedItems == null) { throw FxTrace.Exception.ArgumentNull("selectedItems"); } if (selectedItems.Count < 2) { return selectedItems; } List<ModelItem> list = new List<ModelItem>(); // If the performance here is bad, we can use HashSet for selectedItems // to improve foreach (ModelItem item in this.Items) { int index = selectedItems.IndexOf(item); if (index >= 0) { // use the reference in selectedItems. list.Add(selectedItems[index]); } } // in case passing some items that are not in // my container. if (list.Count != selectedItems.Count) { // throw FxTrace.Exception. throw FxTrace.Exception.AsError(new ArgumentException(SR.Error_CantFindItemInWIsP)); } return list; } public void OnItemsMoved(List<ModelItem> movedItems) { if (movedItems == null) { throw FxTrace.Exception.ArgumentNull("movedItems"); } DragDropHelper.ValidateItemsAreOnView(movedItems, this.Items); this.OnItemsDelete(movedItems); } void OnItemsDropped(DragEventArgs e, int index) { ModelItemHelper.TryCreateImmediateEditingScopeAndExecute(this.Items.GetEditingContext(), System.Activities.Presentation.SR.CollectionAddEditingScopeDescription, (es) => { DragDropHelper.SetDragDropCompletedEffects(e, DragDropEffects.None); List<object> droppedObjects = new List<object>(DragDropHelper.GetDroppedObjects(this, e, Context)); List<WorkflowViewElement> movedViewElements = new List<WorkflowViewElement>(); List<object> externalMoveList = new List<object>(); List<ModelItem> internalMoveList = new List<ModelItem>(); // Step 1: Sort the list List<object> sortedDroppingList = DragDropHelper.SortSelectedObjects(droppedObjects); // Step 2: Categorize dropped objects by their source container. foreach (object droppedObject in sortedDroppingList) { ModelItem modelItem = droppedObject as ModelItem; WorkflowViewElement view = (modelItem == null) ? null : (modelItem.View as WorkflowViewElement); if (view == null) { externalMoveList.Add(droppedObject); continue; } UIElement container = DragDropHelper.GetCompositeView(view); if (container == this) { internalMoveList.Add(modelItem); continue; } movedViewElements.Add(view); externalMoveList.Add(droppedObject); } // Step 3: Internal movement if (this.ShouldMoveItems(internalMoveList, index)) { foreach (ModelItem modelItem in internalMoveList) { int oldIndex = this.Items.IndexOf(modelItem); this.Items.Remove(modelItem); //if element is placed ahead of old location, decrement the index not to include moved object if (oldIndex < index) { this.InsertItem(index - 1, modelItem); } else { this.InsertItem(index, modelItem); index++; } } } // Step 4: External move and drop from toolbox foreach (object droppedObject in externalMoveList) { if (!this.IsDropAllowed(droppedObject)) { continue; } this.InsertItem(index++, droppedObject); DragDropHelper.SetDragDropCompletedEffects(e, DragDropEffects.Move); } DragDropHelper.SetDragDropMovedViewElements(e, movedViewElements); e.Handled = true; if (es != null) { es.Complete(); } }); } private void CheckListConsistentAndThrow(List<ModelItem> src, List<ModelItem> copied) { bool valid = DragDropHelper.AreListsIdenticalExceptOrder(src, copied); if (!valid) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Error_BadOutputFromSortSelectedItems)); } } private bool IsDropAllowed(object droppedObject) { bool isDropAllowed = false; ModelItem modelItem = droppedObject as ModelItem; if (modelItem != null && !IsInParentChain(modelItem)) { if (this.AllowedItemType.IsAssignableFrom(modelItem.ItemType)) { isDropAllowed = true; } } else if (droppedObject is Type && this.AllowedItemType.IsAssignableFrom((Type)droppedObject)) { isDropAllowed = true; } else { if (this.AllowedItemType.IsAssignableFrom(droppedObject.GetType())) { isDropAllowed = true; } } return isDropAllowed; } private bool IsInParentChain(ModelItem droppedModelItem) { bool isInParentChain = false; ModelItem parentModelItem = this.Items; while (parentModelItem != null) { if (parentModelItem == droppedModelItem) { isInParentChain = true; break; } parentModelItem = parentModelItem.Parent; } return isInParentChain; } void InsertItem(int index, object droppedObject) { ModelItem insertedItem = null; if (index == addAtEndMarker) { insertedItem = this.Items.Add(droppedObject); } else { insertedItem = this.Items.Insert(index, droppedObject); } if (insertedItem != null) { Selection.SelectOnly(this.Context, insertedItem); } } protected override void OnDrop(DragEventArgs e) { int index = addAtEndMarker; WorkflowViewElement dropTarget = null; if (e.OriginalSource is WorkflowViewElement) { dropTarget = (WorkflowViewElement)e.OriginalSource; } else { dropTarget = VisualTreeUtils.FindFocusableParent<WorkflowViewElement>((UIElement)e.OriginalSource); } if (null != dropTarget && null != dropTarget.ModelItem) { int targetIndex = this.Items.IndexOf(dropTarget.ModelItem); if (-1 != targetIndex) { index = targetIndex + 1; } } OnItemsDropped(e, index); base.OnDrop(e); } void OnDrag(DragEventArgs e) { if (!e.Handled) { if (!DragDropHelper.AllowDrop(e.Data, this.Context, this.AllowedItemType)) { e.Effects = DragDropEffects.None; } e.Handled = true; } } protected override void OnDragEnter(DragEventArgs e) { this.OnDrag(e); base.OnDragEnter(e); } protected override void OnDragOver(DragEventArgs e) { this.OnDrag(e); base.OnDragOver(e); } public void OnItemMoved(ModelItem modelItem) { if (this.Items.Contains(modelItem)) { this.Items.Remove(modelItem); } } protected override AutomationPeer OnCreateAutomationPeer() { return new WorkflowItemsPresenterAutomationPeer(this); } public object OnItemsCut(List<ModelItem> itemsToCut) { List<object> orderMetaData = GetOrderMetaData(itemsToCut).ToList(); foreach (ModelItem item in itemsToCut) { this.Items.Remove(item); this.Context.Items.SetValue(new Selection(new ArrayList())); } return orderMetaData; } public object OnItemsCopied(List<ModelItem> itemsToCopy) { return this.GetOrderMetaData(itemsToCopy); } public void OnItemsPasted(List<object> itemsToPaste, List<object> metaData, Point pastePoint, WorkflowViewElement pastePointReference) { // first see if a spacer is selected. int index = this.selectedSpacerIndex; // else see if we can paste after a selected child if (index < 0) { Selection currentSelection = this.Context.Items.GetValue<Selection>(); index = this.Items.IndexOf(currentSelection.PrimarySelection); //paste after the selected child if (index >= 0) { index++; } } if (index < 0) { index = addAtEndMarker; } IList<object> mergedItemsToPaste = CutCopyPasteHelper.SortFromMetaData(itemsToPaste, metaData); List<ModelItem> modelItemsToSelect = new List<ModelItem>(); foreach (object itemToPaste in mergedItemsToPaste) { if (IsDropAllowed(itemToPaste)) { if (index == addAtEndMarker) { modelItemsToSelect.Add(this.Items.Add(itemToPaste)); } else { modelItemsToSelect.Add(this.Items.Insert(index, itemToPaste)); } if (index >= 0) { index++; } } } this.Dispatcher.BeginInvoke( new Action(() => { this.Context.Items.SetValue(new Selection(modelItemsToSelect)); }), Windows.Threading.DispatcherPriority.ApplicationIdle, null); } public void OnItemsDelete(List<ModelItem> itemsToDelete) { if (null != itemsToDelete) { itemsToDelete.ForEach(p => { if (null != this.Items && this.Items.Contains(p)) { this.Items.Remove(p); } } ); } } public bool CanPasteItems(List<object> itemsToPaste) { bool result = false; if (null != itemsToPaste && itemsToPaste.Count > 0) { result = itemsToPaste.All(p => this.IsDropAllowed(p)); } return result; } class WorkflowItemsPresenterAutomationPeer : UIElementAutomationPeer { WorkflowItemsPresenter owner; public WorkflowItemsPresenterAutomationPeer(WorkflowItemsPresenter owner) : base(owner) { this.owner = owner; } protected override AutomationControlType GetAutomationControlTypeCore() { return AutomationControlType.Custom; } protected override string GetAutomationIdCore() { string automationId = base.GetAutomationIdCore(); if (string.IsNullOrEmpty(automationId)) { automationId = base.GetNameCore(); if (string.IsNullOrEmpty(automationId)) { automationId = this.owner.GetType().Name; } } return automationId; } protected override string GetNameCore() { // Return an empty string if some activites are dropped on the presenter if (owner.Items.Count > 0) { return string.Empty; } string name = base.GetNameCore(); if (string.IsNullOrEmpty(name)) { name = this.owner.HintText; } return name; } protected override string GetClassNameCore() { return this.owner.GetType().Name; } } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.Xml { using System; using System.IO; using System.Runtime; using System.Runtime.Serialization; using System.Security; public interface IXmlBinaryReaderInitializer { void SetInput(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose); void SetInput(Stream stream, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose); } class XmlBinaryReader : XmlBaseReader, IXmlBinaryReaderInitializer { bool isTextWithEndElement; bool buffered; ArrayState arrayState; int arrayCount; int maxBytesPerRead; XmlBinaryNodeType arrayNodeType; OnXmlDictionaryReaderClose onClose; public XmlBinaryReader() { } public void SetInput(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose) { if (buffer == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer"); if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.ValueMustBeNonNegative))); if (offset > buffer.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.OffsetExceedsBufferSize, buffer.Length))); if (count < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.ValueMustBeNonNegative))); if (count > buffer.Length - offset) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset))); MoveToInitial(quotas, session, onClose); BufferReader.SetBuffer(buffer, offset, count, dictionary, session); this.buffered = true; } public void SetInput(Stream stream, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose) { if (stream == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream"); MoveToInitial(quotas, session, onClose); BufferReader.SetBuffer(stream, dictionary, session); this.buffered = false; } void MoveToInitial(XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose) { MoveToInitial(quotas); this.maxBytesPerRead = quotas.MaxBytesPerRead; this.arrayState = ArrayState.None; this.onClose = onClose; this.isTextWithEndElement = false; } public override void Close() { base.Close(); OnXmlDictionaryReaderClose onClose = this.onClose; this.onClose = null; if (onClose != null) { try { onClose(this); } catch (Exception e) { if (Fx.IsFatal(e)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } } } public override string ReadElementContentAsString() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (!CanOptimizeReadElementContent()) return base.ReadElementContentAsString(); string value; switch (GetNodeType()) { case XmlBinaryNodeType.Chars8TextWithEndElement: SkipNodeType(); value = BufferReader.ReadUTF8String(ReadUInt8()); ReadTextWithEndElement(); break; case XmlBinaryNodeType.DictionaryTextWithEndElement: SkipNodeType(); value = BufferReader.GetDictionaryString(ReadDictionaryKey()).Value; ReadTextWithEndElement(); break; default: value = base.ReadElementContentAsString(); break; } if (value.Length > Quotas.MaxStringContentLength) XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, Quotas.MaxStringContentLength); return value; } public override bool ReadElementContentAsBoolean() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (!CanOptimizeReadElementContent()) return base.ReadElementContentAsBoolean(); bool value; switch (GetNodeType()) { case XmlBinaryNodeType.TrueTextWithEndElement: SkipNodeType(); value = true; ReadTextWithEndElement(); break; case XmlBinaryNodeType.FalseTextWithEndElement: SkipNodeType(); value = false; ReadTextWithEndElement(); break; case XmlBinaryNodeType.BoolTextWithEndElement: SkipNodeType(); value = (BufferReader.ReadUInt8() != 0); ReadTextWithEndElement(); break; default: value = base.ReadElementContentAsBoolean(); break; } return value; } public override int ReadElementContentAsInt() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (!CanOptimizeReadElementContent()) return base.ReadElementContentAsInt(); int value; switch (GetNodeType()) { case XmlBinaryNodeType.ZeroTextWithEndElement: SkipNodeType(); value = 0; ReadTextWithEndElement(); break; case XmlBinaryNodeType.OneTextWithEndElement: SkipNodeType(); value = 1; ReadTextWithEndElement(); break; case XmlBinaryNodeType.Int8TextWithEndElement: SkipNodeType(); value = BufferReader.ReadInt8(); ReadTextWithEndElement(); break; case XmlBinaryNodeType.Int16TextWithEndElement: SkipNodeType(); value = BufferReader.ReadInt16(); ReadTextWithEndElement(); break; case XmlBinaryNodeType.Int32TextWithEndElement: SkipNodeType(); value = BufferReader.ReadInt32(); ReadTextWithEndElement(); break; default: value = base.ReadElementContentAsInt(); break; } return value; } bool CanOptimizeReadElementContent() { return (arrayState == ArrayState.None && !Signing); } public override float ReadElementContentAsFloat() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.FloatTextWithEndElement) { SkipNodeType(); float value = BufferReader.ReadSingle(); ReadTextWithEndElement(); return value; } return base.ReadElementContentAsFloat(); } public override double ReadElementContentAsDouble() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.DoubleTextWithEndElement) { SkipNodeType(); double value = BufferReader.ReadDouble(); ReadTextWithEndElement(); return value; } return base.ReadElementContentAsDouble(); } public override decimal ReadElementContentAsDecimal() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.DecimalTextWithEndElement) { SkipNodeType(); decimal value = BufferReader.ReadDecimal(); ReadTextWithEndElement(); return value; } return base.ReadElementContentAsDecimal(); } public override DateTime ReadElementContentAsDateTime() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.DateTimeTextWithEndElement) { SkipNodeType(); DateTime value = BufferReader.ReadDateTime(); ReadTextWithEndElement(); return value; } return base.ReadElementContentAsDateTime(); } public override TimeSpan ReadElementContentAsTimeSpan() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.TimeSpanTextWithEndElement) { SkipNodeType(); TimeSpan value = BufferReader.ReadTimeSpan(); ReadTextWithEndElement(); return value; } return base.ReadElementContentAsTimeSpan(); } public override Guid ReadElementContentAsGuid() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.GuidTextWithEndElement) { SkipNodeType(); Guid value = BufferReader.ReadGuid(); ReadTextWithEndElement(); return value; } return base.ReadElementContentAsGuid(); } public override UniqueId ReadElementContentAsUniqueId() { if (this.Node.NodeType != XmlNodeType.Element) MoveToStartElement(); if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.UniqueIdTextWithEndElement) { SkipNodeType(); UniqueId value = BufferReader.ReadUniqueId(); ReadTextWithEndElement(); return value; } return base.ReadElementContentAsUniqueId(); } public override bool TryGetBase64ContentLength(out int length) { length = 0; if (!buffered) return false; if (arrayState != ArrayState.None) return false; int totalLength; if (!this.Node.Value.TryGetByteArrayLength(out totalLength)) return false; int offset = BufferReader.Offset; try { bool done = false; while (!done && !BufferReader.EndOfFile) { XmlBinaryNodeType nodeType = GetNodeType(); SkipNodeType(); int actual; switch (nodeType) { case XmlBinaryNodeType.Bytes8TextWithEndElement: actual = BufferReader.ReadUInt8(); done = true; break; case XmlBinaryNodeType.Bytes16TextWithEndElement: actual = BufferReader.ReadUInt16(); done = true; break; case XmlBinaryNodeType.Bytes32TextWithEndElement: actual = BufferReader.ReadUInt31(); done = true; break; case XmlBinaryNodeType.EndElement: actual = 0; done = true; break; case XmlBinaryNodeType.Bytes8Text: actual = BufferReader.ReadUInt8(); break; case XmlBinaryNodeType.Bytes16Text: actual = BufferReader.ReadUInt16(); break; case XmlBinaryNodeType.Bytes32Text: actual = BufferReader.ReadUInt31(); break; default: // Non-optimal or unexpected node - fallback return false; } BufferReader.Advance(actual); if (totalLength > int.MaxValue - actual) return false; totalLength += actual; } length = totalLength; return true; } finally { BufferReader.Offset = offset; } } void ReadTextWithEndElement() { ExitScope(); ReadNode(); } XmlAtomicTextNode MoveToAtomicTextWithEndElement() { isTextWithEndElement = true; return MoveToAtomicText(); } public override bool Read() { if (this.Node.ReadState == ReadState.Closed) return false; SignNode(); if (isTextWithEndElement) { isTextWithEndElement = false; MoveToEndElement(); return true; } if (arrayState == ArrayState.Content) { if (arrayCount != 0) { MoveToArrayElement(); return true; } arrayState = ArrayState.None; } if (this.Node.ExitScope) { ExitScope(); } return ReadNode(); } bool ReadNode() { if (!buffered) BufferReader.SetWindow(ElementNode.BufferOffset, this.maxBytesPerRead); if (BufferReader.EndOfFile) { MoveToEndOfFile(); return false; } XmlBinaryNodeType nodeType; if (arrayState == ArrayState.None) { nodeType = GetNodeType(); SkipNodeType(); } else { Fx.Assert(arrayState == ArrayState.Element, ""); nodeType = arrayNodeType; arrayCount--; arrayState = ArrayState.Content; } XmlElementNode elementNode; PrefixHandleType prefix; switch (nodeType) { case XmlBinaryNodeType.ShortElement: elementNode = EnterScope(); elementNode.Prefix.SetValue(PrefixHandleType.Empty); ReadName(elementNode.LocalName); ReadAttributes(); elementNode.Namespace = LookupNamespace(PrefixHandleType.Empty); elementNode.BufferOffset = BufferReader.Offset; return true; case XmlBinaryNodeType.Element: elementNode = EnterScope(); ReadName(elementNode.Prefix); ReadName(elementNode.LocalName); ReadAttributes(); elementNode.Namespace = LookupNamespace(elementNode.Prefix); elementNode.BufferOffset = BufferReader.Offset; return true; case XmlBinaryNodeType.ShortDictionaryElement: elementNode = EnterScope(); elementNode.Prefix.SetValue(PrefixHandleType.Empty); ReadDictionaryName(elementNode.LocalName); ReadAttributes(); elementNode.Namespace = LookupNamespace(PrefixHandleType.Empty); elementNode.BufferOffset = BufferReader.Offset; return true; case XmlBinaryNodeType.DictionaryElement: elementNode = EnterScope(); ReadName(elementNode.Prefix); ReadDictionaryName(elementNode.LocalName); ReadAttributes(); elementNode.Namespace = LookupNamespace(elementNode.Prefix); elementNode.BufferOffset = BufferReader.Offset; return true; case XmlBinaryNodeType.PrefixElementA: case XmlBinaryNodeType.PrefixElementB: case XmlBinaryNodeType.PrefixElementC: case XmlBinaryNodeType.PrefixElementD: case XmlBinaryNodeType.PrefixElementE: case XmlBinaryNodeType.PrefixElementF: case XmlBinaryNodeType.PrefixElementG: case XmlBinaryNodeType.PrefixElementH: case XmlBinaryNodeType.PrefixElementI: case XmlBinaryNodeType.PrefixElementJ: case XmlBinaryNodeType.PrefixElementK: case XmlBinaryNodeType.PrefixElementL: case XmlBinaryNodeType.PrefixElementM: case XmlBinaryNodeType.PrefixElementN: case XmlBinaryNodeType.PrefixElementO: case XmlBinaryNodeType.PrefixElementP: case XmlBinaryNodeType.PrefixElementQ: case XmlBinaryNodeType.PrefixElementR: case XmlBinaryNodeType.PrefixElementS: case XmlBinaryNodeType.PrefixElementT: case XmlBinaryNodeType.PrefixElementU: case XmlBinaryNodeType.PrefixElementV: case XmlBinaryNodeType.PrefixElementW: case XmlBinaryNodeType.PrefixElementX: case XmlBinaryNodeType.PrefixElementY: case XmlBinaryNodeType.PrefixElementZ: elementNode = EnterScope(); prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixElementA); elementNode.Prefix.SetValue(prefix); ReadName(elementNode.LocalName); ReadAttributes(); elementNode.Namespace = LookupNamespace(prefix); elementNode.BufferOffset = BufferReader.Offset; return true; case XmlBinaryNodeType.PrefixDictionaryElementA: case XmlBinaryNodeType.PrefixDictionaryElementB: case XmlBinaryNodeType.PrefixDictionaryElementC: case XmlBinaryNodeType.PrefixDictionaryElementD: case XmlBinaryNodeType.PrefixDictionaryElementE: case XmlBinaryNodeType.PrefixDictionaryElementF: case XmlBinaryNodeType.PrefixDictionaryElementG: case XmlBinaryNodeType.PrefixDictionaryElementH: case XmlBinaryNodeType.PrefixDictionaryElementI: case XmlBinaryNodeType.PrefixDictionaryElementJ: case XmlBinaryNodeType.PrefixDictionaryElementK: case XmlBinaryNodeType.PrefixDictionaryElementL: case XmlBinaryNodeType.PrefixDictionaryElementM: case XmlBinaryNodeType.PrefixDictionaryElementN: case XmlBinaryNodeType.PrefixDictionaryElementO: case XmlBinaryNodeType.PrefixDictionaryElementP: case XmlBinaryNodeType.PrefixDictionaryElementQ: case XmlBinaryNodeType.PrefixDictionaryElementR: case XmlBinaryNodeType.PrefixDictionaryElementS: case XmlBinaryNodeType.PrefixDictionaryElementT: case XmlBinaryNodeType.PrefixDictionaryElementU: case XmlBinaryNodeType.PrefixDictionaryElementV: case XmlBinaryNodeType.PrefixDictionaryElementW: case XmlBinaryNodeType.PrefixDictionaryElementX: case XmlBinaryNodeType.PrefixDictionaryElementY: case XmlBinaryNodeType.PrefixDictionaryElementZ: elementNode = EnterScope(); prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixDictionaryElementA); elementNode.Prefix.SetValue(prefix); ReadDictionaryName(elementNode.LocalName); ReadAttributes(); elementNode.Namespace = LookupNamespace(prefix); elementNode.BufferOffset = BufferReader.Offset; return true; case XmlBinaryNodeType.EndElement: MoveToEndElement(); return true; case XmlBinaryNodeType.Comment: ReadName(MoveToComment().Value); return true; case XmlBinaryNodeType.EmptyTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.Empty); if (this.OutsideRootElement) VerifyWhitespace(); return true; case XmlBinaryNodeType.ZeroTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.Zero); if (this.OutsideRootElement) VerifyWhitespace(); return true; case XmlBinaryNodeType.OneTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.One); if (this.OutsideRootElement) VerifyWhitespace(); return true; case XmlBinaryNodeType.TrueTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.True); if (this.OutsideRootElement) VerifyWhitespace(); return true; case XmlBinaryNodeType.FalseTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.False); if (this.OutsideRootElement) VerifyWhitespace(); return true; case XmlBinaryNodeType.BoolTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ReadUInt8() != 0 ? ValueHandleType.True : ValueHandleType.False); if (this.OutsideRootElement) VerifyWhitespace(); return true; case XmlBinaryNodeType.Chars8TextWithEndElement: if (buffered) ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, ReadUInt8()); else ReadPartialUTF8Text(true, ReadUInt8()); return true; case XmlBinaryNodeType.Chars8Text: if (buffered) ReadText(MoveToComplexText(), ValueHandleType.UTF8, ReadUInt8()); else ReadPartialUTF8Text(false, ReadUInt8()); return true; case XmlBinaryNodeType.Chars16TextWithEndElement: if (buffered) ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, ReadUInt16()); else ReadPartialUTF8Text(true, ReadUInt16()); return true; case XmlBinaryNodeType.Chars16Text: if (buffered) ReadText(MoveToComplexText(), ValueHandleType.UTF8, ReadUInt16()); else ReadPartialUTF8Text(false, ReadUInt16()); return true; case XmlBinaryNodeType.Chars32TextWithEndElement: if (buffered) ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, ReadUInt31()); else ReadPartialUTF8Text(true, ReadUInt31()); return true; case XmlBinaryNodeType.Chars32Text: if (buffered) ReadText(MoveToComplexText(), ValueHandleType.UTF8, ReadUInt31()); else ReadPartialUTF8Text(false, ReadUInt31()); return true; case XmlBinaryNodeType.UnicodeChars8TextWithEndElement: ReadUnicodeText(true, ReadUInt8()); return true; case XmlBinaryNodeType.UnicodeChars8Text: ReadUnicodeText(false, ReadUInt8()); return true; case XmlBinaryNodeType.UnicodeChars16TextWithEndElement: ReadUnicodeText(true, ReadUInt16()); return true; case XmlBinaryNodeType.UnicodeChars16Text: ReadUnicodeText(false, ReadUInt16()); return true; case XmlBinaryNodeType.UnicodeChars32TextWithEndElement: ReadUnicodeText(true, ReadUInt31()); return true; case XmlBinaryNodeType.UnicodeChars32Text: ReadUnicodeText(false, ReadUInt31()); return true; case XmlBinaryNodeType.Bytes8TextWithEndElement: if (buffered) ReadBinaryText(MoveToAtomicTextWithEndElement(), ReadUInt8()); else ReadPartialBinaryText(true, ReadUInt8()); return true; case XmlBinaryNodeType.Bytes8Text: if (buffered) ReadBinaryText(MoveToComplexText(), ReadUInt8()); else ReadPartialBinaryText(false, ReadUInt8()); return true; case XmlBinaryNodeType.Bytes16TextWithEndElement: if (buffered) ReadBinaryText(MoveToAtomicTextWithEndElement(), ReadUInt16()); else ReadPartialBinaryText(true, ReadUInt16()); return true; case XmlBinaryNodeType.Bytes16Text: if (buffered) ReadBinaryText(MoveToComplexText(), ReadUInt16()); else ReadPartialBinaryText(false, ReadUInt16()); return true; case XmlBinaryNodeType.Bytes32TextWithEndElement: if (buffered) ReadBinaryText(MoveToAtomicTextWithEndElement(), ReadUInt31()); else ReadPartialBinaryText(true, ReadUInt31()); return true; case XmlBinaryNodeType.Bytes32Text: if (buffered) ReadBinaryText(MoveToComplexText(), ReadUInt31()); else ReadPartialBinaryText(false, ReadUInt31()); return true; case XmlBinaryNodeType.DictionaryTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetDictionaryValue(ReadDictionaryKey()); return true; case XmlBinaryNodeType.UniqueIdTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UniqueId, ValueHandleLength.UniqueId); return true; case XmlBinaryNodeType.GuidTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Guid, ValueHandleLength.Guid); return true; case XmlBinaryNodeType.DecimalTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Decimal, ValueHandleLength.Decimal); return true; case XmlBinaryNodeType.Int8TextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int8, ValueHandleLength.Int8); return true; case XmlBinaryNodeType.Int16TextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int16, ValueHandleLength.Int16); return true; case XmlBinaryNodeType.Int32TextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int32, ValueHandleLength.Int32); return true; case XmlBinaryNodeType.Int64TextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int64, ValueHandleLength.Int64); return true; case XmlBinaryNodeType.UInt64TextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UInt64, ValueHandleLength.UInt64); return true; case XmlBinaryNodeType.FloatTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Single, ValueHandleLength.Single); return true; case XmlBinaryNodeType.DoubleTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Double, ValueHandleLength.Double); return true; case XmlBinaryNodeType.TimeSpanTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.TimeSpan, ValueHandleLength.TimeSpan); return true; case XmlBinaryNodeType.DateTimeTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.DateTime, ValueHandleLength.DateTime); return true; case XmlBinaryNodeType.QNameDictionaryTextWithEndElement: BufferReader.ReadQName(MoveToAtomicTextWithEndElement().Value); return true; case XmlBinaryNodeType.Array: ReadArray(); return true; default: BufferReader.ReadValue(nodeType, MoveToComplexText().Value); return true; } } void VerifyWhitespace() { if (!this.Node.Value.IsWhitespace()) XmlExceptionHelper.ThrowInvalidBinaryFormat(this); } void ReadAttributes() { XmlBinaryNodeType nodeType = GetNodeType(); if (nodeType < XmlBinaryNodeType.MinAttribute || nodeType > XmlBinaryNodeType.MaxAttribute) return; ReadAttributes2(); } void ReadAttributes2() { int startOffset = 0; if (buffered) startOffset = BufferReader.Offset; while (true) { XmlAttributeNode attributeNode; Namespace nameSpace; PrefixHandleType prefix; XmlBinaryNodeType nodeType = GetNodeType(); switch (nodeType) { case XmlBinaryNodeType.ShortAttribute: SkipNodeType(); attributeNode = AddAttribute(); attributeNode.Prefix.SetValue(PrefixHandleType.Empty); ReadName(attributeNode.LocalName); ReadAttributeText(attributeNode.AttributeText); break; case XmlBinaryNodeType.Attribute: SkipNodeType(); attributeNode = AddAttribute(); ReadName(attributeNode.Prefix); ReadName(attributeNode.LocalName); ReadAttributeText(attributeNode.AttributeText); FixXmlAttribute(attributeNode); break; case XmlBinaryNodeType.ShortDictionaryAttribute: SkipNodeType(); attributeNode = AddAttribute(); attributeNode.Prefix.SetValue(PrefixHandleType.Empty); ReadDictionaryName(attributeNode.LocalName); ReadAttributeText(attributeNode.AttributeText); break; case XmlBinaryNodeType.DictionaryAttribute: SkipNodeType(); attributeNode = AddAttribute(); ReadName(attributeNode.Prefix); ReadDictionaryName(attributeNode.LocalName); ReadAttributeText(attributeNode.AttributeText); break; case XmlBinaryNodeType.XmlnsAttribute: SkipNodeType(); nameSpace = AddNamespace(); ReadName(nameSpace.Prefix); ReadName(nameSpace.Uri); attributeNode = AddXmlnsAttribute(nameSpace); break; case XmlBinaryNodeType.ShortXmlnsAttribute: SkipNodeType(); nameSpace = AddNamespace(); nameSpace.Prefix.SetValue(PrefixHandleType.Empty); ReadName(nameSpace.Uri); attributeNode = AddXmlnsAttribute(nameSpace); break; case XmlBinaryNodeType.ShortDictionaryXmlnsAttribute: SkipNodeType(); nameSpace = AddNamespace(); nameSpace.Prefix.SetValue(PrefixHandleType.Empty); ReadDictionaryName(nameSpace.Uri); attributeNode = AddXmlnsAttribute(nameSpace); break; case XmlBinaryNodeType.DictionaryXmlnsAttribute: SkipNodeType(); nameSpace = AddNamespace(); ReadName(nameSpace.Prefix); ReadDictionaryName(nameSpace.Uri); attributeNode = AddXmlnsAttribute(nameSpace); break; case XmlBinaryNodeType.PrefixDictionaryAttributeA: case XmlBinaryNodeType.PrefixDictionaryAttributeB: case XmlBinaryNodeType.PrefixDictionaryAttributeC: case XmlBinaryNodeType.PrefixDictionaryAttributeD: case XmlBinaryNodeType.PrefixDictionaryAttributeE: case XmlBinaryNodeType.PrefixDictionaryAttributeF: case XmlBinaryNodeType.PrefixDictionaryAttributeG: case XmlBinaryNodeType.PrefixDictionaryAttributeH: case XmlBinaryNodeType.PrefixDictionaryAttributeI: case XmlBinaryNodeType.PrefixDictionaryAttributeJ: case XmlBinaryNodeType.PrefixDictionaryAttributeK: case XmlBinaryNodeType.PrefixDictionaryAttributeL: case XmlBinaryNodeType.PrefixDictionaryAttributeM: case XmlBinaryNodeType.PrefixDictionaryAttributeN: case XmlBinaryNodeType.PrefixDictionaryAttributeO: case XmlBinaryNodeType.PrefixDictionaryAttributeP: case XmlBinaryNodeType.PrefixDictionaryAttributeQ: case XmlBinaryNodeType.PrefixDictionaryAttributeR: case XmlBinaryNodeType.PrefixDictionaryAttributeS: case XmlBinaryNodeType.PrefixDictionaryAttributeT: case XmlBinaryNodeType.PrefixDictionaryAttributeU: case XmlBinaryNodeType.PrefixDictionaryAttributeV: case XmlBinaryNodeType.PrefixDictionaryAttributeW: case XmlBinaryNodeType.PrefixDictionaryAttributeX: case XmlBinaryNodeType.PrefixDictionaryAttributeY: case XmlBinaryNodeType.PrefixDictionaryAttributeZ: SkipNodeType(); attributeNode = AddAttribute(); prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixDictionaryAttributeA); attributeNode.Prefix.SetValue(prefix); ReadDictionaryName(attributeNode.LocalName); ReadAttributeText(attributeNode.AttributeText); break; case XmlBinaryNodeType.PrefixAttributeA: case XmlBinaryNodeType.PrefixAttributeB: case XmlBinaryNodeType.PrefixAttributeC: case XmlBinaryNodeType.PrefixAttributeD: case XmlBinaryNodeType.PrefixAttributeE: case XmlBinaryNodeType.PrefixAttributeF: case XmlBinaryNodeType.PrefixAttributeG: case XmlBinaryNodeType.PrefixAttributeH: case XmlBinaryNodeType.PrefixAttributeI: case XmlBinaryNodeType.PrefixAttributeJ: case XmlBinaryNodeType.PrefixAttributeK: case XmlBinaryNodeType.PrefixAttributeL: case XmlBinaryNodeType.PrefixAttributeM: case XmlBinaryNodeType.PrefixAttributeN: case XmlBinaryNodeType.PrefixAttributeO: case XmlBinaryNodeType.PrefixAttributeP: case XmlBinaryNodeType.PrefixAttributeQ: case XmlBinaryNodeType.PrefixAttributeR: case XmlBinaryNodeType.PrefixAttributeS: case XmlBinaryNodeType.PrefixAttributeT: case XmlBinaryNodeType.PrefixAttributeU: case XmlBinaryNodeType.PrefixAttributeV: case XmlBinaryNodeType.PrefixAttributeW: case XmlBinaryNodeType.PrefixAttributeX: case XmlBinaryNodeType.PrefixAttributeY: case XmlBinaryNodeType.PrefixAttributeZ: SkipNodeType(); attributeNode = AddAttribute(); prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixAttributeA); attributeNode.Prefix.SetValue(prefix); ReadName(attributeNode.LocalName); ReadAttributeText(attributeNode.AttributeText); break; default: if (buffered && (BufferReader.Offset - startOffset) > this.maxBytesPerRead) XmlExceptionHelper.ThrowMaxBytesPerReadExceeded(this, this.maxBytesPerRead); ProcessAttributes(); return; } } } void ReadText(XmlTextNode textNode, ValueHandleType type, int length) { int offset = BufferReader.ReadBytes(length); textNode.Value.SetValue(type, offset, length); if (this.OutsideRootElement) VerifyWhitespace(); } void ReadBinaryText(XmlTextNode textNode, int length) { ReadText(textNode, ValueHandleType.Base64, length); } void ReadPartialUTF8Text(bool withEndElement, int length) { // The maxBytesPerRead includes the quota for the XmlBinaryNodeType.TextNode, so we need // to account for that. const int maxTextNodeLength = 5; int maxLength = Math.Max(this.maxBytesPerRead - maxTextNodeLength, 0); if (length <= maxLength) { if (withEndElement) ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, length); else ReadText(MoveToComplexText(), ValueHandleType.UTF8, length); } else { // We also need to make sure we have enough room to insert a new XmlBinaryNodeType.TextNode // for the split data. int actual = Math.Max(maxLength - maxTextNodeLength, 0); int offset = BufferReader.ReadBytes(actual); // We need to make sure we don't split a utf8 character, so scan backwards for a // character boundary. We'll actually always push off at least one character since // although we find the character boundary, we don't bother to figure out if we have // all the bytes that comprise the character. int i; for (i = offset + actual - 1; i >= offset; i--) { byte b = BufferReader.GetByte(i); // The first byte of UTF8 character sequence has either the high bit off, or the // two high bits set. if ((b & 0x80) == 0 || (b & 0xC0) == 0xC0) break; } // Move any split characters so we can insert the node int byteCount = (offset + actual - i); // Include the split characters in the count BufferReader.Offset = BufferReader.Offset - byteCount; actual -= byteCount; MoveToComplexText().Value.SetValue(ValueHandleType.UTF8, offset, actual); if (this.OutsideRootElement) VerifyWhitespace(); XmlBinaryNodeType nodeType = (withEndElement ? XmlBinaryNodeType.Chars32TextWithEndElement : XmlBinaryNodeType.Chars32Text); InsertNode(nodeType, length - actual); } } void ReadUnicodeText(bool withEndElement, int length) { if ((length & 1) != 0) XmlExceptionHelper.ThrowInvalidBinaryFormat(this); if (buffered) { if (withEndElement) { ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Unicode, length); } else { ReadText(MoveToComplexText(), ValueHandleType.Unicode, length); } } else { ReadPartialUnicodeText(withEndElement, length); } } void ReadPartialUnicodeText(bool withEndElement, int length) { // The maxBytesPerRead includes the quota for the XmlBinaryNodeType.TextNode, so we need // to account for that. const int maxTextNodeLength = 5; int maxLength = Math.Max(this.maxBytesPerRead - maxTextNodeLength, 0); if (length <= maxLength) { if (withEndElement) ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Unicode, length); else ReadText(MoveToComplexText(), ValueHandleType.Unicode, length); } else { // We also need to make sure we have enough room to insert a new XmlBinaryNodeType.TextNode // for the split data. int actual = Math.Max(maxLength - maxTextNodeLength, 0); // Make sure we break on a char boundary if ((actual & 1) != 0) actual--; int offset = BufferReader.ReadBytes(actual); // We need to make sure we don't split a unicode surrogate character int byteCount = 0; char ch = (char)BufferReader.GetInt16(offset + actual - sizeof(char)); // If the last char is a high surrogate char, then move back if (ch >= 0xD800 && ch < 0xDC00) byteCount = sizeof(char); // Include the split characters in the count BufferReader.Offset = BufferReader.Offset - byteCount; actual -= byteCount; MoveToComplexText().Value.SetValue(ValueHandleType.Unicode, offset, actual); if (this.OutsideRootElement) VerifyWhitespace(); XmlBinaryNodeType nodeType = (withEndElement ? XmlBinaryNodeType.UnicodeChars32TextWithEndElement : XmlBinaryNodeType.UnicodeChars32Text); InsertNode(nodeType, length - actual); } } void ReadPartialBinaryText(bool withEndElement, int length) { const int nodeLength = 5; int maxBytesPerRead = Math.Max(this.maxBytesPerRead - nodeLength, 0); if (length <= maxBytesPerRead) { if (withEndElement) ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Base64, length); else ReadText(MoveToComplexText(), ValueHandleType.Base64, length); } else { int actual = maxBytesPerRead; if (actual > 3) actual -= (actual % 3); ReadText(MoveToComplexText(), ValueHandleType.Base64, actual); XmlBinaryNodeType nodeType = (withEndElement ? XmlBinaryNodeType.Bytes32TextWithEndElement : XmlBinaryNodeType.Bytes32Text); InsertNode(nodeType, length - actual); } } void InsertNode(XmlBinaryNodeType nodeType, int length) { byte[] buffer = new byte[5]; buffer[0] = (byte)nodeType; buffer[1] = (byte)length; length >>= 8; buffer[2] = (byte)length; length >>= 8; buffer[3] = (byte)length; length >>= 8; buffer[4] = (byte)length; BufferReader.InsertBytes(buffer, 0, buffer.Length); } void ReadAttributeText(XmlAttributeTextNode textNode) { XmlBinaryNodeType nodeType = GetNodeType(); SkipNodeType(); BufferReader.ReadValue(nodeType, textNode.Value); } void ReadName(ValueHandle value) { int length = ReadMultiByteUInt31(); int offset = BufferReader.ReadBytes(length); value.SetValue(ValueHandleType.UTF8, offset, length); } void ReadName(StringHandle handle) { int length = ReadMultiByteUInt31(); int offset = BufferReader.ReadBytes(length); handle.SetValue(offset, length); } void ReadName(PrefixHandle prefix) { int length = ReadMultiByteUInt31(); int offset = BufferReader.ReadBytes(length); prefix.SetValue(offset, length); } void ReadDictionaryName(StringHandle s) { int key = ReadDictionaryKey(); s.SetValue(key); } XmlBinaryNodeType GetNodeType() { return BufferReader.GetNodeType(); } void SkipNodeType() { BufferReader.SkipNodeType(); } int ReadDictionaryKey() { return BufferReader.ReadDictionaryKey(); } int ReadMultiByteUInt31() { return BufferReader.ReadMultiByteUInt31(); } int ReadUInt8() { return BufferReader.ReadUInt8(); } int ReadUInt16() { return BufferReader.ReadUInt16(); } int ReadUInt31() { return BufferReader.ReadUInt31(); } bool IsValidArrayType(XmlBinaryNodeType nodeType) { switch (nodeType) { case XmlBinaryNodeType.BoolTextWithEndElement: case XmlBinaryNodeType.Int16TextWithEndElement: case XmlBinaryNodeType.Int32TextWithEndElement: case XmlBinaryNodeType.Int64TextWithEndElement: case XmlBinaryNodeType.FloatTextWithEndElement: case XmlBinaryNodeType.DoubleTextWithEndElement: case XmlBinaryNodeType.DecimalTextWithEndElement: case XmlBinaryNodeType.DateTimeTextWithEndElement: case XmlBinaryNodeType.TimeSpanTextWithEndElement: case XmlBinaryNodeType.GuidTextWithEndElement: return true; default: return false; } } void ReadArray() { if (GetNodeType() == XmlBinaryNodeType.Array) // Prevent recursion XmlExceptionHelper.ThrowInvalidBinaryFormat(this); ReadNode(); // ReadStartElement if (this.Node.NodeType != XmlNodeType.Element) XmlExceptionHelper.ThrowInvalidBinaryFormat(this); if (GetNodeType() == XmlBinaryNodeType.Array) // Prevent recursion XmlExceptionHelper.ThrowInvalidBinaryFormat(this); ReadNode(); // ReadEndElement if (this.Node.NodeType != XmlNodeType.EndElement) XmlExceptionHelper.ThrowInvalidBinaryFormat(this); arrayState = ArrayState.Element; arrayNodeType = GetNodeType(); if (!IsValidArrayType(arrayNodeType)) XmlExceptionHelper.ThrowInvalidBinaryFormat(this); SkipNodeType(); arrayCount = ReadMultiByteUInt31(); if (arrayCount == 0) XmlExceptionHelper.ThrowInvalidBinaryFormat(this); MoveToArrayElement(); } void MoveToArrayElement() { arrayState = ArrayState.Element; MoveToNode(ElementNode); } void SkipArrayElements(int count) { arrayCount -= count; if (arrayCount == 0) { arrayState = ArrayState.None; ExitScope(); ReadNode(); } } public override bool IsStartArray(out Type type) { type = null; if (arrayState != ArrayState.Element) return false; switch (arrayNodeType) { case XmlBinaryNodeType.BoolTextWithEndElement: type = typeof(bool); break; case XmlBinaryNodeType.Int16TextWithEndElement: type = typeof(Int16); break; case XmlBinaryNodeType.Int32TextWithEndElement: type = typeof(Int32); break; case XmlBinaryNodeType.Int64TextWithEndElement: type = typeof(Int64); break; case XmlBinaryNodeType.FloatTextWithEndElement: type = typeof(float); break; case XmlBinaryNodeType.DoubleTextWithEndElement: type = typeof(double); break; case XmlBinaryNodeType.DecimalTextWithEndElement: type = typeof(decimal); break; case XmlBinaryNodeType.DateTimeTextWithEndElement: type = typeof(DateTime); break; case XmlBinaryNodeType.GuidTextWithEndElement: type = typeof(Guid); break; case XmlBinaryNodeType.TimeSpanTextWithEndElement: type = typeof(TimeSpan); break; case XmlBinaryNodeType.UniqueIdTextWithEndElement: type = typeof(UniqueId); break; default: return false; } return true; } public override bool TryGetArrayLength(out int count) { count = 0; if (!buffered) return false; if (arrayState != ArrayState.Element) return false; count = arrayCount; return true; } bool IsStartArray(string localName, string namespaceUri, XmlBinaryNodeType nodeType) { return IsStartElement(localName, namespaceUri) && arrayState == ArrayState.Element && arrayNodeType == nodeType && !Signing; } bool IsStartArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, XmlBinaryNodeType nodeType) { return IsStartElement(localName, namespaceUri) && arrayState == ArrayState.Element && arrayNodeType == nodeType && !Signing; } void CheckArray(Array array, int offset, int count) { if (array == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("array")); if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.ValueMustBeNonNegative))); if (offset > array.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.OffsetExceedsBufferSize, array.Length))); if (count < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.ValueMustBeNonNegative))); if (count > array.Length - offset) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.SizeExceedsRemainingBufferSpace, array.Length - offset))); } // bool [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe int ReadArray(bool[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, arrayCount); fixed (bool* items = &array[offset]) { BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, bool[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.BoolTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.BoolTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } // Int16 [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe int ReadArray(Int16[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, arrayCount); fixed (Int16* items = &array[offset]) { BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, Int16[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int16TextWithEndElement) && BitConverter.IsLittleEndian) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int16[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int16TextWithEndElement) && BitConverter.IsLittleEndian) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } // Int32 [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe int ReadArray(Int32[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, arrayCount); fixed (Int32* items = &array[offset]) { BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, Int32[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int32TextWithEndElement) && BitConverter.IsLittleEndian) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int32[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int32TextWithEndElement) && BitConverter.IsLittleEndian) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } // Int64 [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe int ReadArray(Int64[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, arrayCount); fixed (Int64* items = &array[offset]) { BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, Int64[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int64TextWithEndElement) && BitConverter.IsLittleEndian) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int64[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int64TextWithEndElement) && BitConverter.IsLittleEndian) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } // float [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe int ReadArray(float[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, arrayCount); fixed (float* items = &array[offset]) { BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, float[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.FloatTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.FloatTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } // double [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe int ReadArray(double[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, arrayCount); fixed (double* items = &array[offset]) { BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, double[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DoubleTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DoubleTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } // decimal [Fx.Tag.SecurityNote(Critical = "Contains unsafe code.", Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")] [SecuritySafeCritical] unsafe int ReadArray(decimal[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, arrayCount); fixed (decimal* items = &array[offset]) { BufferReader.UnsafeReadArray((byte*)items, (byte*)&items[actual]); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, decimal[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DecimalTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DecimalTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } // DateTime int ReadArray(DateTime[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, arrayCount); for (int i = 0; i < actual; i++) { array[offset + i] = BufferReader.ReadDateTime(); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, DateTime[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DateTimeTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DateTimeTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } // Guid int ReadArray(Guid[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, arrayCount); for (int i = 0; i < actual; i++) { array[offset + i] = BufferReader.ReadGuid(); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, Guid[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.GuidTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.GuidTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } // TimeSpan int ReadArray(TimeSpan[] array, int offset, int count) { CheckArray(array, offset, count); int actual = Math.Min(count, arrayCount); for (int i = 0; i < actual; i++) { array[offset + i] = BufferReader.ReadTimeSpan(); } SkipArrayElements(actual); return actual; } public override int ReadArray(string localName, string namespaceUri, TimeSpan[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.TimeSpanTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.TimeSpanTextWithEndElement)) return ReadArray(array, offset, count); return base.ReadArray(localName, namespaceUri, array, offset, count); } enum ArrayState { None, Element, Content } protected override XmlSigningNodeWriter CreateSigningNodeWriter() { return new XmlSigningNodeWriter(false); } } }
// dnlib: See LICENSE.txt for more info using System; using System.Collections.Generic; using System.Threading; using dnlib.DotNet.MD; namespace dnlib.DotNet { /// <summary> /// A high-level representation of a row in the MemberRef table /// </summary> public abstract class MemberRef : IHasCustomAttribute, IMethodDefOrRef, ICustomAttributeType, IField, IContainsGenericParameter { /// <summary> /// The row id in its table /// </summary> protected uint rid; /// <summary> /// The owner module /// </summary> protected ModuleDef module; /// <inheritdoc/> public MDToken MDToken { get { return new MDToken(Table.MemberRef, rid); } } /// <inheritdoc/> public uint Rid { get { return rid; } set { rid = value; } } /// <inheritdoc/> public int HasCustomAttributeTag { get { return 6; } } /// <inheritdoc/> public int MethodDefOrRefTag { get { return 1; } } /// <inheritdoc/> public int CustomAttributeTypeTag { get { return 3; } } /// <summary> /// From column MemberRef.Class /// </summary> public IMemberRefParent Class { get { return @class; } set { @class = value; } } /// <summary/> protected IMemberRefParent @class; /// <summary> /// From column MemberRef.Name /// </summary> public UTF8String Name { get { return name; } set { name = value; } } /// <summary>Name</summary> protected UTF8String name; /// <summary> /// From column MemberRef.Signature /// </summary> public CallingConventionSig Signature { get { return signature; } set { signature = value; } } /// <summary/> protected CallingConventionSig signature; /// <summary> /// Gets all custom attributes /// </summary> public CustomAttributeCollection CustomAttributes { get { if (customAttributes == null) InitializeCustomAttributes(); return customAttributes; } } /// <summary/> protected CustomAttributeCollection customAttributes; /// <summary>Initializes <see cref="customAttributes"/></summary> protected virtual void InitializeCustomAttributes() { Interlocked.CompareExchange(ref customAttributes, new CustomAttributeCollection(), null); } /// <inheritdoc/> public bool HasCustomAttributes { get { return CustomAttributes.Count > 0; } } /// <inheritdoc/> public ITypeDefOrRef DeclaringType { get { var owner = @class; var tdr = owner as ITypeDefOrRef; if (tdr != null) return tdr; var method = owner as MethodDef; if (method != null) return method.DeclaringType; var mr = owner as ModuleRef; if (mr != null) { var tr = GetGlobalTypeRef(mr); if (module != null) return module.UpdateRowId(tr); return tr; } return null; } } TypeRefUser GetGlobalTypeRef(ModuleRef mr) { if (module == null) return CreateDefaultGlobalTypeRef(mr); var globalType = module.GlobalType; if (globalType != null && new SigComparer().Equals(module, mr)) return new TypeRefUser(module, globalType.Namespace, globalType.Name, mr); var asm = module.Assembly; if (asm == null) return CreateDefaultGlobalTypeRef(mr); var mod = asm.FindModule(mr.Name); if (mod == null) return CreateDefaultGlobalTypeRef(mr); globalType = mod.GlobalType; if (globalType == null) return CreateDefaultGlobalTypeRef(mr); return new TypeRefUser(module, globalType.Namespace, globalType.Name, mr); } TypeRefUser CreateDefaultGlobalTypeRef(ModuleRef mr) { var tr = new TypeRefUser(module, string.Empty, "<Module>", mr); if (module != null) module.UpdateRowId(tr); return tr; } bool IIsTypeOrMethod.IsType { get { return false; } } bool IIsTypeOrMethod.IsMethod { get { return IsMethodRef; } } bool IMemberRef.IsField { get { return IsFieldRef; } } bool IMemberRef.IsTypeSpec { get { return false; } } bool IMemberRef.IsTypeRef { get { return false; } } bool IMemberRef.IsTypeDef { get { return false; } } bool IMemberRef.IsMethodSpec { get { return false; } } bool IMemberRef.IsMethodDef { get { return false; } } bool IMemberRef.IsMemberRef { get { return true; } } bool IMemberRef.IsFieldDef { get { return false; } } bool IMemberRef.IsPropertyDef { get { return false; } } bool IMemberRef.IsEventDef { get { return false; } } bool IMemberRef.IsGenericParam { get { return false; } } /// <summary> /// <c>true</c> if this is a method reference (<see cref="MethodSig"/> != <c>null</c>) /// </summary> public bool IsMethodRef { get { return MethodSig != null; } } /// <summary> /// <c>true</c> if this is a field reference (<see cref="FieldSig"/> != <c>null</c>) /// </summary> public bool IsFieldRef { get { return FieldSig != null; } } /// <summary> /// Gets/sets the method sig /// </summary> public MethodSig MethodSig { get { return signature as MethodSig; } set { signature = value; } } /// <summary> /// Gets/sets the field sig /// </summary> public FieldSig FieldSig { get { return signature as FieldSig; } set { signature = value; } } /// <inheritdoc/> public ModuleDef Module { get { return module; } } /// <summary> /// <c>true</c> if the method has a hidden 'this' parameter /// </summary> public bool HasThis { get { var ms = MethodSig; return ms == null ? false : ms.HasThis; } } /// <summary> /// <c>true</c> if the method has an explicit 'this' parameter /// </summary> public bool ExplicitThis { get { var ms = MethodSig; return ms == null ? false : ms.ExplicitThis; } } /// <summary> /// Gets the calling convention /// </summary> public CallingConvention CallingConvention { get { var ms = MethodSig; return ms == null ? 0 : ms.CallingConvention & CallingConvention.Mask; } } /// <summary> /// Gets/sets the method return type /// </summary> public TypeSig ReturnType { get { var ms = MethodSig; return ms == null ? null : ms.RetType; } set { var ms = MethodSig; if (ms != null) ms.RetType = value; } } /// <inheritdoc/> int IGenericParameterProvider.NumberOfGenericParameters { get { var sig = MethodSig; return sig == null ? 0 : (int)sig.GenParamCount; } } /// <summary> /// Gets the full name /// </summary> public string FullName { get { var parent = @class; IList<TypeSig> typeGenArgs = null; if (parent is TypeSpec) { var sig = ((TypeSpec)parent).TypeSig as GenericInstSig; if (sig != null) typeGenArgs = sig.GenericArguments; } var methodSig = MethodSig; if (methodSig != null) return FullNameCreator.MethodFullName(GetDeclaringTypeFullName(parent), name, methodSig, typeGenArgs, null, null, null); var fieldSig = FieldSig; if (fieldSig != null) return FullNameCreator.FieldFullName(GetDeclaringTypeFullName(parent), name, fieldSig, typeGenArgs, null); return string.Empty; } } /// <summary> /// Get the declaring type's full name /// </summary> /// <returns>Full name or <c>null</c> if there's no declaring type</returns> public string GetDeclaringTypeFullName() { return GetDeclaringTypeFullName(@class); } string GetDeclaringTypeFullName(IMemberRefParent parent) { if (parent == null) return null; if (parent is ITypeDefOrRef) return ((ITypeDefOrRef)parent).FullName; if (parent is ModuleRef) return string.Format("[module:{0}]<Module>", ((ModuleRef)parent).ToString()); if (parent is MethodDef) { var declaringType = ((MethodDef)parent).DeclaringType; return declaringType == null ? null : declaringType.FullName; } return null; // Should never be reached } /// <summary> /// Resolves the method/field /// </summary> /// <returns>A <see cref="MethodDef"/> or a <see cref="FieldDef"/> instance or <c>null</c> /// if it couldn't be resolved.</returns> public IMemberForwarded Resolve() { if (module == null) return null; return module.Context.Resolver.Resolve(this); } /// <summary> /// Resolves the method/field /// </summary> /// <returns>A <see cref="MethodDef"/> or a <see cref="FieldDef"/> instance</returns> /// <exception cref="MemberRefResolveException">If the method/field couldn't be resolved</exception> public IMemberForwarded ResolveThrow() { var memberDef = Resolve(); if (memberDef != null) return memberDef; throw new MemberRefResolveException(string.Format("Could not resolve method/field: {0} ({1})", this, this.GetDefinitionAssembly())); } /// <summary> /// Resolves the field /// </summary> /// <returns>A <see cref="FieldDef"/> instance or <c>null</c> if it couldn't be resolved.</returns> public FieldDef ResolveField() { return Resolve() as FieldDef; } /// <summary> /// Resolves the field /// </summary> /// <returns>A <see cref="FieldDef"/> instance</returns> /// <exception cref="MemberRefResolveException">If the field couldn't be resolved</exception> public FieldDef ResolveFieldThrow() { var field = ResolveField(); if (field != null) return field; throw new MemberRefResolveException(string.Format("Could not resolve field: {0} ({1})", this, this.GetDefinitionAssembly())); } /// <summary> /// Resolves the method /// </summary> /// <returns>A <see cref="MethodDef"/> instance or <c>null</c> if it couldn't be resolved.</returns> public MethodDef ResolveMethod() { return Resolve() as MethodDef; } /// <summary> /// Resolves the method /// </summary> /// <returns>A <see cref="MethodDef"/> instance</returns> /// <exception cref="MemberRefResolveException">If the method couldn't be resolved</exception> public MethodDef ResolveMethodThrow() { var method = ResolveMethod(); if (method != null) return method; throw new MemberRefResolveException(string.Format("Could not resolve method: {0} ({1})", this, this.GetDefinitionAssembly())); } bool IContainsGenericParameter.ContainsGenericParameter { get { return TypeHelper.ContainsGenericParameter(this); } } /// <summary> /// Gets a <see cref="GenericParamContext"/> that can be used as signature context /// </summary> /// <param name="gpContext">Context passed to the constructor</param> /// <param name="class">Field/method class owner</param> /// <returns></returns> protected static GenericParamContext GetSignatureGenericParamContext(GenericParamContext gpContext, IMemberRefParent @class) { TypeDef type = null; MethodDef method = gpContext.Method; var ts = @class as TypeSpec; if (ts != null) { var gis = ts.TypeSig as GenericInstSig; if (gis != null) type = gis.GenericType.ToTypeDefOrRef().ResolveTypeDef(); } return new GenericParamContext(type, method); } /// <inheritdoc/> public override string ToString() { return FullName; } } /// <summary> /// A MemberRef row created by the user and not present in the original .NET file /// </summary> public class MemberRefUser : MemberRef { /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> public MemberRefUser(ModuleDef module) { this.module = module; } /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> /// <param name="name">Name of ref</param> public MemberRefUser(ModuleDef module, UTF8String name) { this.module = module; this.name = name; } /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> /// <param name="name">Name of field ref</param> /// <param name="sig">Field sig</param> public MemberRefUser(ModuleDef module, UTF8String name, FieldSig sig) : this(module, name, sig, null) { } /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> /// <param name="name">Name of field ref</param> /// <param name="sig">Field sig</param> /// <param name="class">Owner of field</param> public MemberRefUser(ModuleDef module, UTF8String name, FieldSig sig, IMemberRefParent @class) { this.module = module; this.name = name; this.@class = @class; this.signature = sig; } /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> /// <param name="name">Name of method ref</param> /// <param name="sig">Method sig</param> public MemberRefUser(ModuleDef module, UTF8String name, MethodSig sig) : this(module, name, sig, null) { } /// <summary> /// Constructor /// </summary> /// <param name="module">Owner module</param> /// <param name="name">Name of method ref</param> /// <param name="sig">Method sig</param> /// <param name="class">Owner of method</param> public MemberRefUser(ModuleDef module, UTF8String name, MethodSig sig, IMemberRefParent @class) { this.module = module; this.name = name; this.@class = @class; this.signature = sig; } } /// <summary> /// Created from a row in the MemberRef table /// </summary> sealed class MemberRefMD : MemberRef, IMDTokenProviderMD { /// <summary>The module where this instance is located</summary> readonly ModuleDefMD readerModule; readonly uint origRid; /// <inheritdoc/> public uint OrigRid { get { return origRid; } } /// <inheritdoc/> protected override void InitializeCustomAttributes() { var list = readerModule.MetaData.GetCustomAttributeRidList(Table.MemberRef, origRid); var tmp = new CustomAttributeCollection((int)list.Length, list, (list2, index) => readerModule.ReadCustomAttribute(((RidList)list2)[index])); Interlocked.CompareExchange(ref customAttributes, tmp, null); } /// <summary> /// Constructor /// </summary> /// <param name="readerModule">The module which contains this <c>MemberRef</c> row</param> /// <param name="rid">Row ID</param> /// <param name="gpContext">Generic parameter context</param> /// <exception cref="ArgumentNullException">If <paramref name="readerModule"/> is <c>null</c></exception> /// <exception cref="ArgumentException">If <paramref name="rid"/> is invalid</exception> public MemberRefMD(ModuleDefMD readerModule, uint rid, GenericParamContext gpContext) { #if DEBUG if (readerModule == null) throw new ArgumentNullException("readerModule"); if (readerModule.TablesStream.MemberRefTable.IsInvalidRID(rid)) throw new BadImageFormatException(string.Format("MemberRef rid {0} does not exist", rid)); #endif this.origRid = rid; this.rid = rid; this.readerModule = readerModule; this.module = readerModule; uint @class, name; uint signature = readerModule.TablesStream.ReadMemberRefRow(origRid, out @class, out name); this.name = readerModule.StringsStream.ReadNoNull(name); this.@class = readerModule.ResolveMemberRefParent(@class, gpContext); this.signature = readerModule.ReadSignature(signature, GetSignatureGenericParamContext(gpContext, this.@class)); } } }
using J2N.Threading; using Lucene.Net.Documents; using Lucene.Net.Index; using NUnit.Framework; using System; using System.Collections.Generic; using System.Globalization; using System.Threading; 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 Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using IndexReader = Lucene.Net.Index.IndexReader; using IndexWriter = Lucene.Net.Index.IndexWriter; using IndexWriterConfig = Lucene.Net.Index.IndexWriterConfig; using Int32Field = Int32Field; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using StringField = StringField; using Term = Lucene.Net.Index.Term; using TestUtil = Lucene.Net.Util.TestUtil; [TestFixture] public class TestLiveFieldValues : LuceneTestCase { [Test] public virtual void Test() { Directory dir = NewFSDirectory(CreateTempDir("livefieldupdates")); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)); IndexWriter w = new IndexWriter(dir, iwc); SearcherManager mgr = new SearcherManager(w, true, new SearcherFactoryAnonymousInnerClassHelper()); const int missing = -1; LiveFieldValues<IndexSearcher, int?> rt = new LiveFieldValuesAnonymousInnerClassHelper(mgr, missing); int numThreads = TestUtil.NextInt32(Random, 2, 5); if (Verbose) { Console.WriteLine(numThreads + " threads"); } CountdownEvent startingGun = new CountdownEvent(1); IList<ThreadJob> threads = new List<ThreadJob>(); int iters = AtLeast(1000); int idCount = TestUtil.NextInt32(Random, 100, 10000); double reopenChance = Random.NextDouble() * 0.01; double deleteChance = Random.NextDouble() * 0.25; double addChance = Random.NextDouble() * 0.5; for (int t = 0; t < numThreads; t++) { int threadID = t; Random threadRandom = new Random(Random.Next()); ThreadJob thread = new ThreadAnonymousInnerClassHelper(w, mgr, missing, rt, startingGun, iters, idCount, reopenChance, deleteChance, addChance, t, threadID, threadRandom); threads.Add(thread); thread.Start(); } startingGun.Signal(); foreach (ThreadJob thread in threads) { thread.Join(); } mgr.MaybeRefresh(); Assert.AreEqual(0, rt.Count); rt.Dispose(); mgr.Dispose(); w.Dispose(); dir.Dispose(); } private class SearcherFactoryAnonymousInnerClassHelper : SearcherFactory { public override IndexSearcher NewSearcher(IndexReader r) { return new IndexSearcher(r); } } private class LiveFieldValuesAnonymousInnerClassHelper : LiveFieldValues<IndexSearcher, int?> { public LiveFieldValuesAnonymousInnerClassHelper(SearcherManager mgr, int missing) : base(mgr, missing) { } protected override int? LookupFromSearcher(IndexSearcher s, string id) { TermQuery tq = new TermQuery(new Term("id", id)); TopDocs hits = s.Search(tq, 1); Assert.IsTrue(hits.TotalHits <= 1); if (hits.TotalHits == 0) { return null; } else { Document doc = s.Doc(hits.ScoreDocs[0].Doc); return doc.GetField("field").GetInt32Value(); } } } private class ThreadAnonymousInnerClassHelper : ThreadJob { private readonly IndexWriter w; private readonly SearcherManager mgr; private readonly int? missing; private readonly LiveFieldValues<IndexSearcher, int?> rt; private readonly CountdownEvent startingGun; private readonly int iters; private readonly int idCount; private readonly double reopenChance; private readonly double deleteChance; private readonly double addChance; private readonly int t; private readonly int threadID; private readonly Random threadRandom; public ThreadAnonymousInnerClassHelper(IndexWriter w, SearcherManager mgr, int? missing, LiveFieldValues<IndexSearcher, int?> rt, CountdownEvent startingGun, int iters, int idCount, double reopenChance, double deleteChance, double addChance, int t, int threadID, Random threadRandom) { this.w = w; this.mgr = mgr; this.missing = missing; this.rt = rt; this.startingGun = startingGun; this.iters = iters; this.idCount = idCount; this.reopenChance = reopenChance; this.deleteChance = deleteChance; this.addChance = addChance; this.t = t; this.threadID = threadID; this.threadRandom = threadRandom; } public override void Run() { try { IDictionary<string, int?> values = new Dictionary<string, int?>(); IList<string> allIDs = new SynchronizedList<string>(); startingGun.Wait(); for (int iter = 0; iter < iters; iter++) { // Add/update a document Document doc = new Document(); // Threads must not update the same id at the // same time: if (threadRandom.NextDouble() <= addChance) { string id = string.Format(CultureInfo.InvariantCulture, "{0}_{1:X4}", threadID, threadRandom.Next(idCount)); int field = threadRandom.Next(int.MaxValue); doc.Add(new StringField("id", id, Field.Store.YES)); doc.Add(new Int32Field("field", (int)field, Field.Store.YES)); w.UpdateDocument(new Term("id", id), doc); rt.Add(id, field); if (!values.ContainsKey(id))//Key didn't exist before { allIDs.Add(id); } values[id] = field; } if (allIDs.Count > 0 && threadRandom.NextDouble() <= deleteChance) { string randomID = allIDs[threadRandom.Next(allIDs.Count)]; w.DeleteDocuments(new Term("id", randomID)); rt.Delete(randomID); values[randomID] = missing; } if (threadRandom.NextDouble() <= reopenChance || rt.Count > 10000) { //System.out.println("refresh @ " + rt.Size()); mgr.MaybeRefresh(); if (Verbose) { IndexSearcher s = mgr.Acquire(); try { Console.WriteLine("TEST: reopen " + s); } finally { mgr.Release(s); } Console.WriteLine("TEST: " + values.Count + " values"); } } if (threadRandom.Next(10) == 7) { Assert.AreEqual(null, rt.Get("foo")); } if (allIDs.Count > 0) { string randomID = allIDs[threadRandom.Next(allIDs.Count)]; int? expected = values[randomID]; if (expected == missing) { expected = null; } Assert.AreEqual(expected, rt.Get(randomID), "id=" + randomID); } } } catch (Exception t) { throw new Exception(t.Message, t); } } } } }
using System; using System.Diagnostics; using System.IO; using Dune.Packets; using Dune.Packets.Impl; namespace Dune { public class PacketStream { private readonly Stream _stream; private ushort _sequence; public PacketStream(Stream stream) { if (stream == null) throw new ArgumentNullException("stream"); _stream = stream; } public void WritePacket(PacketBase packet, ushort? sequence = null) { sequence = sequence ?? _sequence++; packet.Sequence = sequence.Value; byte[] data = packet.Serialize(); _stream.Write(data, 0, data.Length); } public T ReadPacket<T>() where T : PacketBase { T packet = ReadPacket() as T; if (packet == null) throw new ApplicationException(); return packet; } public RawPacket ReadRawPacket() { return RawPacket.Read(_stream); } public PacketBase ReadPacket() { RawPacket rawPacket = ReadRawPacket(); PacketBase packet; switch (rawPacket.Type) { case PacketType.OnlineCheckRequest: packet = new OnlineCheckRequest(); break; case PacketType.OnlineCheckResponse: packet = new OnlineCheckResponse(); break; case PacketType.DisconnectionRequest: packet = new DisconnectionRequest(); break; case PacketType.DisconnectionResponse: packet = new DisconnectionResponse(); break; case PacketType.DisconnectionNotification: packet = new DisconnectionNotification(); break; case PacketType.ReconnectionRequest: packet = new ReconnectionRequest(); break; case PacketType.FastDataRequest: packet = new FastDataRequest(); break; case PacketType.FastDataResponse: packet = new FastDataResponse(); break; case PacketType.ConnectionSummaryNotification: packet = new ConnectionSummaryNotification(); break; case PacketType.AuthenticationInformationRequestHeader: packet = new AuthenticationInformationRequestHeader(); break; case PacketType.AuthenticationInformationResponseHeader: packet = new AuthenticationInformationResponseHeader(); break; case PacketType.AuthenticationInformationRequestData: packet = new AuthenticationInformationRequestData(); break; case PacketType.AuthenticationInformationResponseData: packet = new AuthenticationInformationResponseData(); break; case PacketType.AuthenticationInformationRequestFooter: packet = new AuthenticationInformationRequestFooter(); break; case PacketType.AuthenticationInformationResponseFooter: packet = new AuthenticationInformationResponseFooter(); break; case PacketType.TusCommonAreaAcquisitionRequest: packet = new TusCommonAreaAcquisitionRequest(); break; case PacketType.TusCommonAreaAcquisitionResponse: packet = new TusCommonAreaAcquisitionResponse(); break; case PacketType.TusCommonAreaSettingsRequest: packet = new TusCommonAreaSettingsRequest(); break; case PacketType.TusCommonAreaSettingsResponse: packet = new TusCommonAreaSettingsResponse(); break; case PacketType.TusCommonAreaAddRequest: packet = new TusCommonAreaAddRequest(); break; case PacketType.TusCommonAreaAddResponse: packet = new TusCommonAreaAddResponse(); break; case PacketType.TusUserAreaWriteRequestHeader: packet = new TusUserAreaWriteRequestHeader(); break; case PacketType.TusUserAreaWriteResponseHeader: packet = new TusUserAreaWriteResponseHeader(); break; case PacketType.TusUserAreaWriteRequestData: packet = new TusUserAreaWriteRequestData(); break; case PacketType.TusUserAreaWriteResponseData: packet = new TusUserAreaWriteResponseData(); break; case PacketType.TusUserAreaWriteRequestFooter: packet = new TusUserAreaWriteRequestFooter(); break; case PacketType.TusUserAreaWriteResponseFooter: packet = new TusUserAreaWriteResponseFooter(); break; case PacketType.TusUserAreaReadRequestHeader: packet = new TusUserAreaReadRequestHeader(); break; case PacketType.TusUserAreaReadResponseHeader: packet = new TusUserAreaReadResponseHeader(); break; case PacketType.TusUserAreaReadRequestData: packet = new TusUserAreaReadRequestData(); break; case PacketType.TusUserAreaReadResponseData: packet = new TusUserAreaReadResponseData(); break; case PacketType.TusUserAreaReadRequestFooter: packet = new TusUserAreaReadRequestFooter(); break; case PacketType.TusUserAreaReadResponseFooter: packet = new TusUserAreaReadResponseFooter(); break; default: return rawPacket; } packet.Sequence = rawPacket.Sequence; packet.ParsePayload(rawPacket.Payload); return packet; } public void Close() { _stream.Close(); } public void WriteData<TRequest, TResponse>(byte[] data, ushort chunkLength) where TRequest : DataChunkBase, new() where TResponse : DataChunkReferenceBase, new() { chunkLength = data.Length < chunkLength ? (ushort)data.Length : chunkLength; MemoryStream dataStream = new MemoryStream(data); byte[] chunk = new byte[chunkLength]; while (dataStream.Position < dataStream.Length) { int dataChunkLength; int remainingLength = (int)(dataStream.Length - dataStream.Position); if (remainingLength < chunkLength) { const byte chunkPadding = 0xDD; for (int i = remainingLength; i < chunk.Length; i++) { chunk[i] = chunkPadding; } dataChunkLength = remainingLength; } else { dataChunkLength = chunkLength; } int chunkOffset = (int)dataStream.Position; dataStream.Read(chunk, 0, dataChunkLength); WritePacket(new TRequest { Chunk = chunk, ChunkOffset = chunkOffset, ChunkLength = chunkLength }); var response = ReadPacket<TResponse>(); Debug.Assert(response.ChunkOffset == chunkOffset); Debug.Assert(response.ChunkLength == chunkLength); } } public byte[] ReadData<TRequest, TResponse>(int bufferLength, ushort chunkLength) where TRequest : DataChunkReferenceBase, new() where TResponse : DataChunkBase, new() { byte[] data = new byte[bufferLength]; MemoryStream dataStream = new MemoryStream(data); while (dataStream.Position < dataStream.Length) { WritePacket(new TRequest { ChunkOffset = (int)dataStream.Position, ChunkLength = chunkLength }); var dataResponse = ReadPacket<TResponse>(); Debug.Assert(dataResponse.ChunkOffset == dataStream.Position); Debug.Assert(dataResponse.Chunk.Length == chunkLength); dataStream.Write(dataResponse.Chunk, 0, dataResponse.Chunk.Length); } return data; } } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System.Runtime.InteropServices; namespace SharpDX.Toolkit.Graphics { /// <summary> /// Provides typed structure to read and write to some <see cref="PixelFormat"/>. /// </summary> public static class PixelData { internal static byte ToByte(float component) { var value = (int) (component*255.0f); return (byte)(value < 0 ? 0 : value > 255 ? 255 : value); } /// <summary> /// Pixel format associated to <see cref="PixelFormat.R8.UNorm"/>. /// </summary> [StructLayout(LayoutKind.Sequential, Size = 1)] public struct R8 : IPixelData { public byte R; public R8(byte r) { this.R = r; } public PixelFormat Format { get { return PixelFormat.R8.UNorm; } } public Color4 Value { get { return new Color4(R/255.0f, 0, 0, 1.0f); } set { R = ToByte(value.Red); } } public Color Value32Bpp { get { return new Color(R, (byte)0, (byte)0, (byte)255); } set { R = value.R; } } public override string ToString() { return string.Format("R:{0}", R); } } /// <summary> /// Pixel format associated to <see cref="PixelFormat.R8G8.UNorm"/>. /// </summary> [StructLayout(LayoutKind.Sequential, Size = 2)] public struct R8G8 : IPixelData { public byte R, G; public PixelFormat Format { get { return PixelFormat.R8G8.UNorm; } } public Color4 Value { get { return new Color4(R / 255.0f, G / 255.0f, 0, 1.0f); } set { R = ToByte(value.Red); G = ToByte(value.Green); } } public Color Value32Bpp { get { return new Color(R, G, (byte)0, (byte)255); } set { R = value.R; G = value.G; } } public override string ToString() { return string.Format("R:{0}, G:{1}", R, G); } } /// <summary> /// Pixel format associated to <see cref="PixelFormat.R8G8B8A8.UNorm"/>. /// </summary> [StructLayout(LayoutKind.Sequential, Size = 4)] public struct R8G8B8A8 : IPixelData { public byte R, G, B, A; public PixelFormat Format { get { return PixelFormat.R8G8B8A8.UNorm; } } public Color4 Value { get { return new Color4(R / 255.0f, G / 255.0f, B / 255.0f, A / 255.0f); } set { R = ToByte(value.Red); G = ToByte(value.Green); B = ToByte(value.Blue); A = ToByte(value.Alpha); } } public Color Value32Bpp { get { return new Color(R, G, B, A); } set { R = value.R; G = value.G; B = value.B; A = value.A; } } public override string ToString() { return string.Format("R:{0}, G:{1}, B:{2}, A:{3}", R, G, B, A); } } /// <summary> /// Pixel format associated to <see cref="PixelFormat.R16.UNorm"/>. /// </summary> [StructLayout(LayoutKind.Sequential, Size = 1)] public struct R16 : IPixelData { public Half R; public PixelFormat Format { get { return PixelFormat.R16.UNorm; } } public Color4 Value { get { return new Color4(R / 255.0f, 0, 0, 1.0f); } set { R = new Half(value.Red); } } public Color Value32Bpp { get { return new Color(R, 0, 0, 1); } set { R = new Half(value.R / 255.0f); } } public override string ToString() { return string.Format("R:{0}", R); } } /// <summary> /// Pixel format associated to <see cref="PixelFormat.R16G16.UNorm"/>. /// </summary> [StructLayout(LayoutKind.Sequential, Size = 2)] public struct R16G16 : IPixelData { public Half R, G; public PixelFormat Format { get { return PixelFormat.R16G16.UNorm; } } public Color4 Value { get { return new Color4(R / 255.0f, G / 255.0f, 0, 1.0f); } set { R = new Half(value.Red); G = new Half(value.Green); } } public Color Value32Bpp { get { return new Color(R, G, 0, 1); } set { R = new Half(value.R / 255.0f); G = new Half(value.G / 255.0f); } } public override string ToString() { return string.Format("R:{0}, G:{1}", R, G); } } /// <summary> /// Pixel format associated to <see cref="PixelFormat.R16G16B16A16.UNorm"/>. /// </summary> [StructLayout(LayoutKind.Sequential, Size = 4)] public struct R16G16B16A16 : IPixelData { public Half R, G, B, A; public PixelFormat Format { get { return PixelFormat.R16G16B16A16.UNorm; } } public Color4 Value { get { return new Color4(R / 255.0f, G / 255.0f, B / 255.0f, A / 255.0f); } set { R = new Half(value.Red); G = new Half(value.Green); B = new Half(value.Blue); A = new Half(value.Alpha); } } public Color Value32Bpp { get { return new Color(R, G, B, A); } set { R = new Half(value.R / 255.0f); G = new Half(value.G / 255.0f); B = new Half(value.B / 255.0f); A = new Half(value.A / 255.0f); } } public override string ToString() { return string.Format("R:{0}, G:{1}, B:{2}, A:{3}", R, G, B, A); } } } }
// 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.IO; using System.Linq; using System.Reflection; using System.Xml; using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.Construction; using Microsoft.Build.Framework; using Microsoft.Build.Shared; namespace Microsoft.Build.BackEnd.SdkResolution { internal class SdkResolverLoader { #if FEATURE_ASSEMBLYLOADCONTEXT private static readonly CoreClrAssemblyLoader s_loader = new CoreClrAssemblyLoader(); #endif private readonly string IncludeDefaultResolver = Environment.GetEnvironmentVariable("MSBUILDINCLUDEDEFAULTSDKRESOLVER"); // Test hook for loading SDK Resolvers from additional folders. Support runtime-specific test hook environment variables, // as an SDK resolver built for .NET Framework probably won't work on .NET Core, and vice versa. private readonly string AdditionalResolversFolder = Environment.GetEnvironmentVariable( #if NETFRAMEWORK "MSBUILDADDITIONALSDKRESOLVERSFOLDER_NETFRAMEWORK" #elif NET "MSBUILDADDITIONALSDKRESOLVERSFOLDER_NET" #endif ) ?? Environment.GetEnvironmentVariable("MSBUILDADDITIONALSDKRESOLVERSFOLDER"); internal virtual IList<SdkResolver> LoadResolvers(LoggingContext loggingContext, ElementLocation location) { var resolvers = !String.Equals(IncludeDefaultResolver, "false", StringComparison.OrdinalIgnoreCase) ? new List<SdkResolver> {new DefaultSdkResolver()} : new List<SdkResolver>(); var potentialResolvers = FindPotentialSdkResolvers( Path.Combine(BuildEnvironmentHelper.Instance.MSBuildToolsDirectory32, "SdkResolvers"), location); if (potentialResolvers.Count == 0) { return resolvers; } foreach (var potentialResolver in potentialResolvers) { LoadResolvers(potentialResolver, loggingContext, location, resolvers); } return resolvers.OrderBy(t => t.Priority).ToList(); } /// <summary> /// Find all files that are to be considered SDK Resolvers. Pattern will match /// Root\SdkResolver\(ResolverName)\(ResolverName).dll. /// </summary> /// <param name="rootFolder"></param> /// <param name="location"></param> /// <returns></returns> internal virtual IList<string> FindPotentialSdkResolvers(string rootFolder, ElementLocation location) { var assembliesList = new List<string>(); if ((string.IsNullOrEmpty(rootFolder) || !FileUtilities.DirectoryExistsNoThrow(rootFolder)) && AdditionalResolversFolder == null) { return assembliesList; } DirectoryInfo[] subfolders = GetSubfolders(rootFolder, AdditionalResolversFolder); foreach (var subfolder in subfolders) { var assembly = Path.Combine(subfolder.FullName, $"{subfolder.Name}.dll"); var manifest = Path.Combine(subfolder.FullName, $"{subfolder.Name}.xml"); var assemblyAdded = TryAddAssembly(assembly, assembliesList); if (!assemblyAdded) { assemblyAdded = TryAddAssemblyFromManifest(manifest, subfolder.FullName, assembliesList, location); } if (!assemblyAdded) { ProjectFileErrorUtilities.ThrowInvalidProjectFile(new BuildEventFileInfo(location), "SdkResolverNoDllOrManifest", subfolder.FullName); } } return assembliesList; } private DirectoryInfo[] GetSubfolders(string rootFolder, string additionalResolversFolder) { DirectoryInfo[] subfolders = null; if (!string.IsNullOrEmpty(rootFolder) && FileUtilities.DirectoryExistsNoThrow(rootFolder)) { subfolders = new DirectoryInfo(rootFolder).GetDirectories(); } if (additionalResolversFolder != null) { var resolversDirInfo = new DirectoryInfo(additionalResolversFolder); if (resolversDirInfo.Exists) { HashSet<DirectoryInfo> overrideFolders = resolversDirInfo.GetDirectories().ToHashSet(new DirInfoNameComparer()); if (subfolders != null) { overrideFolders.UnionWith(subfolders); } return overrideFolders.ToArray(); } } return subfolders; } private class DirInfoNameComparer : IEqualityComparer<DirectoryInfo> { public bool Equals(DirectoryInfo first, DirectoryInfo second) { return string.Equals(first.Name, second.Name, StringComparison.OrdinalIgnoreCase); } public int GetHashCode(DirectoryInfo value) { return value.Name.GetHashCode(); } } private bool TryAddAssemblyFromManifest(string pathToManifest, string manifestFolder, List<string> assembliesList, ElementLocation location) { if (!string.IsNullOrEmpty(pathToManifest) && !FileUtilities.FileExistsNoThrow(pathToManifest)) return false; string path = null; try { // <SdkResolver> // <Path>...</Path> // </SdkResolver> var manifest = SdkResolverManifest.Load(pathToManifest); if (manifest == null || string.IsNullOrEmpty(manifest.Path)) { ProjectFileErrorUtilities.ThrowInvalidProjectFile(new BuildEventFileInfo(location), "SdkResolverDllInManifestMissing", pathToManifest, string.Empty); } path = FileUtilities.FixFilePath(manifest.Path); } catch (XmlException e) { // Note: Not logging e.ToString() as most of the information is not useful, the Message will contain what is wrong with the XML file. ProjectFileErrorUtilities.ThrowInvalidProjectFile(new BuildEventFileInfo(location), e, "SdkResolverManifestInvalid", pathToManifest, e.Message); } if (!Path.IsPathRooted(path)) { path = Path.Combine(manifestFolder, path); path = Path.GetFullPath(path); } if (!TryAddAssembly(path, assembliesList)) { ProjectFileErrorUtilities.ThrowInvalidProjectFile(new BuildEventFileInfo(location), "SdkResolverDllInManifestMissing", pathToManifest, path); } return true; } private bool TryAddAssembly(string assemblyPath, List<string> assembliesList) { if (string.IsNullOrEmpty(assemblyPath) || !FileUtilities.FileExistsNoThrow(assemblyPath)) return false; assembliesList.Add(assemblyPath); return true; } protected virtual IEnumerable<Type> GetResolverTypes(Assembly assembly) { return assembly.ExportedTypes .Select(type => new {type, info = type.GetTypeInfo()}) .Where(t => t.info.IsClass && t.info.IsPublic && !t.info.IsAbstract && typeof(SdkResolver).IsAssignableFrom(t.type)) .Select(t => t.type); } protected virtual Assembly LoadResolverAssembly(string resolverPath, LoggingContext loggingContext, ElementLocation location) { #if !FEATURE_ASSEMBLYLOADCONTEXT return Assembly.LoadFrom(resolverPath); #else return s_loader.LoadFromPath(resolverPath); #endif } protected virtual void LoadResolvers(string resolverPath, LoggingContext loggingContext, ElementLocation location, List<SdkResolver> resolvers) { Assembly assembly; try { assembly = LoadResolverAssembly(resolverPath, loggingContext, location); } catch (Exception e) { ProjectFileErrorUtilities.ThrowInvalidProjectFile(new BuildEventFileInfo(location), e, "CouldNotLoadSdkResolverAssembly", resolverPath, e.Message); return; } foreach (Type type in GetResolverTypes(assembly)) { try { resolvers.Add((SdkResolver)Activator.CreateInstance(type)); } catch (TargetInvocationException e) { // .NET wraps the original exception inside of a TargetInvocationException which masks the original message // Attempt to get the inner exception in this case, but fall back to the top exception message string message = e.InnerException?.Message ?? e.Message; ProjectFileErrorUtilities.ThrowInvalidProjectFile(new BuildEventFileInfo(location), e.InnerException ?? e, "CouldNotLoadSdkResolver", type.Name, message); } catch (Exception e) { ProjectFileErrorUtilities.ThrowInvalidProjectFile(new BuildEventFileInfo(location), e, "CouldNotLoadSdkResolver", type.Name, e.Message); } } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using BufferedIndexInput = Lucene.Net.Store.BufferedIndexInput; using Cache = Lucene.Net.Util.Cache.Cache; using SimpleLRUCache = Lucene.Net.Util.Cache.SimpleLRUCache; using CloseableThreadLocal = Lucene.Net.Util.CloseableThreadLocal; using Directory = Lucene.Net.Store.Directory; namespace Lucene.Net.Index { /// <summary>This stores a monotonically increasing set of <Term, TermInfo> pairs in a /// Directory. Pairs are accessed either by Term or by ordinal position the /// set. /// </summary> public sealed class TermInfosReader { private Directory directory; private System.String segment; private FieldInfos fieldInfos; private CloseableThreadLocal threadResources = new CloseableThreadLocal(); private SegmentTermEnum origEnum; private long size; private Term[] indexTerms = null; private TermInfo[] indexInfos; private long[] indexPointers; private SegmentTermEnum indexEnum; private int indexDivisor = 1; private int totalIndexInterval; private const int DEFAULT_CACHE_SIZE = 1024; /// <summary> /// Per-thread resources managed by ThreadLocal. /// </summary> internal sealed class ThreadResources { internal SegmentTermEnum termEnum; // used for caching the least recently looked-up Terms internal Cache termInfoCache; } internal TermInfosReader(Directory dir, System.String seg, FieldInfos fis) : this(dir, seg, fis, BufferedIndexInput.BUFFER_SIZE) { } internal TermInfosReader(Directory dir, System.String seg, FieldInfos fis, int readBufferSize) { bool success = false; try { directory = dir; segment = seg; fieldInfos = fis; origEnum = new SegmentTermEnum(directory.OpenInput(segment + "." + IndexFileNames.TERMS_EXTENSION, readBufferSize), fieldInfos, false); size = origEnum.size; totalIndexInterval = origEnum.indexInterval; indexEnum = new SegmentTermEnum(directory.OpenInput(segment + "." + IndexFileNames.TERMS_INDEX_EXTENSION, readBufferSize), fieldInfos, true); success = true; } finally { // With lock-less commits, it's entirely possible (and // fine) to hit a FileNotFound exception above. In // this case, we want to explicitly close any subset // of things that were opened so that we don't have to // wait for a GC to do so. if (!success) { Close(); } } } public int GetSkipInterval() { return origEnum.skipInterval; } public int GetMaxSkipLevels() { return origEnum.maxSkipLevels; } /// <summary> <p>Sets the indexDivisor, which subsamples the number /// of indexed terms loaded into memory. This has a /// similar effect as {@link /// IndexWriter#setTermIndexInterval} except that setting /// must be done at indexing time while this setting can be /// set per reader. When set to N, then one in every /// N*termIndexInterval terms in the index is loaded into /// memory. By setting this to a value > 1 you can reduce /// memory usage, at the expense of higher latency when /// loading a TermInfo. The default value is 1.</p> /// /// <b>NOTE:</b> you must call this before the term /// index is loaded. If the index is already loaded, /// an IllegalStateException is thrown. /// /// + @throws IllegalStateException if the term index has /// already been loaded into memory. /// </summary> public void SetIndexDivisor(int indexDivisor) { if (indexDivisor < 1) throw new System.ArgumentException("indexDivisor must be > 0: got " + indexDivisor); if (indexTerms != null) throw new System.SystemException("index terms are already loaded"); this.indexDivisor = indexDivisor; totalIndexInterval = origEnum.indexInterval * indexDivisor; } /// <summary>Returns the indexDivisor.</summary> /// <seealso cref="setIndexDivisor"> /// </seealso> public int GetIndexDivisor() { return indexDivisor; } public void Close() { if (origEnum != null) origEnum.Close(); if (indexEnum != null) indexEnum.Close(); threadResources.Close(); } /// <summary>Returns the number of term/value pairs in the set. </summary> internal long Size() { return size; } internal ThreadResources GetThreadResources() { ThreadResources resources = (ThreadResources)threadResources.Get(); if (resources == null) { resources = new ThreadResources(); resources.termEnum = Terms(); // cache does not have to be thread-safe, it is only used by one thread at the same time resources.termInfoCache = new SimpleLRUCache(DEFAULT_CACHE_SIZE); threadResources.Set(resources); } return resources; } private void EnsureIndexIsRead() { lock (this) { if (indexTerms != null) // index already read return ; // do nothing try { int indexSize = 1 + ((int) indexEnum.size - 1) / indexDivisor; // otherwise read index indexTerms = new Term[indexSize]; indexInfos = new TermInfo[indexSize]; indexPointers = new long[indexSize]; for (int i = 0; indexEnum.Next(); i++) { indexTerms[i] = indexEnum.Term(); indexInfos[i] = indexEnum.TermInfo(); indexPointers[i] = indexEnum.indexPointer; for (int j = 1; j < indexDivisor; j++) if (!indexEnum.Next()) break; } } finally { indexEnum.Close(); indexEnum = null; } } } /// <summary>Returns the offset of the greatest index entry which is less than or equal to term.</summary> private int GetIndexOffset(Term term) { int lo = 0; // binary search indexTerms[] int hi = indexTerms.Length - 1; while (hi >= lo) { int mid = (lo + hi) >> 1; int delta = term.CompareTo(indexTerms[mid]); if (delta < 0) hi = mid - 1; else if (delta > 0) lo = mid + 1; else return mid; } return hi; } private void SeekEnum(SegmentTermEnum enumerator, int indexOffset) { enumerator.Seek(indexPointers[indexOffset], (indexOffset * totalIndexInterval) - 1, indexTerms[indexOffset], indexInfos[indexOffset]); } /// <summary>Returns the TermInfo for a Term in the set, or null. </summary> internal TermInfo Get(Term term) { //return Get(term, true); //Lucene.Net specific. Default:true return Get(term, SupportClass.AppSettings.Get("EnableTermInfosReaderCache", true)); } /// <summary>Returns the TermInfo for a Term in the set, or null. </summary> public TermInfo Get(Term term, bool useCache) { if (size == 0) return null; EnsureIndexIsRead(); TermInfo ti; ThreadResources resources = GetThreadResources(); Cache cache = null; if (useCache) { cache = resources.termInfoCache; // check the cache first if the term was recently looked up ti = (TermInfo)cache.Get(term); if (ti != null) { return ti; } } // optimize sequential access: first try scanning cached enum w/o seeking SegmentTermEnum enumerator = resources.termEnum; if (enumerator.Term() != null && ((enumerator.Prev() != null && term.CompareTo(enumerator.Prev()) > 0) || term.CompareTo(enumerator.Term()) >= 0)) { int enumOffset = (int) (enumerator.position / totalIndexInterval) + 1; if (indexTerms.Length == enumOffset || term.CompareTo(indexTerms[enumOffset]) < 0) { int numScans = enumerator.ScanTo(term); if (enumerator.Term() != null && term.CompareTo(enumerator.Term()) == 0) { ti = enumerator.TermInfo(); if (cache != null && numScans > 1) { // we only want to put this TermInfo into the cache if // scanEnum skipped more than one dictionary entry. // this prevents RangeQueries or WildcardQueries from // wiping out the cache when they iterate over a large number // of terms in order cache.Put(term, ti); } } else { ti = null; } return ti; } } // random-access: must seek SeekEnum(enumerator, GetIndexOffset(term)); enumerator.ScanTo(term); if (enumerator.Term() != null && term.CompareTo(enumerator.Term()) == 0) { ti = enumerator.TermInfo(); if (cache != null) { cache.Put(term, ti); } } else { ti = null; } return ti; } /// <summary>Returns the nth term in the set. </summary> internal Term Get(int position) { if (size == 0) return null; SegmentTermEnum enumerator = GetThreadResources().termEnum; if (enumerator != null && enumerator.Term() != null && position >= enumerator.position && position < (enumerator.position + totalIndexInterval)) return ScanEnum(enumerator, position); // can avoid seek SeekEnum(enumerator, position / totalIndexInterval); // must seek return ScanEnum(enumerator, position); } private Term ScanEnum(SegmentTermEnum enumerator, int position) { while (enumerator.position < position) if (!enumerator.Next()) return null; return enumerator.Term(); } /// <summary>Returns the position of a Term in the set or -1. </summary> internal long GetPosition(Term term) { if (size == 0) return - 1; EnsureIndexIsRead(); int indexOffset = GetIndexOffset(term); SegmentTermEnum enumerator = GetThreadResources().termEnum; SeekEnum(enumerator, indexOffset); while (term.CompareTo(enumerator.Term()) > 0 && enumerator.Next()) { } if (term.CompareTo(enumerator.Term()) == 0) return enumerator.position; else return - 1; } /// <summary>Returns an enumeration of all the Terms and TermInfos in the set. </summary> public SegmentTermEnum Terms() { return (SegmentTermEnum) origEnum.Clone(); } /// <summary>Returns an enumeration of terms starting at or after the named term. </summary> public SegmentTermEnum Terms(Term term) { // don't use the cache in this call because we want to reposition the enumeration Get(term, false); return (SegmentTermEnum) GetThreadResources().termEnum.Clone(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.Serialization; using Microsoft.Xna.Framework; namespace MonoGame.Extended { // Real-Time Collision Detection, Christer Ericson, 2005. Chapter 4.2; Bounding Volumes - Axis-aligned Bounding Boxes (AABBs). pg 77 /// <summary> /// An axis-aligned, four sided, two dimensional box defined by a top-left position (<see cref="X" /> and /// <see cref="Y" />) and a size (<see cref="Width" /> and <see cref="Height" />). /// </summary> /// <remarks> /// <para> /// An <see cref="RectangleF" /> is categorized by having its faces oriented in such a way that its /// face normals are at all times parallel with the axes of the given coordinate system. /// </para> /// <para> /// The bounding <see cref="RectangleF" /> of a rotated <see cref="RectangleF" /> will be equivalent or larger /// in size than the original depending on the angle of rotation. /// </para> /// </remarks> /// <seealso cref="IEquatable{T}" /> /// <seealso cref="IEquatableByRef{T}" /> [DataContract] [DebuggerDisplay("{DebugDisplayString,nq}")] public struct RectangleF : IEquatable<RectangleF>, IEquatableByRef<RectangleF> { /// <summary> /// The <see cref="RectangleF" /> with <see cref="X" />, <see cref="Y" />, <see cref="Width" /> and /// <see cref="Height" /> all set to <code>0.0f</code>. /// </summary> public static readonly RectangleF Empty = new RectangleF(); /// <summary> /// The x-coordinate of the top-left corner position of this <see cref="RectangleF" />. /// </summary> [DataMember] public float X; /// <summary> /// The y-coordinate of the top-left corner position of this <see cref="RectangleF" />. /// </summary> [DataMember] public float Y; /// <summary> /// The width of this <see cref="RectangleF" />. /// </summary> [DataMember] public float Width; /// <summary> /// The height of this <see cref="RectangleF" />. /// </summary> [DataMember] public float Height; /// <summary> /// Gets the x-coordinate of the left edge of this <see cref="RectangleF" />. /// </summary> public float Left => X; /// <summary> /// Gets the x-coordinate of the right edge of this <see cref="RectangleF" />. /// </summary> public float Right => X + Width; /// <summary> /// Gets the y-coordinate of the top edge of this <see cref="RectangleF" />. /// </summary> public float Top => Y; /// <summary> /// Gets the y-coordinate of the bottom edge of this <see cref="RectangleF" />. /// </summary> public float Bottom => Y + Height; /// <summary> /// Gets a value indicating whether this <see cref="RectangleF" /> has a <see cref="X" />, <see cref="Y" />, /// <see cref="Width" />, /// <see cref="Height" /> all equal to <code>0.0f</code>. /// </summary> /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// </value> public bool IsEmpty => Width.Equals(0) && Height.Equals(0) && X.Equals(0) && Y.Equals(0); /// <summary> /// Gets the <see cref="Point2" /> representing the the top-left of this <see cref="RectangleF" />. /// </summary> public Point2 Position { get { return new Point2(X, Y); } set { X = value.X; Y = value.Y; } } /// <summary> /// Gets the <see cref="Size2" /> representing the extents of this <see cref="RectangleF" />. /// </summary> public Size2 Size { get { return new Size2(Width, Height); } set { Width = value.Width; Height = value.Height; } } /// <summary> /// Gets the <see cref="Point2" /> representing the center of this <see cref="RectangleF" />. /// </summary> public Point2 Center => new Point2(X + Width * 0.5f, Y + Height * 0.5f); /// <summary> /// Gets the <see cref="Point2" /> representing the top-left of this <see cref="RectangleF" />. /// </summary> public Point2 TopLeft => new Point2(X, Y); /// <summary> /// Gets the <see cref="Point2" /> representing the bottom-right of this <see cref="RectangleF" />. /// </summary> public Point2 BottomRight => new Point2(X + Width, Y + Height); /// <summary> /// Initializes a new instance of the <see cref="RectangleF" /> structure from the specified top-left xy-coordinate /// <see cref="float" />s, width <see cref="float" /> and height <see cref="float" />. /// </summary> /// <param name="x">The x-coordinate.</param> /// <param name="y">The y-coordinate.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> public RectangleF(float x, float y, float width, float height) { X = x; Y = y; Width = width; Height = height; } /// <summary> /// Initializes a new instance of the <see cref="RectangleF" /> structure from the specified top-left /// <see cref="Point2" /> and the extents <see cref="Size2" />. /// </summary> /// <param name="position">The top-left point.</param> /// <param name="size">The extents.</param> public RectangleF(Point2 position, Size2 size) { X = position.X; Y = position.Y; Width = size.Width; Height = size.Height; } /// <summary> /// Computes the <see cref="RectangleF" /> from a minimum <see cref="Point2" /> and maximum /// <see cref="Point2" />. /// </summary> /// <param name="minimum">The minimum point.</param> /// <param name="maximum">The maximum point.</param> /// <param name="result">The resulting rectangle.</param> public static void CreateFrom(Point2 minimum, Point2 maximum, out RectangleF result) { result.X = minimum.Y; result.Y = minimum.Y; result.Width = maximum.X - maximum.X; result.Height = maximum.Y - minimum.Y; } /// <summary> /// Computes the <see cref="RectangleF" /> from a minimum <see cref="Point2" /> and maximum /// <see cref="Point2" />. /// </summary> /// <param name="minimum">The minimum point.</param> /// <param name="maximum">The maximum point.</param> /// <returns>The resulting <see cref="RectangleF" />.</returns> public static RectangleF CreateFrom(Point2 minimum, Point2 maximum) { RectangleF result; CreateFrom(minimum, maximum, out result); return result; } /// <summary> /// Computes the <see cref="RectangleF" /> from a list of <see cref="Point2" /> structures. /// </summary> /// <param name="points">The points.</param> /// <param name="result">The resulting rectangle.</param> public static void CreateFrom(IReadOnlyList<Point2> points, out RectangleF result) { Point2 minimum; Point2 maximum; PrimitivesHelper.CreateRectangleFromPoints(points, out minimum, out maximum); CreateFrom(minimum, maximum, out result); } /// <summary> /// Computes the <see cref="RectangleF" /> from a list of <see cref="Point2" /> structures. /// </summary> /// <param name="points">The points.</param> /// <returns>The resulting <see cref="RectangleF" />.</returns> public static RectangleF CreateFrom(IReadOnlyList<Point2> points) { RectangleF result; CreateFrom(points, out result); return result; } /// <summary> /// Computes the <see cref="RectangleF" /> from the specified <see cref="RectangleF" /> transformed by /// the specified <see cref="Matrix2D" />. /// </summary> /// <param name="rectangle">The rectangle to be transformed.</param> /// <param name="transformMatrix">The transform matrix.</param> /// <param name="result">The resulting transformed rectangle.</param> /// <returns> /// The <see cref="BoundingRectangle" /> from the <paramref name="rectangle" /> transformed by the /// <paramref name="transformMatrix" />. /// </returns> /// <remarks> /// <para> /// If a transformed <see cref="BoundingRectangle" /> is used for <paramref name="rectangle" /> then the /// resulting <see cref="BoundingRectangle" /> will have the compounded transformation, which most likely is /// not desired. /// </para> /// </remarks> public static void Transform(ref RectangleF rectangle, ref Matrix2D transformMatrix, out RectangleF result) { var center = rectangle.Center; var halfExtents = (Vector2)rectangle.Size * 0.5f; PrimitivesHelper.TransformRectangle(ref center, ref halfExtents, ref transformMatrix); result.X = center.X - halfExtents.X; result.Y = center.Y - halfExtents.Y; result.Width = halfExtents.X * 2; result.Height = halfExtents.Y * 2; } /// <summary> /// Computes the <see cref="RectangleF" /> from the specified <see cref="BoundingRectangle" /> transformed by /// the /// specified <see cref="Matrix2D" />. /// </summary> /// <param name="rectangle">The bounding rectangle.</param> /// <param name="transformMatrix">The transform matrix.</param> /// <returns> /// The <see cref="BoundingRectangle" /> from the <paramref name="rectangle" /> transformed by the /// <paramref name="transformMatrix" />. /// </returns> /// <remarks> /// <para> /// If a transformed <see cref="BoundingRectangle" /> is used for <paramref name="rectangle" /> then the /// resulting <see cref="BoundingRectangle" /> will have the compounded transformation, which most likely is /// not desired. /// </para> /// </remarks> public static RectangleF Transform(RectangleF rectangle, ref Matrix2D transformMatrix) { RectangleF result; Transform(ref rectangle, ref transformMatrix, out result); return result; } /// <summary> /// Computes the <see cref="RectangleF" /> that contains the two specified /// <see cref="RectangleF" /> structures. /// </summary> /// <param name="first">The first rectangle.</param> /// <param name="second">The second rectangle.</param> /// <param name="result">The resulting rectangle that contains both the <paramref name="first" /> and the /// <paramref name="second" />.</param> public static void Union(ref RectangleF first, ref RectangleF second, out RectangleF result) { result.X = Math.Min(first.X, second.X); result.Y = Math.Min(first.Y, second.Y); result.Width = Math.Max(first.Right, second.Right) - result.X; result.Height = Math.Max(first.Bottom, second.Bottom) - result.Y; } /// <summary> /// Computes the <see cref="RectangleF" /> that contains the two specified /// <see cref="RectangleF" /> structures. /// </summary> /// <param name="first">The first rectangle.</param> /// <param name="second">The second rectangle.</param> /// <returns> /// An <see cref="RectangleF" /> that contains both the <paramref name="first" /> and the /// <paramref name="second" />. /// </returns> public static RectangleF Union(RectangleF first, RectangleF second) { RectangleF result; Union(ref first, ref second, out result); return result; } /// <summary> /// Computes the <see cref="RectangleF" /> that contains both the specified <see cref="RectangleF" /> and this <see cref="RectangleF" />. /// </summary> /// <param name="rectangle">The rectangle.</param> /// <returns> /// An <see cref="RectangleF" /> that contains both the <paramref name="rectangle" /> and /// this <see cref="RectangleF" />. /// </returns> public RectangleF Union(RectangleF rectangle) { RectangleF result; Union(ref this, ref rectangle, out result); return result; } /// <summary> /// Computes the <see cref="RectangleF" /> that is in common between the two specified /// <see cref="RectangleF" /> structures. /// </summary> /// <param name="first">The first rectangle.</param> /// <param name="second">The second rectangle.</param> /// <param name="result">The resulting rectangle that is in common between both the <paramref name="first" /> and /// the <paramref name="second" />, if they intersect; otherwise, <see cref="Empty"/>.</param> public static void Intersection(ref RectangleF first, ref RectangleF second, out RectangleF result) { var firstMinimum = first.TopLeft; var firstMaximum = first.BottomRight; var secondMinimum = second.TopLeft; var secondMaximum = second.BottomRight; var minimum = Point2.Maximum(firstMinimum, secondMinimum); var maximum = Point2.Minimum(firstMaximum, secondMaximum); if ((maximum.X < minimum.X) || (maximum.Y < minimum.Y)) result = new RectangleF(); else result = CreateFrom(minimum, maximum); } /// <summary> /// Computes the <see cref="RectangleF" /> that is in common between the two specified /// <see cref="RectangleF" /> structures. /// </summary> /// <param name="first">The first rectangle.</param> /// <param name="second">The second rectangle.</param> /// <returns> /// A <see cref="RectangleF" /> that is in common between both the <paramref name="first" /> and /// the <paramref name="second" />, if they intersect; otherwise, <see cref="Empty"/>. /// </returns> public static RectangleF Intersection(RectangleF first, RectangleF second) { RectangleF result; Intersection(ref first, ref second, out result); return result; } /// <summary> /// Computes the <see cref="RectangleF" /> that is in common between the specified /// <see cref="RectangleF" /> and this <see cref="RectangleF" />. /// </summary> /// <param name="rectangle">The rectangle.</param> /// <returns> /// A <see cref="RectangleF" /> that is in common between both the <paramref name="rectangle" /> and /// this <see cref="RectangleF"/>, if they intersect; otherwise, <see cref="Empty"/>. /// </returns> public RectangleF Intersection(RectangleF rectangle) { RectangleF result; Intersection(ref this, ref rectangle, out result); return result; } [Obsolete("RectangleF.Intersect() may be removed in the future. Use Intersection() instead.")] public static RectangleF Intersect(RectangleF value1, RectangleF value2) { RectangleF rectangle; Intersection(ref value1, ref value2, out rectangle); return rectangle; } [Obsolete("RectangleF.Intersect() may be removed in the future. Use Intersection() instead.")] public static void Intersect(ref RectangleF value1, ref RectangleF value2, out RectangleF result) { Intersection(ref value1, ref value2, out result); } /// <summary> /// Determines whether the two specified <see cref="RectangleF" /> structures intersect. /// </summary> /// <param name="first">The first rectangle.</param> /// <param name="second">The second rectangle.</param> /// <returns> /// <c>true</c> if the <paramref name="first" /> intersects with the <see cref="second" />; otherwise, <c>false</c>. /// </returns> public static bool Intersects(ref RectangleF first, ref RectangleF second) { return first.X < second.X + second.Width && first.X + first.Width > second.X && first.Y < second.Y + second.Height && first.Y + first.Height > second.Y; } /// <summary> /// Determines whether the two specified <see cref="RectangleF" /> structures intersect. /// </summary> /// <param name="first">The first rectangle.</param> /// <param name="second">The second rectangle.</param> /// <returns> /// <c>true</c> if the <paramref name="first" /> intersects with the <see cref="second" />; otherwise, <c>false</c>. /// </returns> public static bool Intersects(RectangleF first, RectangleF second) { return Intersects(ref first, ref second); } /// <summary> /// Determines whether the specified <see cref="RectangleF" /> intersects with this /// <see cref="RectangleF" />. /// </summary> /// <param name="rectangle">The bounding rectangle.</param> /// <returns> /// <c>true</c> if the <paramref name="rectangle" /> intersects with this /// <see cref="RectangleF" />; otherwise, /// <c>false</c>. /// </returns> public bool Intersects(RectangleF rectangle) { return Intersects(ref this, ref rectangle); } /// <summary> /// Determines whether the specified <see cref="RectangleF" /> contains the specified /// <see cref="Point2" />. /// </summary> /// <param name="rectangle">The rectangle.</param> /// <param name="point">The point.</param> /// <returns> /// <c>true</c> if the <paramref name="rectangle" /> contains the <paramref name="point" />; otherwise, /// <c>false</c>. /// </returns> public static bool Contains(ref RectangleF rectangle, ref Point2 point) { return rectangle.X <= point.X && point.X < rectangle.X + rectangle.Width && rectangle.Y <= point.Y && point.Y < rectangle.Y + rectangle.Height; } /// <summary> /// Determines whether the specified <see cref="RectangleF" /> contains the specified /// <see cref="Point2" />. /// </summary> /// <param name="rectangle">The rectangle.</param> /// <param name="point">The point.</param> /// <returns> /// <c>true</c> if the <paramref name="rectangle" /> contains the <paramref name="point" />; otherwise, /// <c>false</c>. /// </returns> public static bool Contains(RectangleF rectangle, Point2 point) { return Contains(ref rectangle, ref point); } /// <summary> /// Determines whether this <see cref="RectangleF" /> contains the specified /// <see cref="Point2" />. /// </summary> /// <param name="point">The point.</param> /// <returns> /// <c>true</c> if the this <see cref="RectangleF"/> contains the <paramref name="point" />; otherwise, /// <c>false</c>. /// </returns> public bool Contains(Point2 point) { return Contains(ref this, ref point); } /// <summary> /// Updates this <see cref="RectangleF" /> from a list of <see cref="Point2" /> structures. /// </summary> /// <param name="points">The points.</param> public void UpdateFromPoints(IReadOnlyList<Point2> points) { var rectangle = CreateFrom(points); X = rectangle.X; Y = rectangle.Y; Width = rectangle.Width; Height = rectangle.Height; } /// <summary> /// Computes the squared distance from this <see cref="RectangleF"/> to a <see cref="Point2"/>. /// </summary> /// <param name="point">The point.</param> /// <returns>The squared distance from this <see cref="RectangleF"/> to the <paramref name="point"/>.</returns> public float SquaredDistanceTo(Point2 point) { return PrimitivesHelper.SquaredDistanceToPointFromRectangle(TopLeft, BottomRight, point); } /// <summary> /// Computes the distance from this <see cref="RectangleF"/> to a <see cref="Point2"/>. /// </summary> /// <param name="point">The point.</param> /// <returns>The distance from this <see cref="RectangleF"/> to the <paramref name="point"/>.</returns> public float DistanceTo(Point2 point) { return (float)Math.Sqrt(SquaredDistanceTo(point)); } /// <summary> /// Computes the closest <see cref="Point2" /> on this <see cref="RectangleF" /> to a specified /// <see cref="Point2" />. /// </summary> /// <param name="point">The point.</param> /// <returns>The closest <see cref="Point2" /> on this <see cref="RectangleF" /> to the <paramref name="point" />.</returns> public Point2 ClosestPointTo(Point2 point) { Point2 result; PrimitivesHelper.ClosestPointToPointFromRectangle(TopLeft, BottomRight, point, out result); return result; } //TODO: Document this. public void Inflate(float horizontalAmount, float verticalAmount) { X -= horizontalAmount; Y -= verticalAmount; Width += horizontalAmount * 2; Height += verticalAmount * 2; } //TODO: Document this. public void Offset(float offsetX, float offsetY) { X += offsetX; Y += offsetY; } //TODO: Document this. public void Offset(Vector2 amount) { X += amount.X; Y += amount.Y; } /// <summary> /// Compares two <see cref="RectangleF" /> structures. The result specifies whether the values of the /// <see cref="X" />, <see cref="Y"/>, <see cref="Width"/> and <see cref="Height" /> fields of the two <see cref="RectangleF" /> structures /// are equal. /// </summary> /// <param name="first">The first rectangle.</param> /// <param name="second">The second rectangle.</param> /// <returns> /// <c>true</c> if the values of the /// <see cref="X" />, <see cref="Y"/>, <see cref="Width"/> and <see cref="Height" /> fields of the two <see cref="RectangleF" /> structures /// are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(RectangleF first, RectangleF second) { return first.Equals(ref second); } /// <summary> /// Compares two <see cref="RectangleF" /> structures. The result specifies whether the values of the /// <see cref="X" />, <see cref="Y"/>, <see cref="Width"/> and <see cref="Height" /> fields of the two <see cref="RectangleF" /> structures /// are unequal. /// </summary> /// <param name="first">The first rectangle.</param> /// <param name="second">The second rectangle.</param> /// <returns> /// <c>true</c> if the values of the /// <see cref="X" />, <see cref="Y"/>, <see cref="Width"/> and <see cref="Height" /> fields of the two <see cref="RectangleF" /> structures /// are unequal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(RectangleF first, RectangleF second) { return !(first == second); } /// <summary> /// Indicates whether this <see cref="RectangleF" /> is equal to another <see cref="RectangleF" />. /// </summary> /// <param name="rectangle">The rectangle.</param> /// <returns> /// <c>true</c> if this <see cref="RectangleF" /> is equal to the <paramref name="rectangle" />; otherwise, <c>false</c>. /// </returns> public bool Equals(RectangleF rectangle) { return Equals(ref rectangle); } /// <summary> /// Indicates whether this <see cref="RectangleF" /> is equal to another <see cref="RectangleF" />. /// </summary> /// <param name="rectangle">The rectangle.</param> /// <returns> /// <c>true</c> if this <see cref="RectangleF" /> is equal to the <paramref name="rectangle" />; otherwise, <c>false</c>. /// </returns> public bool Equals(ref RectangleF rectangle) { // ReSharper disable CompareOfFloatsByEqualityOperator return X == rectangle.X && Y == rectangle.Y && Width == rectangle.Width && Height == rectangle.Height; // ReSharper restore CompareOfFloatsByEqualityOperator } /// <summary> /// Returns a value indicating whether this <see cref="RectangleF" /> is equal to a specified object. /// </summary> /// <param name="obj">The object to make the comparison with.</param> /// <returns> /// <c>true</c> if this <see cref="RectangleF" /> is equal to <paramref name="obj" />; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return obj is RectangleF && Equals((RectangleF)obj); } /// <summary> /// Returns a hash code of this <see cref="RectangleF" /> suitable for use in hashing algorithms and data /// structures like a hash table. /// </summary> /// <returns> /// A hash code of this <see cref="RectangleF" />. /// </returns> public override int GetHashCode() { unchecked { var hashCode = X.GetHashCode(); hashCode = (hashCode * 397) ^ Y.GetHashCode(); hashCode = (hashCode * 397) ^ Width.GetHashCode(); hashCode = (hashCode * 397) ^ Height.GetHashCode(); return hashCode; } } /// <summary> /// Performs an implicit conversion from a <see cref="Rectangle" /> to a <see cref="RectangleF" />. /// </summary> /// <param name="rectangle">The rectangle.</param> /// <returns> /// The resulting <see cref="RectangleF" />. /// </returns> public static implicit operator RectangleF(Rectangle rectangle) { return new RectangleF { X = rectangle.X, Y = rectangle.Y, Width = rectangle.Width, Height = rectangle.Height }; } /// <summary> /// Performs an implicit conversion from a <see cref="Rectangle" /> to a <see cref="RectangleF" />. /// </summary> /// <param name="rectangle">The rectangle.</param> /// <returns> /// The resulting <see cref="RectangleF" />. /// </returns> /// <remarks> /// <para>A loss of precision may occur due to the truncation from <see cref="float" /> to <see cref="int" />.</para> /// </remarks> public static explicit operator Rectangle(RectangleF rectangle) { return new Rectangle((int)rectangle.X, (int)rectangle.Y, (int)rectangle.Width, (int)rectangle.Height); } /// <summary> /// Returns a <see cref="string" /> that represents this <see cref="RectangleF" />. /// </summary> /// <returns> /// A <see cref="string" /> that represents this <see cref="RectangleF" />. /// </returns> public override string ToString() { return $"{{X: {X}, Y: {Y}, Width: {Width}, Height: {Height}"; } internal string DebugDisplayString => string.Concat(X, " ", Y, " ", Width, " ", Height); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Threading; namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; using Apache.Geode.DUnitFramework; using Apache.Geode.Client.Tests; using Apache.Geode.Client; public class MyCqListener<TKey, TResult> : ICqListener<TKey, TResult> { #region Private members private bool m_failedOver = false; private UInt32 m_eventCountBefore = 0; private UInt32 m_errorCountBefore = 0; private UInt32 m_eventCountAfter = 0; private UInt32 m_errorCountAfter = 0; #endregion #region Public accessors public void failedOver() { m_failedOver = true; } public UInt32 getEventCountBefore() { return m_eventCountBefore; } public UInt32 getErrorCountBefore() { return m_errorCountBefore; } public UInt32 getEventCountAfter() { return m_eventCountAfter; } public UInt32 getErrorCountAfter() { return m_errorCountAfter; } #endregion public virtual void OnEvent(CqEvent<TKey, TResult> ev) { Util.Log("MyCqListener::OnEvent called"); if (m_failedOver == true) m_eventCountAfter++; else m_eventCountBefore++; //IGeodeSerializable val = ev.getNewValue(); //ICacheableKey key = ev.getKey(); TResult val = (TResult)ev.getNewValue(); /*ICacheableKey*/ TKey key = ev.getKey(); CqOperationType opType = ev.getQueryOperation(); //CacheableString keyS = key as CacheableString; string keyS = key.ToString(); //as string; Portfolio pval = val as Portfolio; PortfolioPdx pPdxVal = val as PortfolioPdx; Assert.IsTrue((pPdxVal != null) || (pval != null)); //string opStr = "DESTROY"; /*if (opType == CqOperationType.OP_TYPE_CREATE) opStr = "CREATE"; else if (opType == CqOperationType.OP_TYPE_UPDATE) opStr = "UPDATE";*/ //Util.Log("key {0}, value ({1},{2}), op {3}.", keyS, // pval.ID, pval.Pkid, opStr); } public virtual void OnError(CqEvent<TKey, TResult> ev) { Util.Log("MyCqListener::OnError called"); if (m_failedOver == true) m_errorCountAfter++; else m_errorCountBefore++; } public virtual void Close() { Util.Log("MyCqListener::close called"); } public virtual void Clear() { Util.Log("MyCqListener::Clear called"); m_eventCountBefore = 0; m_errorCountBefore = 0; m_eventCountAfter = 0; m_errorCountAfter = 0; } } public class MyCqListener1<TKey, TResult> : ICqListener<TKey, TResult> { public static UInt32 m_cntEvents = 0; public virtual void OnEvent(CqEvent<TKey, TResult> ev) { m_cntEvents++; Util.Log("MyCqListener1::OnEvent called"); Object val = (Object)ev.getNewValue(); Object pkey = (Object)ev.getKey(); int value = (int)val; int key = (int)pkey; CqOperationType opType = ev.getQueryOperation(); String opStr = "Default"; if (opType == CqOperationType.OP_TYPE_CREATE) opStr = "CREATE"; else if (opType == CqOperationType.OP_TYPE_UPDATE) opStr = "UPDATE"; Util.Log("MyCqListener1::OnEvent called with {0} , key = {1}, value = {2} ", opStr, key, value); } public virtual void OnError(CqEvent<TKey, TResult> ev) { Util.Log("MyCqListener1::OnError called"); } public virtual void Close() { Util.Log("MyCqListener1::close called"); } } public class MyCqStatusListener<TKey, TResult> : ICqStatusListener<TKey, TResult> { #region Private members private bool m_failedOver = false; private UInt32 m_eventCountBefore = 0; private UInt32 m_errorCountBefore = 0; private UInt32 m_eventCountAfter = 0; private UInt32 m_errorCountAfter = 0; private UInt32 m_CqConnectedCount = 0; private UInt32 m_CqDisConnectedCount = 0; #endregion #region Public accessors public MyCqStatusListener(int id) { } public void failedOver() { m_failedOver = true; } public UInt32 getEventCountBefore() { return m_eventCountBefore; } public UInt32 getErrorCountBefore() { return m_errorCountBefore; } public UInt32 getEventCountAfter() { return m_eventCountAfter; } public UInt32 getErrorCountAfter() { return m_errorCountAfter; } public UInt32 getCqConnectedCount() { return m_CqConnectedCount; } public UInt32 getCqDisConnectedCount() { return m_CqDisConnectedCount; } #endregion public virtual void OnEvent(CqEvent<TKey, TResult> ev) { Util.Log("MyCqStatusListener::OnEvent called"); if (m_failedOver == true) m_eventCountAfter++; else m_eventCountBefore++; TResult val = (TResult)ev.getNewValue(); TKey key = ev.getKey(); CqOperationType opType = ev.getQueryOperation(); string keyS = key.ToString(); //as string; } public virtual void OnError(CqEvent<TKey, TResult> ev) { Util.Log("MyCqStatusListener::OnError called"); if (m_failedOver == true) m_errorCountAfter++; else m_errorCountBefore++; } public virtual void Close() { Util.Log("MyCqStatusListener::close called"); } public virtual void OnCqConnected() { m_CqConnectedCount++; Util.Log("MyCqStatusListener::OnCqConnected called"); } public virtual void OnCqDisconnected() { m_CqDisConnectedCount++; Util.Log("MyCqStatusListener::OnCqDisconnected called"); } public virtual void Clear() { Util.Log("MyCqStatusListener::Clear called"); m_eventCountBefore = 0; m_errorCountBefore = 0; m_eventCountAfter = 0; m_errorCountAfter = 0; m_CqConnectedCount = 0; m_CqDisConnectedCount = 0; } } [TestFixture] [Category("group3")] [Category("unicast_only")] [Category("generics")] public class ThinClientCqTests : ThinClientRegionSteps { #region Private members private static bool m_usePdxObjects = false; private UnitProcess m_client1; private UnitProcess m_client2; private static string[] QueryRegionNames = { "Portfolios", "Positions", "Portfolios2", "Portfolios3" }; private static string QERegionName = "Portfolios"; private static string CqName = "MyCq"; private static string CqName1 = "testCQAllServersLeave"; private static string CqName2 = "testCQAllServersLeave1"; private static string CqQuery1 = "select * from /DistRegionAck"; private static string CqQuery2 = "select * from /DistRegionAck1"; //private static string CqName1 = "MyCq1"; #endregion protected override ClientBase[] GetClients() { m_client1 = new UnitProcess(); m_client2 = new UnitProcess(); return new ClientBase[] { m_client1, m_client2 }; } [TestFixtureSetUp] public override void InitTests() { base.InitTests(); m_client1.Call(InitClient); m_client2.Call(InitClient); } [TearDown] public override void EndTest() { CacheHelper.StopJavaServers(); base.EndTest(); } public void InitClient() { CacheHelper.Init(); try { Serializable.RegisterTypeGeneric(Portfolio.CreateDeserializable, CacheHelper.DCache); Serializable.RegisterTypeGeneric(Position.CreateDeserializable, CacheHelper.DCache); } catch (IllegalStateException) { // ignore since we run multiple iterations for pool and non pool configs } } public void StepOne(string locators) { CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[0], true, true, null, locators, "__TESTPOOL1_", true); CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[1], true, true, null, locators, "__TESTPOOL1_", true); CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[2], true, true, null, locators, "__TESTPOOL1_", true); CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[3], true, true, null, locators, "__TESTPOOL1_", true); CacheHelper.CreateTCRegion_Pool<object, object>("DistRegionAck", true, true, null, locators, "__TESTPOOL1_", true); IRegion<object, object> region = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]); Apache.Geode.Client.RegionAttributes<object, object> regattrs = region.Attributes; region.CreateSubRegion(QueryRegionNames[1], regattrs); } public void StepTwo(bool usePdxObject) { IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]); IRegion<object, object> subRegion0 = region0.GetSubRegion(QueryRegionNames[1]); IRegion<object, object> region1 = CacheHelper.GetRegion<object, object>(QueryRegionNames[1]); IRegion<object, object> region2 = CacheHelper.GetRegion<object, object>(QueryRegionNames[2]); IRegion<object, object> region3 = CacheHelper.GetRegion<object, object>(QueryRegionNames[3]); QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache); Util.Log("Object type is pdx = " + m_usePdxObjects); Util.Log("SetSize {0}, NumSets {1}.", qh.PortfolioSetSize, qh.PortfolioNumSets); if (!usePdxObject) { qh.PopulatePortfolioData(region0, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePositionData(subRegion0, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePositionData(region1, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePortfolioData(region2, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePortfolioData(region3, qh.PortfolioSetSize, qh.PortfolioNumSets); } else { Serializable.RegisterPdxType(PortfolioPdx.CreateDeserializable); Serializable.RegisterPdxType(PositionPdx.CreateDeserializable); qh.PopulatePortfolioPdxData(region0, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePortfolioPdxData(subRegion0, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePortfolioPdxData(region1, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePortfolioPdxData(region2, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePortfolioPdxData(region3, qh.PortfolioSetSize, qh.PortfolioNumSets); } } public void StepTwoQT() { IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]); IRegion<object, object> subRegion0 = region0.GetSubRegion(QueryRegionNames[1]); QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache); qh.PopulatePortfolioData(region0, 100, 20, 100); qh.PopulatePositionData(subRegion0, 100, 20); } public void StepOneQE(string locators) { CacheHelper.CreateTCRegion_Pool<object, object>(QERegionName, true, true, null, locators, "__TESTPOOL1_", true); IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(QERegionName); Portfolio p1 = new Portfolio(1, 100); Portfolio p2 = new Portfolio(2, 100); Portfolio p3 = new Portfolio(3, 100); Portfolio p4 = new Portfolio(4, 100); region["1"] = p1; region["2"] = p2; region["3"] = p3; region["4"] = p4; var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService(); CqAttributesFactory<object, object> cqFac = new CqAttributesFactory<object, object>(); ICqListener<object, object> cqLstner = new MyCqListener<object, object>(); cqFac.AddCqListener(cqLstner); CqAttributes<object, object> cqAttr = cqFac.Create(); CqQuery<object, object> qry = qs.NewCq(CqName, "select * from /" + QERegionName + " p where p.ID!=2", cqAttr, false); qry.Execute(); Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete region["4"] = p1; region["3"] = p2; region["2"] = p3; region["1"] = p4; Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete qry = qs.GetCq<object, object>(CqName); CqServiceStatistics cqSvcStats = qs.GetCqStatistics(); Assert.AreEqual(1, cqSvcStats.numCqsActive()); Assert.AreEqual(1, cqSvcStats.numCqsCreated()); Assert.AreEqual(1, cqSvcStats.numCqsOnClient()); cqAttr = qry.GetCqAttributes(); ICqListener<object, object>[] vl = cqAttr.getCqListeners(); Assert.IsNotNull(vl); Assert.AreEqual(1, vl.Length); cqLstner = vl[0]; Assert.IsNotNull(cqLstner); MyCqListener<object, object> myLisner = (MyCqListener<object, object>)cqLstner;// as MyCqListener<object, object>; Util.Log("event count:{0}, error count {1}.", myLisner.getEventCountBefore(), myLisner.getErrorCountBefore()); CqStatistics cqStats = qry.GetStatistics(); Assert.AreEqual(cqStats.numEvents(), myLisner.getEventCountBefore()); if (myLisner.getEventCountBefore() + myLisner.getErrorCountBefore() == 0) { Assert.Fail("cq before count zero"); } qry.Stop(); Assert.AreEqual(1, cqSvcStats.numCqsStopped()); qry.Close(); Assert.AreEqual(1, cqSvcStats.numCqsClosed()); // Bring down the region region.GetLocalView().DestroyRegion(); } public void StepOnePdxQE(string locators) { CacheHelper.CreateTCRegion_Pool<object, object>(QERegionName, true, true, null, locators, "__TESTPOOL1_", true); IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(QERegionName); PortfolioPdx p1 = new PortfolioPdx(1, 100); PortfolioPdx p2 = new PortfolioPdx(2, 100); PortfolioPdx p3 = new PortfolioPdx(3, 100); PortfolioPdx p4 = new PortfolioPdx(4, 100); region["1"] = p1; region["2"] = p2; region["3"] = p3; region["4"] = p4; var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService(); CqAttributesFactory<object, object> cqFac = new CqAttributesFactory<object, object>(); ICqListener<object, object> cqLstner = new MyCqListener<object, object>(); cqFac.AddCqListener(cqLstner); CqAttributes<object, object> cqAttr = cqFac.Create(); CqQuery<object, object> qry = qs.NewCq(CqName, "select * from /" + QERegionName + " p where p.ID!=2", cqAttr, false); qry.Execute(); Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete region["4"] = p1; region["3"] = p2; region["2"] = p3; region["1"] = p4; Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete qry = qs.GetCq<object, object>(CqName); CqServiceStatistics cqSvcStats = qs.GetCqStatistics(); Assert.AreEqual(1, cqSvcStats.numCqsActive()); Assert.AreEqual(1, cqSvcStats.numCqsCreated()); Assert.AreEqual(1, cqSvcStats.numCqsOnClient()); cqAttr = qry.GetCqAttributes(); ICqListener<object, object>[] vl = cqAttr.getCqListeners(); Assert.IsNotNull(vl); Assert.AreEqual(1, vl.Length); cqLstner = vl[0]; Assert.IsNotNull(cqLstner); MyCqListener<object, object> myLisner = (MyCqListener<object, object>)cqLstner;// as MyCqListener<object, object>; Util.Log("event count:{0}, error count {1}.", myLisner.getEventCountBefore(), myLisner.getErrorCountBefore()); CqStatistics cqStats = qry.GetStatistics(); Assert.AreEqual(cqStats.numEvents(), myLisner.getEventCountBefore()); if (myLisner.getEventCountBefore() + myLisner.getErrorCountBefore() == 0) { Assert.Fail("cq before count zero"); } qry.Stop(); Assert.AreEqual(1, cqSvcStats.numCqsStopped()); qry.Close(); Assert.AreEqual(1, cqSvcStats.numCqsClosed()); // Bring down the region region.GetLocalView().DestroyRegion(); } public void KillServer() { CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); } public delegate void KillServerDelegate(); /* public void StepOneFailover() { // This is here so that Client1 registers information of the cacheserver // that has been already started CacheHelper.SetupJavaServers("remotequery.xml", "cqqueryfailover.xml"); CacheHelper.StartJavaServer(1, "GFECS1"); Util.Log("Cacheserver 1 started."); CacheHelper.CreateTCRegion(QueryRegionNames[0], true, true, null, true); Region region = CacheHelper.GetVerifyRegion(QueryRegionNames[0]); Portfolio p1 = new Portfolio(1, 100); Portfolio p2 = new Portfolio(2, 200); Portfolio p3 = new Portfolio(3, 300); Portfolio p4 = new Portfolio(4, 400); region.Put("1", p1); region.Put("2", p2); region.Put("3", p3); region.Put("4", p4); } */ /* public void StepTwoFailover() { CacheHelper.StartJavaServer(2, "GFECS2"); Util.Log("Cacheserver 2 started."); IAsyncResult killRes = null; KillServerDelegate ksd = new KillServerDelegate(KillServer); CacheHelper.CreateTCRegion(QueryRegionNames[0], true, true, null, true); IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(QueryRegionNames[0]); var qs = CacheHelper.DCache.GetQueryService(); CqAttributesFactory cqFac = new CqAttributesFactory(); ICqListener cqLstner = new MyCqListener(); cqFac.AddCqListener(cqLstner); CqAttributes cqAttr = cqFac.Create(); CqQuery qry = qs.NewCq(CqName1, "select * from /" + QERegionName + " p where p.ID!<4", cqAttr, true); qry.Execute(); Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete qry = qs.GetCq(CqName1); cqAttr = qry.GetCqAttributes(); ICqListener[] vl = cqAttr.getCqListeners(); Assert.IsNotNull(vl); Assert.AreEqual(1, vl.Length); cqLstner = vl[0]; Assert.IsNotNull(cqLstner); MyCqListener myLisner = cqLstner as MyCqListener; if (myLisner.getEventCountAfter() + myLisner.getErrorCountAfter() != 0) { Assert.Fail("cq after count not zero"); } killRes = ksd.BeginInvoke(null, null); Thread.Sleep(18000); // sleep 0.3min to allow failover complete myLisner.failedOver(); Portfolio p1 = new Portfolio(1, 100); Portfolio p2 = new Portfolio(2, 200); Portfolio p3 = new Portfolio(3, 300); Portfolio p4 = new Portfolio(4, 400); region.Put("4", p1); region.Put("3", p2); region.Put("2", p3); region.Put("1", p4); Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete qry = qs.GetCq(CqName1); cqAttr = qry.GetCqAttributes(); vl = cqAttr.getCqListeners(); cqLstner = vl[0]; Assert.IsNotNull(vl); Assert.AreEqual(1, vl.Length); cqLstner = vl[0]; Assert.IsNotNull(cqLstner); myLisner = cqLstner as MyCqListener; if (myLisner.getEventCountAfter() + myLisner.getErrorCountAfter() == 0) { Assert.Fail("no cq after failover"); } killRes.AsyncWaitHandle.WaitOne(); ksd.EndInvoke(killRes); qry.Stop(); qry.Close(); } */ public void ProcessCQ(string locators) { CacheHelper.CreateTCRegion_Pool<object, object>(QERegionName, true, true, null, locators, "__TESTPOOL1_", true); IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(QERegionName); Portfolio p1 = new Portfolio(1, 100); Portfolio p2 = new Portfolio(2, 100); Portfolio p3 = new Portfolio(3, 100); Portfolio p4 = new Portfolio(4, 100); region["1"] = p1; region["2"] = p2; region["3"] = p3; region["4"] = p4; var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService(); CqAttributesFactory<object, object> cqFac = new CqAttributesFactory<object, object>(); ICqListener<object, object> cqLstner = new MyCqListener<object, object>(); ICqStatusListener<object, object> cqStatusLstner = new MyCqStatusListener<object, object>(1); ICqListener<object, object>[] v = new ICqListener<object, object>[2]; cqFac.AddCqListener(cqLstner); v[0] = cqLstner; v[1] = cqStatusLstner; cqFac.InitCqListeners(v); Util.Log("InitCqListeners called"); CqAttributes<object, object> cqAttr = cqFac.Create(); CqQuery<object, object> qry1 = qs.NewCq("CQ1", "select * from /" + QERegionName + " p where p.ID >= 1", cqAttr, false); qry1.Execute(); Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete region["4"] = p1; region["3"] = p2; region["2"] = p3; region["1"] = p4; Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete qry1 = qs.GetCq<object, object>("CQ1"); cqAttr = qry1.GetCqAttributes(); ICqListener<object, object>[] vl = cqAttr.getCqListeners(); Assert.IsNotNull(vl); Assert.AreEqual(2, vl.Length); cqLstner = vl[0]; Assert.IsNotNull(cqLstner); MyCqListener<object, object> myLisner = (MyCqListener<object, object>)cqLstner;// as MyCqListener<object, object>; Util.Log("event count:{0}, error count {1}.", myLisner.getEventCountBefore(), myLisner.getErrorCountBefore()); Assert.AreEqual(4, myLisner.getEventCountBefore()); cqStatusLstner = (ICqStatusListener<object, object>)vl[1]; Assert.IsNotNull(cqStatusLstner); MyCqStatusListener<object, object> myStatLisner = (MyCqStatusListener<object, object>)cqStatusLstner;// as MyCqStatusListener<object, object>; Util.Log("event count:{0}, error count {1}.", myStatLisner.getEventCountBefore(), myStatLisner.getErrorCountBefore()); Assert.AreEqual(1, myStatLisner.getCqConnectedCount()); Assert.AreEqual(4, myStatLisner.getEventCountBefore()); CqAttributesMutator<object, object> mutator = qry1.GetCqAttributesMutator(); mutator.RemoveCqListener(cqLstner); cqAttr = qry1.GetCqAttributes(); Util.Log("cqAttr.getCqListeners().Length = {0}", cqAttr.getCqListeners().Length); Assert.AreEqual(1, cqAttr.getCqListeners().Length); mutator.RemoveCqListener(cqStatusLstner); cqAttr = qry1.GetCqAttributes(); Util.Log("1 cqAttr.getCqListeners().Length = {0}", cqAttr.getCqListeners().Length); Assert.AreEqual(0, cqAttr.getCqListeners().Length); ICqListener<object, object>[] v2 = new ICqListener<object, object>[2]; v2[0] = cqLstner; v2[1] = cqStatusLstner; MyCqListener<object, object> myLisner2 = (MyCqListener<object, object>)cqLstner; myLisner2.Clear(); MyCqStatusListener<object, object> myStatLisner2 = (MyCqStatusListener<object, object>)cqStatusLstner; myStatLisner2.Clear(); mutator.SetCqListeners(v2); cqAttr = qry1.GetCqAttributes(); Assert.AreEqual(2, cqAttr.getCqListeners().Length); region["4"] = p1; region["3"] = p2; region["2"] = p3; region["1"] = p4; Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete qry1 = qs.GetCq<object, object>("CQ1"); cqAttr = qry1.GetCqAttributes(); ICqListener<object, object>[] v3 = cqAttr.getCqListeners(); Assert.IsNotNull(v3); Assert.AreEqual(2, vl.Length); cqLstner = v3[0]; Assert.IsNotNull(cqLstner); myLisner2 = (MyCqListener<object, object>)cqLstner;// as MyCqListener<object, object>; Util.Log("event count:{0}, error count {1}.", myLisner2.getEventCountBefore(), myLisner2.getErrorCountBefore()); Assert.AreEqual(4, myLisner2.getEventCountBefore()); cqStatusLstner = (ICqStatusListener<object, object>)v3[1]; Assert.IsNotNull(cqStatusLstner); myStatLisner2 = (MyCqStatusListener<object, object>)cqStatusLstner;// as MyCqStatusListener<object, object>; Util.Log("event count:{0}, error count {1}.", myStatLisner2.getEventCountBefore(), myStatLisner2.getErrorCountBefore()); Assert.AreEqual(0, myStatLisner2.getCqConnectedCount()); Assert.AreEqual(4, myStatLisner2.getEventCountBefore()); mutator = qry1.GetCqAttributesMutator(); mutator.RemoveCqListener(cqLstner); cqAttr = qry1.GetCqAttributes(); Util.Log("cqAttr.getCqListeners().Length = {0}", cqAttr.getCqListeners().Length); Assert.AreEqual(1, cqAttr.getCqListeners().Length); mutator.RemoveCqListener(cqStatusLstner); cqAttr = qry1.GetCqAttributes(); Util.Log("1 cqAttr.getCqListeners().Length = {0}", cqAttr.getCqListeners().Length); Assert.AreEqual(0, cqAttr.getCqListeners().Length); region["4"] = p1; region["3"] = p2; region["2"] = p3; region["1"] = p4; Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete qry1 = qs.GetCq<object, object>("CQ1"); cqAttr = qry1.GetCqAttributes(); ICqListener<object, object>[] v4 = cqAttr.getCqListeners(); Assert.IsNotNull(v4); Assert.AreEqual(0, v4.Length); Util.Log("cqAttr.getCqListeners() done"); } public void CreateAndExecuteCQ_StatusListener(string poolName, string cqName, string cqQuery, int id) { var qs = CacheHelper.DCache.GetPoolManager().Find(poolName).GetQueryService(); CqAttributesFactory<object, object> cqFac = new CqAttributesFactory<object, object>(); cqFac.AddCqListener(new MyCqStatusListener<object, object>(id)); CqAttributes<object, object> cqAttr = cqFac.Create(); CqQuery<object, object> qry = qs.NewCq(cqName, cqQuery, cqAttr, false); qry.Execute(); Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete } public void CreateAndExecuteCQ_Listener(string poolName, string cqName, string cqQuery, int id) { var qs = CacheHelper.DCache.GetPoolManager().Find(poolName).GetQueryService(); CqAttributesFactory<object, object> cqFac = new CqAttributesFactory<object, object>(); cqFac.AddCqListener(new MyCqListener<object, object>(/*id*/)); CqAttributes<object, object> cqAttr = cqFac.Create(); CqQuery<object, object> qry = qs.NewCq(cqName, cqQuery, cqAttr, false); qry.Execute(); Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete } public void CheckCQStatusOnConnect(string poolName, string cqName, int onCqStatusConnect) { var qs = CacheHelper.DCache.GetPoolManager().Find(poolName).GetQueryService(); CqQuery<object, object> query = qs.GetCq<object, object>(cqName); CqAttributes<object, object> cqAttr = query.GetCqAttributes(); ICqListener<object, object>[] vl = cqAttr.getCqListeners(); MyCqStatusListener<object, object> myCqStatusLstr = (MyCqStatusListener<object, object>) vl[0]; Util.Log("CheckCQStatusOnConnect = {0} ", myCqStatusLstr.getCqConnectedCount()); Assert.AreEqual(onCqStatusConnect, myCqStatusLstr.getCqConnectedCount()); } public void CheckCQStatusOnDisConnect(string poolName, string cqName, int onCqStatusDisConnect) { var qs = CacheHelper.DCache.GetPoolManager().Find(poolName).GetQueryService(); CqQuery<object, object> query = qs.GetCq<object, object>(cqName); CqAttributes<object, object> cqAttr = query.GetCqAttributes(); ICqListener<object, object>[] vl = cqAttr.getCqListeners(); MyCqStatusListener<object, object> myCqStatusLstr = (MyCqStatusListener<object, object>)vl[0]; Util.Log("CheckCQStatusOnDisConnect = {0} ", myCqStatusLstr.getCqDisConnectedCount()); Assert.AreEqual(onCqStatusDisConnect, myCqStatusLstr.getCqDisConnectedCount()); } public void PutEntries(string regionName) { IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName); for (int i = 1; i <= 10; i++) { region["key-" + i] = "val-" + i; } Thread.Sleep(18000); // sleep 0.3min to allow server c query to complete } public void CheckCQStatusOnPutEvent(string poolName, string cqName, int onCreateCount) { var qs = CacheHelper.DCache.GetPoolManager().Find(poolName).GetQueryService(); CqQuery<object, object> query = qs.GetCq<object, object>(cqName); CqAttributes<object, object> cqAttr = query.GetCqAttributes(); ICqListener<object, object>[] vl = cqAttr.getCqListeners(); MyCqStatusListener<object, object> myCqStatusLstr = (MyCqStatusListener<object, object>)vl[0]; Util.Log("CheckCQStatusOnPutEvent = {0} ", myCqStatusLstr.getEventCountBefore()); Assert.AreEqual(onCreateCount, myCqStatusLstr.getEventCountBefore()); } public void CreateRegion(string locators, string servergroup, string regionName, string poolName) { CacheHelper.CreateTCRegion_Pool<object, object>(regionName, true, true, null, locators, poolName, true, servergroup); } void runCqQueryTest() { CacheHelper.SetupJavaServers(true, "remotequeryN.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); m_client1.Call(StepOne, CacheHelper.Locators); Util.Log("StepOne complete."); m_client1.Call(StepTwo, m_usePdxObjects); Util.Log("StepTwo complete."); if (!m_usePdxObjects) m_client1.Call(StepOneQE, CacheHelper.Locators); else m_client1.Call(StepOnePdxQE, CacheHelper.Locators); Util.Log("StepOne complete."); m_client1.Call(Close); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator stopped"); } void runCqQueryStatusTest() { CacheHelper.SetupJavaServers(true, "cacheserver.xml", "cacheserver2.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); m_client1.Call(StepOne, CacheHelper.Locators); Util.Log("StepOne complete."); m_client1.Call(CreateAndExecuteCQ_StatusListener, "__TESTPOOL1_", CqName1, CqQuery1, 100); Util.Log("CreateAndExecuteCQ complete."); m_client1.Call(CheckCQStatusOnConnect, "__TESTPOOL1_", CqName1, 1); Util.Log("CheckCQStatusOnConnect complete."); m_client1.Call(PutEntries, "DistRegionAck"); Util.Log("PutEntries complete."); m_client1.Call(CheckCQStatusOnPutEvent, "__TESTPOOL1_", CqName1, 10); Util.Log("CheckCQStatusOnPutEvent complete."); CacheHelper.SetupJavaServers(true, "cacheserver.xml", "cacheserver2.xml"); CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1); Util.Log("start server 2 complete."); Thread.Sleep(20000); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); Thread.Sleep(20000); m_client1.Call(CheckCQStatusOnDisConnect, "__TESTPOOL1_", CqName1, 0); Util.Log("CheckCQStatusOnDisConnect complete."); CacheHelper.StopJavaServer(2); Util.Log("Cacheserver 2 stopped."); Thread.Sleep(20000); m_client1.Call(CheckCQStatusOnDisConnect, "__TESTPOOL1_", CqName1, 1); Util.Log("CheckCQStatusOnDisConnect complete."); CacheHelper.SetupJavaServers(true, "cacheserver.xml", "cacheserver2.xml"); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); Thread.Sleep(20000); m_client1.Call(CheckCQStatusOnConnect, "__TESTPOOL1_", CqName1, 2); Util.Log("CheckCQStatusOnConnect complete."); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); Thread.Sleep(20000); m_client1.Call(CheckCQStatusOnDisConnect, "__TESTPOOL1_", CqName1, 2); Util.Log("CheckCQStatusOnDisConnect complete."); m_client1.Call(Close); CacheHelper.StopJavaLocator(1); Util.Log("Locator stopped"); } void runCqQueryStatusTest2() { CacheHelper.SetupJavaServers(true, "cacheserver_servergroup.xml", "cacheserver_servergroup2.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("start server 1 complete."); CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1); Util.Log("start server 2 complete."); m_client1.Call(CreateRegion, CacheHelper.Locators, "group1", "DistRegionAck", "__TESTPOOL1_"); Util.Log("CreateRegion DistRegionAck complete."); m_client1.Call(CreateRegion, CacheHelper.Locators, "group2", "DistRegionAck1", "__TESTPOOL2_"); Util.Log("CreateRegion DistRegionAck1 complete."); m_client1.Call(CreateAndExecuteCQ_StatusListener, "__TESTPOOL1_", CqName1, CqQuery1, 100); Util.Log("CreateAndExecuteCQ1 complete."); m_client1.Call(CreateAndExecuteCQ_StatusListener, "__TESTPOOL2_", CqName2, CqQuery2, 101); Util.Log("CreateAndExecuteCQ2 complete."); m_client1.Call(CheckCQStatusOnConnect, "__TESTPOOL1_", CqName1, 1); Util.Log("CheckCQStatusOnConnect1 complete."); m_client1.Call(CheckCQStatusOnConnect, "__TESTPOOL2_", CqName2, 1); Util.Log("CheckCQStatusOnConnect2 complete."); m_client1.Call(PutEntries, "DistRegionAck"); Util.Log("PutEntries1 complete."); m_client1.Call(PutEntries, "DistRegionAck1"); Util.Log("PutEntries2 complete."); m_client1.Call(CheckCQStatusOnPutEvent, "__TESTPOOL1_", CqName1, 10); Util.Log("CheckCQStatusOnPutEvent complete."); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); Thread.Sleep(20000); m_client1.Call(CheckCQStatusOnDisConnect, "__TESTPOOL1_", CqName1, 1); Util.Log("CheckCQStatusOnDisConnect complete."); CacheHelper.StopJavaServer(2); Util.Log("Cacheserver 2 stopped."); Thread.Sleep(20000); m_client1.Call(CheckCQStatusOnDisConnect, "__TESTPOOL2_", CqName2, 1); Util.Log("CheckCQStatusOnDisConnect complete."); m_client1.Call(Close); CacheHelper.StopJavaLocator(1); Util.Log("Locator stopped"); } void runCqQueryStatusTest3() { CacheHelper.SetupJavaServers(true, "remotequeryN.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); m_client1.Call(ProcessCQ, CacheHelper.Locators); Util.Log("ProcessCQ complete."); m_client1.Call(Close); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator stopped"); } [Test] public void CqQueryTest() { runCqQueryTest(); } [Test] public void CqQueryPdxTest() { m_usePdxObjects = true; runCqQueryTest(); m_usePdxObjects = false; } // [Test] // public void CqFailover() // { // try // { // m_client1.Call(StepOneFailover); // Util.Log("StepOneFailover complete."); // // m_client1.Call(StepTwoFailover); // Util.Log("StepTwoFailover complete."); // } // finally // { // m_client1.Call(CacheHelper.StopJavaServers); // } // } [Test] public void CqQueryStatusTest() { runCqQueryStatusTest(); } [Test] public void CqQueryStatusTest2() { runCqQueryStatusTest2(); } [Test] public void CqQueryStatusTest3() { runCqQueryStatusTest3(); } } }
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 defence establishment, such as an army or navy base. /// </summary> public class DefenceEstablishment_Core : TypeCore, IGovernmentBuilding { public DefenceEstablishment_Core() { this._TypeId = 83; this._Id = "DefenceEstablishment"; this._Schema_Org_Url = "http://schema.org/DefenceEstablishment"; string label = ""; GetLabel(out label, "DefenceEstablishment", typeof(DefenceEstablishment_Core)); this._Label = label; this._Ancestors = new int[]{266,206,62,116}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{116}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,152}; } /// <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 basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <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> /// 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> /// 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> /// 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> /// 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> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <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 System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using RestWell.Client.Enums; using RestWell.Domain.Extensions; namespace RestWell.Client.Request { public class ProxyRequestBuilder : ProxyRequestBuilder<Missing, Missing> { #region Public Constructors public ProxyRequestBuilder(string baseUri, HttpRequestMethod requestMethod) : base(baseUri, requestMethod) { } public ProxyRequestBuilder(Uri baseUri, HttpRequestMethod requestMethod) : base(baseUri, requestMethod) { } #endregion Public Constructors } public class ProxyRequestBuilder<TResponseDto> : ProxyRequestBuilder<Missing, TResponseDto> { #region Public Constructors public ProxyRequestBuilder(string baseUri, HttpRequestMethod requestMethod) : base(baseUri, requestMethod) { } public ProxyRequestBuilder(Uri baseUri, HttpRequestMethod requestMethod) : base(baseUri, requestMethod) { } #endregion Public Constructors } public class ProxyRequestBuilder<TRequestDto, TResponseDto> { #region Private Fields private readonly Uri baseUri; private readonly Dictionary<string, List<string>> headers; private readonly List<string> pathArguments; private readonly Dictionary<string, List<object>> queryParameters; private readonly HttpRequestMethod requestMethod; private readonly List<string> routeAppendages; private TRequestDto requestDto; #endregion Private Fields #region Public Constructors public ProxyRequestBuilder(string baseUri, HttpRequestMethod requestMethod) { if (baseUri.IsNullOrEmptyOrWhitespace()) { throw new ArgumentException($"{nameof(baseUri)} must be a valid URI scheme (e.g. https://www.test.com/api"); } if (requestMethod == HttpRequestMethod.None) { throw new ArgumentException($"{nameof(requestMethod)} cannot be {HttpRequestMethod.None}. You must use a valid request type when using AsRequestType"); } this.baseUri = new Uri(baseUri); this.headers = new Dictionary<string, List<string>>(); this.pathArguments = new List<string>(); this.queryParameters = new Dictionary<string, List<object>>(); this.requestMethod = requestMethod; this.routeAppendages = new List<string>(); } public ProxyRequestBuilder(Uri baseUri, HttpRequestMethod requestMethod) : this(baseUri.ToString(), requestMethod) { } #endregion Public Constructors #region Public Methods public static ProxyRequestBuilder<TRequestDto, TResponseDto> CreateBuilder(string baseUri, HttpRequestMethod requestMethod) => new ProxyRequestBuilder<TRequestDto, TResponseDto>(baseUri, requestMethod); public static ProxyRequestBuilder<TRequestDto, TResponseDto> CreateBuilder(Uri baseUri, HttpRequestMethod requestMethod) => new ProxyRequestBuilder<TRequestDto, TResponseDto>(baseUri, requestMethod); /// <summary> /// Set/Modify the Accept Header /// </summary> /// <param name="mediaTypeValues">Accept header media type values (e.g. application/json)</param> /// <param name="mediaTypeValues">The media type values.</param> /// <returns>Reference to the current builder</returns> /// <exception cref="ArgumentException">mediaTypeValues</exception> public ProxyRequestBuilder<TRequestDto, TResponseDto> Accept(params string[] mediaTypeValues) { if (mediaTypeValues == null || mediaTypeValues.Length == 0) { throw new ArgumentException($"{nameof(mediaTypeValues)} was null or empty. You must specify media type values when using {nameof(Accept)}."); } return this.AddHeader("Accept", mediaTypeValues); } /// <summary> /// Add/Modify a header on the request. /// Note: This method does not restrict header modifications. Please ensure you follow proper standards. /// </summary> /// <param name="headerName">Name of the header to modify</param> /// <param name="values">Values for the header</param> /// <returns>Reference to the current builder</returns> /// <exception cref="ArgumentException">headerName or values</exception> public ProxyRequestBuilder<TRequestDto, TResponseDto> AddHeader(string headerName, params string[] values) { if (headerName.IsNullOrEmptyOrWhitespace()) { throw new ArgumentException($"{nameof(headerName)} was null or empty. You must specify a header name when using {nameof(AddHeader)}."); } if (values == null || values.Length == 0) { throw new ArgumentException($"{nameof(values)} was null or empty. You must specify header values when using {nameof(AddHeader)}"); } if (!this.headers.ContainsKey(headerName)) { this.headers.Add(headerName, new List<string>()); } this.headers[headerName].AddRange(values); return this; } /// <summary> /// Appends path arguments onto the request (e.g. https://www.test.com/api/pathArg/pathArg) /// </summary> /// <param name="pathArguments"> /// Must be an object with a valid ToString() which returns a value for the path argument. /// </param> /// <returns>Reference to the current builder</returns> /// <exception cref="ArgumentException">pathArguments</exception> public ProxyRequestBuilder<TRequestDto, TResponseDto> AddPathArguments(params object[] pathArguments) { if (pathArguments == null || pathArguments.Length == 0) { throw new ArgumentException($"{nameof(pathArguments)} was null or empty. You must specify path arguments when using {nameof(AddPathArguments)}"); } foreach (var argument in pathArguments) { this.pathArguments.Add(argument.ToString()); } return this; } /// <summary> /// Adds query parameters to be appeneded to the request URI (e.g. https://www.test.com/api?queryParam=value). /// </summary> /// <param name="queryParam">Must match the query parameter name.</param> /// <param name="value"> /// Must have a valid ToString() which returns a value for the query parameter. /// </param> /// <returns>Reference to the current builder</returns> /// <exception cref="ArgumentException">queryParam or value</exception> public ProxyRequestBuilder<TRequestDto, TResponseDto> AddQueryParameter(string queryParam, params object[] values) { if (queryParam.IsNullOrEmptyOrWhitespace()) { throw new ArgumentException($"{nameof(queryParam)} was null or empty. You must specify the query parameter when using {nameof(AddQueryParameter)}"); } if (values == null || values.Length == 0) { throw new ArgumentException($"{nameof(values)} was null or empty. You must specify the query parameter value when using {nameof(AddQueryParameter)}"); } if (!this.queryParameters.ContainsKey(queryParam)) { this.queryParameters.Add(queryParam, new List<object>()); } this.queryParameters[queryParam].AddRange(values); return this; } /// <summary> /// Appends a value to the current route /// </summary> /// <param name="appendage">A value you wish to append (e.g. www.test.com/api/appendage)</param> /// <returns>Reference to the current builder</returns> /// <exception cref="ArgumentException">appendages</exception> public ProxyRequestBuilder<TRequestDto, TResponseDto> AppendToRoute(params string[] appendages) { if (appendages == null || appendages.Length == 0) { throw new ArgumentException($"{nameof(appendages)} was null or empty. You must specify the appendage when using {nameof(AppendToRoute)}"); } this.routeAppendages.AddRange(appendages); return this; } /// <summary> /// Sets the authorization header of the request. /// </summary> /// <param name="scheme">The scheme you'd like to use (e.g. Bearer, Basic, etc.).</param> /// <param name="token">The authorization token (e.g. an api key).</param> /// <returns>Reference to the current builder</returns> /// <exception cref="ArgumentException">scheme or token</exception> public ProxyRequestBuilder<TRequestDto, TResponseDto> Authorization(string scheme, string token) { if (scheme.IsNullOrEmptyOrWhitespace()) { throw new ArgumentException($"{nameof(scheme)} was null or empty. You must specify a scheme when using {nameof(Authorization)}"); } if (token.IsNullOrEmptyOrWhitespace()) { throw new ArgumentException($"{nameof(token)} was null or empty. You must specify a token when using {nameof(Authorization)}"); } return this.AddHeader("Authorization", $"{scheme} {token}"); } /// <summary> /// Builds the proxy request. /// </summary> /// <returns>An IProxyRequest representing your request.</returns> public IProxyRequest<TRequestDto, TResponseDto> Build() { var routeBuilder = new StringBuilder(this.baseUri.ToString().TrimEnd('/')); routeBuilder = BuildRoute(routeBuilder, this.routeAppendages); routeBuilder = BuildRoute(routeBuilder, this.pathArguments); routeBuilder = BuildQueryParameters(routeBuilder, this.queryParameters); return new ProxyRequest<TRequestDto, TResponseDto>(this.headers) { HttpRequestMethod = this.requestMethod, RequestDto = this.requestDto, RequestUri = new Uri(routeBuilder.ToString()) }; } /// <summary> /// Sets the request body of the request. /// </summary> /// <param name="requestDto">A DTO which represents the request body</param> /// <returns>Reference to the current builder</returns> /// <exception cref="ArgumentException">requestDto</exception> public ProxyRequestBuilder<TRequestDto, TResponseDto> SetRequestDto(TRequestDto requestDto) { if (requestDto == null) { throw new ArgumentException($"{nameof(requestDto)} was null. You must specify a valid request DTO when using {nameof(SetRequestDto)}"); } this.requestDto = requestDto; return this; } #endregion Public Methods #region Private Methods private static StringBuilder BuildQueryParameters(StringBuilder requestBuilder, IDictionary<string, List<object>> queryParameters) { if (queryParameters.Any()) { requestBuilder.Append("?"); foreach (var queryParameter in queryParameters) { foreach (var value in queryParameter.Value) { requestBuilder.Append($"{queryParameter.Key}={value.ToString()}&"); } } } return new StringBuilder(requestBuilder.ToString().TrimEnd('&')); } private static StringBuilder BuildRoute(StringBuilder requestBuilder, IEnumerable<string> thingsToAppend) { if (thingsToAppend.Any()) { requestBuilder.Append("/"); foreach (var thingToAppend in thingsToAppend) { requestBuilder.Append($"{thingToAppend}/"); } } return new StringBuilder(requestBuilder.ToString().TrimEnd('/')); } #endregion Private Methods } }
using System; using System.Collections; using System.IO; using NUnit.Framework; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Pkix; using Org.BouncyCastle.Utilities.Collections; using Org.BouncyCastle.Utilities.Date; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.Test; using Org.BouncyCastle.X509; using Org.BouncyCastle.X509.Store; namespace Org.BouncyCastle.Tests { [TestFixture] public class CertPathValidatorTest : SimpleTest { private byte[] AC_PR = Base64.Decode( "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tDQpNSUlFU1RDQ0F6R2dBd0lC" + "QWdJQkJUQU5CZ2txaGtpRzl3MEJBUVVGQURDQnRERUxNQWtHQTFVRUJoTUNR" + "bEl4DQpFekFSQmdOVkJBb1RDa2xEVUMxQ2NtRnphV3d4UFRBN0JnTlZCQXNU" + "TkVsdWMzUnBkSFYwYnlCT1lXTnBiMjVoDQpiQ0JrWlNCVVpXTnViMnh2WjJs" + "aElHUmhJRWx1Wm05eWJXRmpZVzhnTFNCSlZFa3hFVEFQQmdOVkJBY1RDRUp5" + "DQpZWE5wYkdsaE1Rc3dDUVlEVlFRSUV3SkVSakV4TUM4R0ExVUVBeE1vUVhW" + "MGIzSnBaR0ZrWlNCRFpYSjBhV1pwDQpZMkZrYjNKaElGSmhhWG9nUW5KaGMy" + "bHNaV2x5WVRBZUZ3MHdNakEwTURReE9UTTVNREJhRncwd05UQTBNRFF5DQpN" + "elU1TURCYU1HRXhDekFKQmdOVkJBWVRBa0pTTVJNd0VRWURWUVFLRXdwSlEx" + "QXRRbkpoYzJsc01UMHdPd1lEDQpWUVFERXpSQmRYUnZjbWxrWVdSbElFTmxj" + "blJwWm1sallXUnZjbUVnWkdFZ1VISmxjMmxrWlc1amFXRWdaR0VnDQpVbVZ3" + "ZFdKc2FXTmhNSUlCSWpBTkJna3Foa2lHOXcwQkFRRUZBQU9DQVE4QU1JSUJD" + "Z0tDQVFFQXMwc0t5NGsrDQp6b016aldyMTQxeTVYQ045UGJMZERFQXN2cjZ4" + "Z0NCN1l5bEhIQ1NBYmpGR3dOQ0R5NlVxN1h0VjZ6UHdIMXpGDQpFWENlS3Jm" + "UUl5YXBXSEZ4V1VKajBMblFrY1RZM1FOR1huK0JuVk9EVTZDV3M1c3NoZktH" + "RXZyVlQ1Z214V1NmDQp4OFlsdDgzY1dwUE1QZzg3VDlCaHVIbHQzazh2M2Ev" + "NmRPbmF2dytOYTAyZExBaDBlNzZqcCtQUS9LK0pHZlBuDQphQjVVWURrZkd0" + "em5uTTNBV01tY3VJK0o0ek5OMDZaa3ZnbDFsdEo2UU1qcnZEUFlSak9ndDlT" + "cklpY1NmbEo4DQptVDdHWGRRaXJnQUNXc3g1QURBSklRK253TU1vNHlyTUtx" + "SlFhNFFDMHhhT0QvdkdVcG9SaDQzT0FTZFp3c3YvDQpPWFlybmVJeVAwVCs4" + "UUlEQVFBQm80RzNNSUcwTUQwR0ExVWRId1EyTURRd01xQXdvQzZHTEdoMGRI" + "QTZMeTloDQpZM0poYVhvdWFXTndZbkpoYzJsc0xtZHZkaTVpY2k5TVExSmhZ" + "M0poYVhvdVkzSnNNQklHQTFVZElBUUxNQWt3DQpCd1lGWUV3QkFRRXdIUVlE" + "VlIwT0JCWUVGREpUVFlKNE9TWVB5T09KZkVMZXhDaHppK2hiTUI4R0ExVWRJ" + "d1FZDQpNQmFBRklyNjhWZUVFUk0xa0VMNlYwbFVhUTJreFBBM01BNEdBMVVk" + "RHdFQi93UUVBd0lCQmpBUEJnTlZIUk1CDQpBZjhFQlRBREFRSC9NQTBHQ1Nx" + "R1NJYjNEUUVCQlFVQUE0SUJBUUJRUFNoZ1lidnFjaWV2SDVVb3ZMeXhkbkYr" + "DQpFcjlOeXF1SWNkMnZ3Y0N1SnpKMkQ3WDBUcWhHQ0JmUEpVVkdBVWorS0NP" + "SDFCVkgva1l1OUhsVHB1MGtKWFBwDQpBQlZkb2hJUERqRHhkbjhXcFFSL0Yr" + "ejFDaWtVcldIMDR4eTd1N1p6UUpLSlBuR0loY1FpOElyRm1PYkllMEc3DQpY" + "WTZPTjdPRUZxY21KTFFHWWdtRzFXMklXcytQd1JwWTdENGhLVEFoVjFSNkVv" + "amE1L3BPcmVDL09kZXlQWmVxDQo1SUZTOUZZZk02U0Npd2hrK3l2Q1FHbVo0" + "YzE5SjM0ZjVFYkRrK1NQR2tEK25EQ0E3L3VMUWNUMlJURE14SzBaDQpuZlo2" + "Nm1Sc0ZjcXRGaWdScjVFcmtKZDdoUVV6eHNOV0VrNzJEVUFIcVgvNlNjeWtt" + "SkR2V0plSUpqZlcNCi0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0NCg=="); private byte[] AC_RAIZ_ICPBRASIL = Base64.Decode( "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tDQpNSUlFdURDQ0E2Q2dBd0lC" + "QWdJQkJEQU5CZ2txaGtpRzl3MEJBUVVGQURDQnRERUxNQWtHQTFVRUJoTUNR" + "bEl4DQpFekFSQmdOVkJBb1RDa2xEVUMxQ2NtRnphV3d4UFRBN0JnTlZCQXNU" + "TkVsdWMzUnBkSFYwYnlCT1lXTnBiMjVoDQpiQ0JrWlNCVVpXTnViMnh2WjJs" + "aElHUmhJRWx1Wm05eWJXRmpZVzhnTFNCSlZFa3hFVEFQQmdOVkJBY1RDRUp5" + "DQpZWE5wYkdsaE1Rc3dDUVlEVlFRSUV3SkVSakV4TUM4R0ExVUVBeE1vUVhW" + "MGIzSnBaR0ZrWlNCRFpYSjBhV1pwDQpZMkZrYjNKaElGSmhhWG9nUW5KaGMy" + "bHNaV2x5WVRBZUZ3MHdNVEV4TXpBeE1qVTRNREJhRncweE1URXhNekF5DQpN" + "elU1TURCYU1JRzBNUXN3Q1FZRFZRUUdFd0pDVWpFVE1CRUdBMVVFQ2hNS1NV" + "TlFMVUp5WVhOcGJERTlNRHNHDQpBMVVFQ3hNMFNXNXpkR2wwZFhSdklFNWhZ" + "Mmx2Ym1Gc0lHUmxJRlJsWTI1dmJHOW5hV0VnWkdFZ1NXNW1iM0p0DQpZV05o" + "YnlBdElFbFVTVEVSTUE4R0ExVUVCeE1JUW5KaGMybHNhV0V4Q3pBSkJnTlZC" + "QWdUQWtSR01URXdMd1lEDQpWUVFERXloQmRYUnZjbWxrWVdSbElFTmxjblJw" + "Wm1sallXUnZjbUVnVW1GcGVpQkNjbUZ6YVd4bGFYSmhNSUlCDQpJakFOQmdr" + "cWhraUc5dzBCQVFFRkFBT0NBUThBTUlJQkNnS0NBUUVBd1BNdWR3WC9odm0r" + "VWgyYi9sUUFjSFZBDQppc2FtYUxrV2Rrd1A5L1MvdE9LSWdSckw2T3krWklH" + "bE9VZGQ2dVl0azlNYS8zcFVwZ2NmTkFqMHZZbTVnc3lqDQpRbzllbXNjK3g2" + "bTRWV3drOWlxTVpTQ0s1RVFrQXEvVXQ0bjdLdUxFMStnZGZ0d2RJZ3hmVXNQ" + "dDRDeU5yWTUwDQpRVjU3S00yVVQ4eDVycm16RWpyN1RJQ0dwU1VBbDJnVnFl" + "NnhhaWkrYm1ZUjFRcm1XYUJTQUc1OUxya3Jqcll0DQpiUmhGYm9VRGUxREsr" + "NlQ4czVMNms4Yzhva3BiSHBhOXZlTXp0RFZDOXNQSjYwTVdYaDZhblZLbzFV" + "Y0xjYlVSDQp5RWVOdlpuZVZSS0FBVTZvdXdkakR2d2xzYUt5ZEZLd2VkMFRv" + "UTQ3Ym1VS2djbSt3VjNlVFJrMzZVT25Ud0lEDQpBUUFCbzRIU01JSFBNRTRH" + "QTFVZElBUkhNRVV3UXdZRllFd0JBUUF3T2pBNEJnZ3JCZ0VGQlFjQ0FSWXNh" + "SFIwDQpjRG92TDJGamNtRnBlaTVwWTNCaWNtRnphV3d1WjI5MkxtSnlMMFJR" + "UTJGamNtRnBlaTV3WkdZd1BRWURWUjBmDQpCRFl3TkRBeW9EQ2dMb1lzYUhS" + "MGNEb3ZMMkZqY21GcGVpNXBZM0JpY21GemFXd3VaMjkyTG1KeUwweERVbUZq" + "DQpjbUZwZWk1amNtd3dIUVlEVlIwT0JCWUVGSXI2OFZlRUVSTTFrRUw2VjBs" + "VWFRMmt4UEEzTUE4R0ExVWRFd0VCDQovd1FGTUFNQkFmOHdEZ1lEVlIwUEFR" + "SC9CQVFEQWdFR01BMEdDU3FHU0liM0RRRUJCUVVBQTRJQkFRQVpBNWMxDQpV" + "L2hnSWg2T2NnTEFmaUpnRldwdm1EWldxbFYzMC9iSEZwajhpQm9iSlNtNXVE" + "cHQ3VGlyWWgxVXhlM2ZRYUdsDQpZakplKzl6ZCtpelBSYkJxWFBWUUEzNEVY" + "Y3drNHFwV3VmMWhIcmlXZmRyeDhBY3FTcXI2Q3VRRndTcjc1Rm9zDQpTemx3" + "REFEYTcwbVQ3d1pqQW1RaG5aeDJ4SjZ3ZldsVDlWUWZTLy9KWWVJYzdGdWUy" + "Sk5MZDAwVU9TTU1haUsvDQp0NzllbktOSEVBMmZ1cEgzdkVpZ2Y1RWg0YlZB" + "TjVWb2hyVG02TVk1M3g3WFFaWnIxTUU3YTU1bEZFblNlVDB1DQptbE9BalIy" + "bUFidlNNNVg1b1NaTnJtZXRkenlUajJmbENNOENDN01MYWIwa2tkbmdSSWxV" + "QkdIRjEvUzVubVBiDQpLKzlBNDZzZDMzb3FLOG44DQotLS0tLUVORCBDRVJU" + "SUZJQ0FURS0tLS0tDQo="); private byte[] schefer = Base64.Decode( "MIIEnDCCBAWgAwIBAgICIPAwDQYJKoZIhvcNAQEEBQAwgcAxCzAJBgNVBAYT" + "AkRFMQ8wDQYDVQQIEwZIRVNTRU4xGDAWBgNVBAcTDzY1MDA4IFdpZXNiYWRl" + "bjEaMBgGA1UEChMRU0NIVUZBIEhPTERJTkcgQUcxGjAYBgNVBAsTEVNDSFVG" + "QSBIT0xESU5HIEFHMSIwIAYDVQQDExlJbnRlcm5ldCBCZW51dHplciBTZXJ2" + "aWNlMSowKAYJKoZIhvcNAQkBFht6ZXJ0aWZpa2F0QHNjaHVmYS1vbmxpbmUu" + "ZGUwHhcNMDQwMzMwMTEwODAzWhcNMDUwMzMwMTEwODAzWjCBnTELMAkGA1UE" + "BhMCREUxCjAIBgNVBAcTASAxIzAhBgNVBAoTGlNIUyBJbmZvcm1hdGlvbnNz" + "eXN0ZW1lIEFHMRwwGgYDVQQLExM2MDAvMDU5NDktNjAwLzA1OTQ5MRgwFgYD" + "VQQDEw9TY2hldHRlciBTdGVmYW4xJTAjBgkqhkiG9w0BCQEWFlN0ZWZhbi5T" + "Y2hldHRlckBzaHMuZGUwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAJD0" + "95Bi76fkAMjJNTGPDiLPHmZXNsmakngDeS0juzKMeJA+TjXFouhYh6QyE4Bl" + "Nf18fT4mInlgLefwf4t6meIWbiseeTo7VQdM+YrbXERMx2uHsRcgZMsiMYHM" + "kVfYMK3SMJ4nhCmZxrBkoTRed4gXzVA1AA8YjjTqMyyjvt4TAgMBAAGjggHE" + "MIIBwDAJBgNVHRMEAjAAMBEGCWCGSAGG+EIBAQQEAwIEsDALBgNVHQ8EBAMC" + "BNAwOQYJYIZIAYb4QgENBCwWKlplcnRpZmlrYXQgbnVyIGZ1ZXIgU0NIVUZB" + "LU9ubGluZSBndWVsdGlnLjAdBgNVHQ4EFgQUXReirhBfg0Yhf6MsBWoo/nPa" + "hGwwge0GA1UdIwSB5TCB4oAUf2UyCaBV9JUeG9lS1Yo6OFBUdEKhgcakgcMw" + "gcAxCzAJBgNVBAYTAkRFMQ8wDQYDVQQIEwZIRVNTRU4xGDAWBgNVBAcTDzY1" + "MDA4IFdpZXNiYWRlbjEaMBgGA1UEChMRU0NIVUZBIEhPTERJTkcgQUcxGjAY" + "BgNVBAsTEVNDSFVGQSBIT0xESU5HIEFHMSIwIAYDVQQDExlJbnRlcm5ldCBC" + "ZW51dHplciBTZXJ2aWNlMSowKAYJKoZIhvcNAQkBFht6ZXJ0aWZpa2F0QHNj" + "aHVmYS1vbmxpbmUuZGWCAQAwIQYDVR0RBBowGIEWU3RlZmFuLlNjaGV0dGVy" + "QHNocy5kZTAmBgNVHRIEHzAdgRt6ZXJ0aWZpa2F0QHNjaHVmYS1vbmxpbmUu" + "ZGUwDQYJKoZIhvcNAQEEBQADgYEAWzZtN9XQ9uyrFXqSy3hViYwV751+XZr0" + "YH5IFhIS+9ixNAu8orP3bxqTaMhpwoU7T/oSsyGGSkb3fhzclgUADbA2lrOI" + "GkeB/m+FArTwRbwpqhCNTwZywOp0eDosgPjCX1t53BB/m/2EYkRiYdDGsot0" + "kQPOVGSjQSQ4+/D+TM8="); public override void PerformTest() { X509CertificateParser certParser = new X509CertificateParser(); X509CrlParser crlParser = new X509CrlParser(); // initialise CertStore X509Certificate rootCert = certParser.ReadCertificate(CertPathTest.rootCertBin); X509Certificate interCert = certParser.ReadCertificate(CertPathTest.interCertBin); X509Certificate finalCert = certParser.ReadCertificate(CertPathTest.finalCertBin); X509Crl rootCrl = crlParser.ReadCrl(CertPathTest.rootCrlBin); X509Crl interCrl = crlParser.ReadCrl(CertPathTest.interCrlBin); IList x509Certs = new ArrayList(); x509Certs.Add(rootCert); x509Certs.Add(interCert); x509Certs.Add(finalCert); IList x509Crls = new ArrayList(); x509Crls.Add(rootCrl); x509Crls.Add(interCrl); // CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list); // CertStore store = CertStore.GetInstance("Collection", ccsp); // X509CollectionStoreParameters ccsp = new X509CollectionStoreParameters(list); IX509Store x509CertStore = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(x509Certs)); IX509Store x509CrlStore = X509StoreFactory.Create( "CRL/Collection", new X509CollectionStoreParameters(x509Crls)); // NB: Month is 1-based in .NET DateTime validDate = new DateTime(2008,9,4,14,49,10).ToUniversalTime(); //validating path IList certchain = new ArrayList(); certchain.Add(finalCert); certchain.Add(interCert); // CertPath cp = CertificateFactory.GetInstance("X.509").GenerateCertPath(certchain); PkixCertPath cp = new PkixCertPath(certchain); ISet trust = new HashSet(); trust.Add(new TrustAnchor(rootCert, null)); // CertPathValidator cpv = CertPathValidator.GetInstance("PKIX"); PkixCertPathValidator cpv = new PkixCertPathValidator(); PkixParameters param = new PkixParameters(trust); param.AddStore(x509CertStore); param.AddStore(x509CrlStore); param.Date = new DateTimeObject(validDate); MyChecker checker = new MyChecker(); param.AddCertPathChecker(checker); PkixCertPathValidatorResult result = (PkixCertPathValidatorResult) cpv.Validate(cp, param); PkixPolicyNode policyTree = result.PolicyTree; IAsymmetricKeyParameter subjectPublicKey = result.SubjectPublicKey; if (checker.GetCount() != 2) { Fail("checker not evaluated for each certificate"); } if (!subjectPublicKey.Equals(finalCert.GetPublicKey())) { Fail("wrong public key returned"); } // // invalid path containing a valid one test // try { // initialise CertStore rootCert = certParser.ReadCertificate(AC_RAIZ_ICPBRASIL); interCert = certParser.ReadCertificate(AC_PR); finalCert = certParser.ReadCertificate(schefer); x509Certs = new ArrayList(); x509Certs.Add(rootCert); x509Certs.Add(interCert); x509Certs.Add(finalCert); // ccsp = new CollectionCertStoreParameters(list); // store = CertStore.GetInstance("Collection", ccsp); // ccsp = new X509CollectionStoreParameters(list); x509CertStore = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(x509Certs)); // NB: Month is 1-based in .NET validDate = new DateTime(2004,3,21,2,21,10).ToUniversalTime(); //validating path certchain = new ArrayList(); certchain.Add(finalCert); certchain.Add(interCert); // cp = CertificateFactory.GetInstance("X.509").GenerateCertPath(certchain); cp = new PkixCertPath(certchain); trust = new HashSet(); trust.Add(new TrustAnchor(rootCert, null)); // cpv = CertPathValidator.GetInstance("PKIX"); cpv = new PkixCertPathValidator(); param = new PkixParameters(trust); param.AddStore(x509CertStore); param.IsRevocationEnabled = false; param.Date = new DateTimeObject(validDate); result =(PkixCertPathValidatorResult) cpv.Validate(cp, param); policyTree = result.PolicyTree; subjectPublicKey = result.SubjectPublicKey; Fail("Invalid path validated"); } catch (Exception e) { if (e is PkixCertPathValidatorException && e.Message.StartsWith("Could not validate certificate signature.")) { return; } Fail("unexpected exception", e); } } public override string Name { get { return "CertPathValidator"; } } public static void Main( string[] args) { RunTest(new CertPathValidatorTest()); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } private class MyChecker : PkixCertPathChecker { private static int count; public override void Init(bool forward) { } public override bool IsForwardCheckingSupported() { return true; } public override ISet GetSupportedExtensions() { return null; } public override void Check(X509Certificate cert, ICollection unresolvedCritExts) { count++; } public int GetCount() { return count; } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using System; using System.Reflection; namespace OpenSim.Region.CoreModules.Avatar.Dialog { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "DialogModule")] public class DialogModule : IDialogModule, INonSharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected Scene m_scene; public void Initialise(IConfigSource source) { } public Type ReplaceableInterface { get { return null; } } public void AddRegion(Scene scene) { m_scene = scene; m_scene.RegisterModuleInterface<IDialogModule>(this); } public void RegionLoaded(Scene scene) { if (scene != m_scene) return; m_scene.AddCommand( "Users", this, "alert", "alert <message>", "Send an alert to everyone", HandleAlertConsoleCommand); m_scene.AddCommand( "Users", this, "alert-user", "alert-user <first> <last> <message>", "Send an alert to a user", HandleAlertConsoleCommand); } public void RemoveRegion(Scene scene) { if (scene != m_scene) return; m_scene.UnregisterModuleInterface<IDialogModule>(this); } public void Close() { } public string Name { get { return "Dialog Module"; } } public void SendAlertToUser(IClientAPI client, string message) { SendAlertToUser(client, message, false); } public void SendAlertToUser(IClientAPI client, string message, bool modal) { client.SendAgentAlertMessage(message, modal); } public void SendAlertToUser(UUID agentID, string message) { SendAlertToUser(agentID, message, false); } public void SendAlertToUser(UUID agentID, string message, bool modal) { ScenePresence sp = m_scene.GetScenePresence(agentID); if (sp != null) sp.ControllingClient.SendAgentAlertMessage(message, modal); } public void SendAlertToUser(string firstName, string lastName, string message, bool modal) { ScenePresence presence = m_scene.GetScenePresence(firstName, lastName); if (presence != null) { presence.ControllingClient.SendAgentAlertMessage(message, modal); } } public void SendGeneralAlert(string message) { m_scene.ForEachRootClient(delegate(IClientAPI client) { client.SendAlertMessage(message); }); } public void SendDialogToUser(UUID avatarID, string objectName, UUID objectID, UUID ownerID, string message, UUID textureID, int ch, string[] buttonlabels) { UserAccount account = m_scene.UserAccountService.GetUserAccount( m_scene.RegionInfo.ScopeID, ownerID); string ownerFirstName, ownerLastName; if (account != null) { ownerFirstName = account.FirstName; ownerLastName = account.LastName; } else { ownerFirstName = "(unknown"; ownerLastName = "user)"; } ScenePresence sp = m_scene.GetScenePresence(avatarID); if (sp != null) { sp.ControllingClient.SendDialog(objectName, objectID, ownerID, ownerFirstName, ownerLastName, message, textureID, ch, buttonlabels); } } public void SendUrlToUser(UUID avatarID, string objectName, UUID objectID, UUID ownerID, bool groupOwned, string message, string url) { ScenePresence sp = m_scene.GetScenePresence(avatarID); if (sp != null) { sp.ControllingClient.SendLoadURL(objectName, objectID, ownerID, groupOwned, message, url); } } public void SendTextBoxToUser(UUID avatarid, string message, int chatChannel, string name, UUID objectid, UUID ownerid) { UserAccount account = m_scene.UserAccountService.GetUserAccount( m_scene.RegionInfo.ScopeID, ownerid); string ownerFirstName, ownerLastName; UUID ownerID = UUID.Zero; if (account != null) { ownerFirstName = account.FirstName; ownerLastName = account.LastName; ownerID = account.PrincipalID; } else { ownerFirstName = "(unknown"; ownerLastName = "user)"; } ScenePresence sp = m_scene.GetScenePresence(avatarid); if (sp != null) { sp.ControllingClient.SendTextBoxRequest(message, chatChannel, name, ownerID, ownerFirstName, ownerLastName, objectid); } } public void SendNotificationToUsersInRegion(UUID fromAvatarID, string fromAvatarName, string message) { m_scene.ForEachRootClient(delegate(IClientAPI client) { client.SendBlueBoxMessage(fromAvatarID, fromAvatarName, message); }); } /// <summary> /// Handle an alert command from the console. /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> public void HandleAlertConsoleCommand(string module, string[] cmdparams) { if (m_scene.ConsoleScene() != null && m_scene.ConsoleScene() != m_scene) { return; } string message = string.Empty; if (cmdparams[0].ToLower().Equals("alert")) { message = CombineParams(cmdparams, 1); m_log.InfoFormat("[DIALOG]: Sending general alert in region {0} with message {1}", m_scene.RegionInfo.RegionName, message); SendGeneralAlert(message); } else if (cmdparams.Length > 3) { string firstName = cmdparams[1]; string lastName = cmdparams[2]; message = CombineParams(cmdparams, 3); m_log.InfoFormat("[DIALOG]: Sending alert in region {0} to {1} {2} with message {3}", m_scene.RegionInfo.RegionName, firstName, lastName, message); SendAlertToUser(firstName, lastName, message, false); } else { MainConsole.Instance.Output( "Usage: alert <message> | alert-user <first> <last> <message>"); return; } } private string CombineParams(string[] commandParams, int pos) { string result = string.Empty; for (int i = pos; i < commandParams.Length; i++) { result += commandParams[i] + " "; } return result; } } }
// 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 OrInt16() { var test = new SimpleBinaryOpTest__OrInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // 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(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__OrInt16 { private const int VectorSize = 32; private const int ElementCount = VectorSize / sizeof(Int16); private static Int16[] _data1 = new Int16[ElementCount]; private static Int16[] _data2 = new Int16[ElementCount]; private static Vector256<Int16> _clsVar1; private static Vector256<Int16> _clsVar2; private Vector256<Int16> _fld1; private Vector256<Int16> _fld2; private SimpleBinaryOpTest__DataTable<Int16> _dataTable; static SimpleBinaryOpTest__OrInt16() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__OrInt16() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Int16>(_data1, _data2, new Int16[ElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.Or( Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.Or( Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.Or( Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.Or( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr); var result = Avx2.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__OrInt16(); var result = Avx2.Or(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.Or(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Int16> left, Vector256<Int16> right, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[ElementCount]; Int16[] inArray2 = new Int16[ElementCount]; Int16[] outArray = new Int16[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[ElementCount]; Int16[] inArray2 = new Int16[ElementCount]; Int16[] outArray = new Int16[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { if ((short)(left[0] | right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if ((short)(left[i] | right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Or)}<Int16>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright Structured Solutions using System; using System.Collections.Generic; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml.Serialization; using BVSoftware.Bvc5.Core.Orders; using BVSoftware.Bvc5.Core.Shipping; using StructuredSolutions.Bvc5.Shipping; using StructuredSolutions.Bvc5.Shipping.Providers.Controls; using StructuredSolutions.Bvc5.Shipping.Providers.Packaging; using StructuredSolutions.Bvc5.Shipping.PostalCodes; using StructuredSolutions.Bvc5.Shipping.Providers.Settings; using ASPNET=System.Web.UI.WebControls; public partial class BVModules_Shipping_Package_Rules_PackagingRules : UserControl { #region Overrides /// <summary> /// Add script to the page that hides the import validation message when /// the dialog is closed. /// Also add script to perform client-side validation of the file import /// field (built in RequiredFieldValidator does not work). /// </summary> /// <param name="e"></param> protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); String script = String.Format( @"function hideImportPackagingDialogValidation(type, args) {{ el = document.getElementById('{0}'); if (typeof(el) != 'undefined' && el != null) {{ el.style.display = 'none'; }} }} ", ImportPackagingUploadRequired.ClientID); Page.ClientScript.RegisterStartupScript(GetType(), script, script, true); script = String.Format( @"function validateImportPackagingUpload(source, args) {{ el = document.getElementById('{0}'); if (typeof(el) != 'undefined' && el != null) {{ args.IsValid = (el.value != null && el.value.length > 0); el = document.getElementById(source.id); el.style.display = args.IsValid ? 'none' : 'inline'; }} }} ", ImportPackagingUpload.ClientID); Page.ClientScript.RegisterStartupScript(GetType(), script, script, true); } #endregion #region Properties protected PackageRuleProviderSettings Settings { get { return ((PackageRulesEditor) NamingContainer).Settings; } } #endregion #region Event Handlers protected void Export_Click(object sender, EventArgs e) { Response.Clear(); Response.ContentType = "text/xml"; Response.AddHeader("Content-Disposition", "attachment;filename=Packaging.rules"); XmlSerializer serializer = new XmlSerializer(typeof (PackagingRuleList)); serializer.Serialize(Response.OutputStream, Settings.PackagingRules); Response.End(); } protected void Import_Click(object sender, EventArgs e) { if (Page.IsValid) { XmlSerializer serializer = new XmlSerializer(typeof (PackagingRule[])); try { PackagingRule[] rules = serializer.Deserialize(ImportPackagingUpload.FileContent) as PackagingRule[]; if (rules != null) { Settings.PackagingRules.Clear(); foreach (PackagingRule rule in rules) Settings.PackagingRules.Add(rule); Settings.PackagingRules.Save(); DataBind(); } } catch { ImportPackagingUploadRequired.Text = "<br />Invalid file format<br />"; ImportPackagingUploadRequired.IsValid = false; RedisplayImportPackagingDialog(); } } } protected void ImportPackagingUploadRequired_ServerValidate(object source, ServerValidateEventArgs e) { e.IsValid = ImportPackagingUpload.HasFile; if (!e.IsValid) { ImportPackagingUploadRequired.Text = "<br />Please select a rules file<br />"; RedisplayImportPackagingDialog(); } } protected void SamplePackages_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridView grid = (GridView) sender; grid.DataSource = Session["SamplePackagesData"]; grid.PageIndex = e.NewPageIndex; grid.DataBind(); } protected void PackagingRules_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "MoveDown") { String id = e.CommandArgument.ToString(); Int32 index = Settings.PackagingRules.IndexOf(id); PackagingRule packagingRule = Settings.PackagingRules[index]; Settings.PackagingRules.RemoveAt(index); Settings.PackagingRules.Insert(index + 1, packagingRule); Settings.PackagingRules.Save(); PackagingRules.DataBind(); } else if (e.CommandName == "MoveUp") { String id = e.CommandArgument.ToString(); Int32 index = Settings.PackagingRules.IndexOf(id); PackagingRule packagingRule = Settings.PackagingRules[index]; Settings.PackagingRules.RemoveAt(index); Settings.PackagingRules.Insert(index - 1, packagingRule); Settings.PackagingRules.Save(); PackagingRules.DataBind(); } else if (e.CommandName == "New") { // Create the default packaging rule PackagingRule packagingRule = new PackagingRule(); packagingRule.Limits.Add(new PackageMatch()); // Add or insert the settings into the list String id = e.CommandArgument.ToString(); Int32 index = Settings.PackagingRules.IndexOf(id); Settings.PackagingRules.Insert(index + 1, packagingRule); Settings.PackagingRules.Save(); PackagingRules.DataBind(); PackagingRules.EditIndex = index + 1; Page.Items["PackagingRules"] = packagingRule; } else if (e.CommandName == "Update") { if (Page.IsValid) { GridViewRow row = PackagingRules.Rows[PackagingRules.EditIndex]; if (Page.IsValid) { if (row != null) { PackageMatchList matches = ((BVModules_Shipping_Package_Rules_PackageMatchEditor) row.FindControl("PackageMatchEditor")).GetMatches(); foreach (PackageMatch match in matches) { if (match.PackageProperty == PackageProperties.Distance) { if (PostalCode.IsPostalDataInstalled()) { Anthem.Manager.AddScriptForClientSideEval("alert('No postal code data has been installed. The Distance property will always return -1.');"); break; } } } Page.Items["Limits"] = matches; } } } } else if (e.CommandName == "View") { if (Page.IsValid) { GridViewRow row = PackagingRules.Rows[PackagingRules.EditIndex]; if (row != null) { GridView grid = row.FindControl("SamplePackages") as GridView; if (grid != null) { Int32 count; grid.Visible = true; Session["SamplePackagesData"] = GetSamplePackages(row, out count); grid.DataSource = Session["SamplePackagesData"]; grid.DataBind(); if (count > grid.PageSize*5) { grid.Caption = string.Format("This rule would create {0}+ packages", grid.PageSize*5); } else { grid.Caption = string.Format("This rule would create {0} package", count); if (count == 0 || count > 1) grid.Caption += "s"; } grid.Caption += " from your existing orders"; } } } } } protected void PackagingRules_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { Int32 rowIndex = (PackagingRules.PageIndex*PackagingRules.PageSize) + e.Row.RowIndex; if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate) { if (rowIndex == Settings.PackagingRules.Count - 1) { e.Row.FindControl("PackagingRuleMoveDown").Visible = false; } if (rowIndex == 0) { e.Row.FindControl("PackagingRuleMoveUp").Visible = false; } } } } protected void PackagingRulesDataSource_Deleting(object sender, ObjectDataSourceMethodEventArgs e) { e.InputParameters["settings"] = Settings; } protected void PackagingRulesDataSource_Selecting(object sender, ObjectDataSourceSelectingEventArgs e) { e.InputParameters["settings"] = Settings; } protected void PackagingRulesDataSource_Updating(object sender, ObjectDataSourceMethodEventArgs e) { if (Page.IsValid) { e.InputParameters["settings"] = Settings; e.InputParameters["limits"] = Page.Items["Limits"]; } else { e.Cancel = true; } } #endregion #region Methods private List<SamplePackageResult> GetSamplePackages(Control row, out int count) { GridView grid = (GridView) row.FindControl("SamplePackages"); PackagingRule rule = new PackagingRule(); rule.BoxHeight = decimal.Parse(((TextBox)row.FindControl("HeightField")).Text); rule.BoxLength = decimal.Parse(((TextBox)row.FindControl("LengthField")).Text); rule.BoxWidth = decimal.Parse(((TextBox)row.FindControl("WidthField")).Text); rule.Limits.AddRange( ((BVModules_Shipping_Package_Rules_PackageMatchEditor) row.FindControl("PackageMatchEditor")).GetMatches()); rule.Name = ((TextBox)row.FindControl("NameField")).Text.Trim(); rule.TareWeight = decimal.Parse(((TextBox)row.FindControl("TareWeightField")).Text); Packager packager = new Packager(rule); count = 0; // Scan all placed orders List<SamplePackageResult> results = new List<SamplePackageResult>(); int rowCount = 0; foreach (Order order in Order.FindByCriteria(new OrderSearchCriteria(), -1, grid.PageSize * 5, ref rowCount)) { Order heavyOrder = Order.FindByBvin(order.Bvin); // "Unship" all of the items so that the samples look like they // were just placed. Skip any orders with deleted items. bool skipOrder = false; foreach (LineItem lineitem in heavyOrder.Items) { if (lineitem.AssociatedProduct == null || lineitem.AssociatedProduct.ShippingMode == ShippingMode.None) skipOrder = true; else lineitem.QuantityShipped = 0; } if (skipOrder) break; ExtendedShippingGroupList groups = new ExtendedShippingGroupList(); foreach (ShippingGroup group in heavyOrder.GetShippingGroups()) { groups.Add(new ExtendedShippingGroup(0, group, group.Items)); } foreach (ExtendedShippingGroup group in groups) { ExtendedShippingGroupList splitGroups = packager.Split(group); List<String> remainingItems = new List<string>(); SamplePackageResult result; Boolean matchingPackage = false; foreach (ExtendedShippingGroup splitGroup in splitGroups) { if (splitGroup.Name.Equals(rule.Name)) { matchingPackage = true; count += 1; result = new SamplePackageResult(); result.OrderNumber = order.OrderNumber; result.OrderDisplay = string.Format("<a href=\"{0}\" target=\"order\">{1}</a>", Page.ResolveUrl( string.Format("~/BVAdmin/Orders/ViewOrder.aspx?id={0}", order.Bvin)), order.OrderNumber); List<string> matchValues = new List<string>(); List<string> limitValues = new List<string>(); for (int index = 0; index < rule.Limits.Count; index++) { PackageMatch match = rule.Limits[index]; string matchValue = PackagePropertiesHelper.GetPackagePropertyValue(splitGroup, match.PackageProperty, match.ItemProperty, match.CustomProperty, "1").ToString(); if (string.IsNullOrEmpty(matchValue)) matchValue = "(empty)"; matchValues.Add(matchValue); string limitValue = PackagePropertiesHelper.GetPackagePropertyValue(splitGroup, match.LimitPackageProperty, match.LimitItemProperty, match.LimitCustomProperty, match.Limit).ToString(); if (string.IsNullOrEmpty(limitValue)) limitValue = "(empty)"; limitValues.Add(limitValue); } result.MatchValues = string.Join(", ", matchValues.ToArray()); result.LimitValues = string.Join(", ", limitValues.ToArray()); result.Volume = splitGroup.GetShippingVolume().ToString("0.000"); result.Weight = splitGroup.GetShippingWeight().ToString("0.000"); if (splitGroup.HasBoxDimensions) { decimal boxVolume = splitGroup.BoxHeight * splitGroup.BoxLength * splitGroup.BoxWidth; result.FillFactor = string.Format("{0:0.000}%", splitGroup.GetShippingVolume() * 100M / boxVolume); } else { result.FillFactor = "n/a"; } List<string> lineitems = new List<string>(); foreach (LineItem lineitem in splitGroup.Items) { lineitems.Add(string.Format("{0:0} &times; {1}", lineitem.Quantity, lineitem.ProductSku)); } result.Items = string.Join(", ", lineitems.ToArray()); results.Add(result); } else { foreach (LineItem lineitem in splitGroup.Items) { remainingItems.Add(string.Format("{0:0} &times; {1}", lineitem.Quantity, lineitem.ProductSku)); } } if (count > grid.PageSize * 5) break; } // If there was at least one matching package, then list the unmatched items if (matchingPackage && (remainingItems.Count > 0)) { result = new SamplePackageResult(); result.OrderNumber = order.OrderNumber; result.OrderDisplay = string.Format("<a href=\"{0}\" target=\"order\">{1}</a>", Page.ResolveUrl( string.Format("~/BVAdmin/Orders/ViewOrder.aspx?id={0}", order.Bvin)), order.OrderNumber); result.MatchValues = "unpackaged items"; result.Items = string.Join(", ", remainingItems.ToArray()); results.Add(result); } } if (count > grid.PageSize*5) break; } results.Sort(); return results; } private void RedisplayImportPackagingDialog() { Page.ClientScript.RegisterStartupScript(GetType(), "showImportPackagingDialog", "YAHOO.util.Event.addListener(window, \"load\", showImportPackagingDialog);", true); } #endregion #region Private Classes [Serializable] private class SamplePackageResult : IComparable { private String _fillFactor = String.Empty; public String FillFactor { get { return _fillFactor; } set { _fillFactor = value; } } private String _items = String.Empty; public String Items { get { return _items; } set { _items = value; } } private String _limitValues = String.Empty; public String LimitValues { get { return _limitValues; } set { _limitValues = value; } } private String _matchValues = String.Empty; public String MatchValues { get { return _matchValues; } set { _matchValues = value; } } private String _orderDisplay = String.Empty; public String OrderDisplay { get { return _orderDisplay; } set { _orderDisplay = value; } } private String _orderNumber = String.Empty; public String OrderNumber { get { return _orderNumber; } set { _orderNumber = value; } } private String _remainingItems = String.Empty; public String RemainingItems { get { return _remainingItems; } set { _remainingItems = value; } } private String _volume = String.Empty; public String Volume { get { return _volume; } set { _volume = value; } } private String _weight = String.Empty; public String Weight { get { return _weight; } set { _weight = value; } } #region IComparable Members public int CompareTo(object obj) { if (obj == null) throw new ArgumentNullException("obj"); SamplePackageResult result = obj as SamplePackageResult; if (result == null) throw new ArgumentException("obj must be a SamplePackageResult."); return String.Compare(OrderNumber, result.OrderNumber, true); } #endregion } #endregion }
namespace Argus.Drawing.Video.Vfw { using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; /// <summary> /// Reading AVI files using Video for Windows /// </summary> /// <remarks> /// This code was a free example found through the AForge project. This Vfw Win32 API's are stable and old but also /// marked as obsolete which means that they may not work in future versions of Windows. They currently work and have /// been tested through Windows 7. If these do not work in the future then they should be marked obselete here and /// DirectShow should instead be used. These however (if no codecs are used) are included with Windows and don't need /// another Framework (DirectX/DirectShow) to be installed). /// </remarks> public class AVIReader : IDisposable { private IntPtr file; private IntPtr stream; private IntPtr getFrame; private int width; private int height; private int position; private int start; private int length; private float rate; private string codec; /// <summary> /// The width of the AVI file. /// </summary> public int Width { get { return width; } } /// <summary> /// The height of the AVI file. /// </summary> public int Height { get { return height; } } /// <summary> /// The frame rate or frames per second (fps) of the AVI file. /// </summary> public float FrameRate { get { return rate; } } /// <summary> /// The current position in the AVI file. /// </summary> public int CurrentPosition { get { return position; } set { if ((value < start) || (value >= start + length)) position = start; else position = value; } } /// <summary> /// The length of the AVI file. /// </summary> public int Length { get { return length; } } /// <summary> /// The string codec associated with the AVI file. /// </summary> public string Codec { get { return codec; } } /// <summary> /// Contructor /// </summary> public AVIReader() { Win32.AVIFileInit(); } /// <summary> /// Desctructor /// </summary> ~AVIReader() { Dispose(false); } /// <summary> /// Dispose, Free all unmanaged resources /// </summary> public void Dispose() { Dispose(true); // Remove me from the Finalization queue GC.SuppressFinalize(this); } /// <summary> /// Dispose, Free all unmanaged resources /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { if (disposing) { // Dispose managed resources // there is nothing managed yet } Close(); Win32.AVIFileExit(); } /// <summary> /// Open an AVI file /// </summary> /// <param name="fname"></param> public void Open(string fname) { // close previous file Close(); // open file if (Win32.AVIFileOpen(out file, fname, Win32.OpenFileMode.ShareDenyWrite, IntPtr.Zero) != 0) throw new ApplicationException("Failed opening file"); // get first video stream if (Win32.AVIFileGetStream(file, out stream, Win32.mmioFOURCC("vids"), 0) != 0) throw new ApplicationException("Failed getting video stream"); // get stream info Win32.AVISTREAMINFO info = new Win32.AVISTREAMINFO(); Win32.AVIStreamInfo(stream, ref info, Marshal.SizeOf(info)); width = info.rcFrame.right; height = info.rcFrame.bottom; position = info.dwStart; start = info.dwStart; length = info.dwLength; rate = (float) info.dwRate / (float) info.dwScale; codec = Win32.decode_mmioFOURCC(info.fccHandler); // prepare decompressor Win32.BITMAPINFOHEADER bih = new Win32.BITMAPINFOHEADER(); bih.biSize = Marshal.SizeOf(bih.GetType()); bih.biWidth = width; bih.biHeight = height; bih.biPlanes = 1; bih.biBitCount = 24; bih.biCompression = 0; // BI_RGB // get frame open object if ((getFrame = Win32.AVIStreamGetFrameOpen(stream, ref bih)) == IntPtr.Zero) { bih.biHeight = -height; if ((getFrame = Win32.AVIStreamGetFrameOpen(stream, ref bih)) == IntPtr.Zero) throw new ApplicationException("Failed initializing decompressor"); } } /// <summary> /// Close the AVI file /// </summary> public void Close() { // release frame open object if (getFrame != IntPtr.Zero) { Win32.AVIStreamGetFrameClose(getFrame); getFrame = IntPtr.Zero; } // release stream if (stream != IntPtr.Zero) { Win32.AVIStreamRelease(stream); stream = IntPtr.Zero; } // release file if (file != IntPtr.Zero) { Win32.AVIFileRelease(file); file = IntPtr.Zero; } } /// <summary> /// Get next video frame /// </summary> /// <returns></returns> public Bitmap GetNextFrame() { // get frame at specified position IntPtr pdib = Win32.AVIStreamGetFrame(getFrame, position); if (pdib == IntPtr.Zero) throw new ApplicationException("Failed getting frame"); Win32.BITMAPINFOHEADER bih; // copy BITMAPINFOHEADER from unmanaged memory bih = (Win32.BITMAPINFOHEADER) Marshal.PtrToStructure(pdib, typeof(Win32.BITMAPINFOHEADER)); // create new bitmap Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb); // lock bitmap data BitmapData bmData = bmp.LockBits( new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); // copy image data int srcStride = bmData.Stride; // width * 3; int dstStride = bmData.Stride; // check image direction if (bih.biHeight > 0) { // it`s a bottom-top image int dst = bmData.Scan0.ToInt32() + dstStride * (height - 1); int src = pdib.ToInt32() + Marshal.SizeOf(typeof(Win32.BITMAPINFOHEADER)); for (int y = 0; y < height; y++) { Win32.memcpy(dst, src, srcStride); dst -= dstStride; src += srcStride; } } else { // it`s a top bootom image int dst = bmData.Scan0.ToInt32(); int src = pdib.ToInt32() + Marshal.SizeOf(typeof(Win32.BITMAPINFOHEADER)); if (srcStride != dstStride) { // copy line by line for (int y = 0; y < height; y++) { Win32.memcpy(dst, src, srcStride); dst += dstStride; src += srcStride; } } else { // copy the whole image Win32.memcpy(dst, src, srcStride * height); } } // unlock bitmap data bmp.UnlockBits(bmData); position++; return bmp; } } }
using DataBox.Tests.Helpers; using Microsoft.Azure.Management.DataBox; using Microsoft.Azure.Management.DataBox.Models; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Management.Resources.Models; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Xunit; using Xunit.Abstractions; namespace DataBox.Tests.Tests { public class JobCRUDTests : DataBoxTestBase { public JobCRUDTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) { } [Fact] public void TestJobCRUDOperations() { var resourceGroupName = TestUtilities.GenerateName("SdkRg"); var jobName = TestUtilities.GenerateName("SdkJob"); ContactDetails contactDetails = GetDefaultContactDetails(); ShippingAddress shippingAddress = GetDefaultShippingAddress(); Sku sku = GetDefaultSku(); var destinationAccountsList = GetDestinationAccountsList(); JobDetails jobDetails = new DataBoxJobDetails { ContactDetails = contactDetails, ShippingAddress = shippingAddress }; jobDetails.DataImportDetails = new List<DataImportDetails>(); jobDetails.DataImportDetails.Add(new DataImportDetails(destinationAccountsList.FirstOrDefault())); var jobResource = new JobResource { Sku = sku, Location = TestConstants.DefaultResourceLocation, Details = jobDetails }; this.RMClient.ResourceGroups.CreateOrUpdate( resourceGroupName, new ResourceGroup { Location = TestConstants.DefaultResourceLocation }); var job = this.Client.Jobs.Create(resourceGroupName, jobName, jobResource); ValidateJobWithoutDetails(jobName, sku, job); Assert.Equal(StageName.DeviceOrdered, job.Status); var getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details); ValidateJobWithoutDetails(jobName, sku, getJob); ValidateJobDetails(contactDetails, shippingAddress, getJob, JobDeliveryType.NonScheduled); Assert.Equal(StageName.DeviceOrdered, job.Status); contactDetails.ContactName = "Update Job"; getJob.Details.ContactDetails = contactDetails; var Details = new UpdateJobDetails { ContactDetails = getJob.Details.ContactDetails, ShippingAddress = getJob.Details.ShippingAddress }; var updateParams = new JobResourceUpdateParameter { Details = Details }; var updateJob = this.Client.Jobs.Update(resourceGroupName, jobName, updateParams); ValidateJobWithoutDetails(jobName, sku, updateJob); Assert.Equal(StageName.DeviceOrdered, updateJob.Status); getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details); ValidateJobWithoutDetails(jobName, sku, getJob); ValidateJobDetails(contactDetails, shippingAddress, getJob, JobDeliveryType.NonScheduled); Assert.Equal(StageName.DeviceOrdered, getJob.Status); var jobList = this.Client.Jobs.List(); Assert.NotNull(jobList); jobList = this.Client.Jobs.ListByResourceGroup(resourceGroupName); Assert.NotNull(jobList); this.Client.Jobs.Cancel(resourceGroupName, jobName, "CancelTest"); getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details); Assert.Equal(StageName.Cancelled, getJob.Status); while (!string.IsNullOrWhiteSpace(getJob.Details.ContactDetails.ContactName)) { Wait(TimeSpan.FromMinutes(5)); getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details); } this.Client.Jobs.Delete(resourceGroupName, jobName); } [Fact] public void TestScheduledJob() { var resourceGroupName = TestUtilities.GenerateName("SdkRg"); var jobName = TestUtilities.GenerateName("SdkJob"); ContactDetails contactDetails = GetDefaultContactDetails(); ShippingAddress shippingAddress = GetDefaultShippingAddress(); Sku sku = GetDefaultSku(); var destinationAccountsList = GetDestinationAccountsList(); JobDetails jobDetails = new DataBoxJobDetails { ContactDetails = contactDetails, ShippingAddress = shippingAddress, }; jobDetails.DataImportDetails = new List<DataImportDetails>(); jobDetails.DataImportDetails.Add(new DataImportDetails(destinationAccountsList.FirstOrDefault())); var jobResource = new JobResource { Sku = sku, Location = TestConstants.DefaultResourceLocation, Details = jobDetails, DeliveryType = JobDeliveryType.Scheduled, DeliveryInfo = new JobDeliveryInfo { ScheduledDateTime = DateTime.UtcNow.AddDays(20) } }; this.RMClient.ResourceGroups.CreateOrUpdate( resourceGroupName, new ResourceGroup { Location = TestConstants.DefaultResourceLocation }); var job = this.Client.Jobs.Create(resourceGroupName, jobName, jobResource); ValidateJobWithoutDetails(jobName, sku, job); Assert.Equal(StageName.DeviceOrdered, job.Status); var getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details); ValidateJobWithoutDetails(jobName, sku, getJob); ValidateJobDetails(contactDetails, shippingAddress, getJob, JobDeliveryType.Scheduled); Assert.Equal(StageName.DeviceOrdered, job.Status); contactDetails.ContactName = "Update Job"; getJob.Details.ContactDetails = contactDetails; var Details = new UpdateJobDetails { ContactDetails = getJob.Details.ContactDetails, ShippingAddress = getJob.Details.ShippingAddress }; var updateParams = new JobResourceUpdateParameter { Details = Details }; var updateJob = this.Client.Jobs.Update(resourceGroupName, jobName, updateParams); ValidateJobWithoutDetails(jobName, sku, updateJob); Assert.Equal(StageName.DeviceOrdered, updateJob.Status); getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details); ValidateJobWithoutDetails(jobName, sku, getJob); ValidateJobDetails(contactDetails, shippingAddress, getJob, JobDeliveryType.Scheduled); Assert.Equal(StageName.DeviceOrdered, getJob.Status); var jobList = this.Client.Jobs.List(); Assert.NotNull(jobList); jobList = this.Client.Jobs.ListByResourceGroup(resourceGroupName); Assert.NotNull(jobList); this.Client.Jobs.Cancel(resourceGroupName, jobName, "CancelTest"); getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details); Assert.Equal(StageName.Cancelled, getJob.Status); while (!string.IsNullOrWhiteSpace(getJob.Details.ContactDetails.ContactName)) { Wait(TimeSpan.FromMinutes(5)); getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details); } this.Client.Jobs.Delete(resourceGroupName, jobName); } [Fact] public void TestExportJobCRUDOperations() { var resourceGroupName = TestUtilities.GenerateName("SdkRg"); var jobName = TestUtilities.GenerateName("SdkJob"); ContactDetails contactDetails = GetDefaultContactDetails(); ShippingAddress shippingAddress = GetDefaultShippingAddress(); Sku sku = GetDefaultSku(); var sourceAccountsList = GetSourceAccountsList(); JobDetails jobDetails = new DataBoxJobDetails { ContactDetails = contactDetails, ShippingAddress = shippingAddress }; jobDetails.DataExportDetails = new List<DataExportDetails>(); TransferConfiguration transferCofiguration = new TransferConfiguration { TransferConfigurationType = TransferConfigurationType.TransferAll, TransferAllDetails = new TransferConfigurationTransferAllDetails { Include = new TransferAllDetails { DataAccountType = DataAccountType.StorageAccount, TransferAllBlobs = true, TransferAllFiles = true } } }; jobDetails.DataExportDetails.Add(new DataExportDetails(transferCofiguration, sourceAccountsList.FirstOrDefault())); var jobResource = new JobResource { Sku = sku, Location = TestConstants.DefaultResourceLocation, Details = jobDetails, TransferType = TransferType.ExportFromAzure }; this.RMClient.ResourceGroups.CreateOrUpdate( resourceGroupName, new ResourceGroup { Location = TestConstants.DefaultResourceLocation }); var job = this.Client.Jobs.Create(resourceGroupName, jobName, jobResource); ValidateJobWithoutDetails(jobName, sku, job); Assert.Equal(StageName.DeviceOrdered, job.Status); var getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details); ValidateJobWithoutDetails(jobName, sku, getJob); ValidateJobDetails(contactDetails, shippingAddress, getJob, JobDeliveryType.NonScheduled); Assert.Equal(StageName.DeviceOrdered, job.Status); contactDetails.ContactName = "Update Job"; getJob.Details.ContactDetails = contactDetails; var Details = new UpdateJobDetails { ContactDetails = getJob.Details.ContactDetails, ShippingAddress = getJob.Details.ShippingAddress }; var updateParams = new JobResourceUpdateParameter { Details = Details }; var updateJob = this.Client.Jobs.Update(resourceGroupName, jobName, updateParams); ValidateJobWithoutDetails(jobName, sku, updateJob); Assert.Equal(StageName.DeviceOrdered, updateJob.Status); getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details); ValidateJobWithoutDetails(jobName, sku, getJob); ValidateJobDetails(contactDetails, shippingAddress, getJob, JobDeliveryType.NonScheduled); Assert.Equal(StageName.DeviceOrdered, getJob.Status); var jobList = this.Client.Jobs.List(); Assert.NotNull(jobList); jobList = this.Client.Jobs.ListByResourceGroup(resourceGroupName); Assert.NotNull(jobList); this.Client.Jobs.Cancel(resourceGroupName, jobName, "CancelTest"); getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details); Assert.Equal(StageName.Cancelled, getJob.Status); while (!string.IsNullOrWhiteSpace(getJob.Details.ContactDetails.ContactName)) { Wait(TimeSpan.FromMinutes(5)); getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details); } this.Client.Jobs.Delete(resourceGroupName, jobName); } [Fact] public void DevicePasswordTest() { var resourceGroupName = TestUtilities.GenerateName("SdkRg"); var jobName = TestUtilities.GenerateName("SdkJob"); //var jobName = "SdkJob5929"; ContactDetails contactDetails = GetDefaultContactDetails(); ShippingAddress shippingAddress = GetDefaultShippingAddress(); Sku sku = GetDefaultSku(); var destinationAccountsList = new List<StorageAccountDetails> { new StorageAccountDetails { StorageAccountId = "/subscriptions/fa68082f-8ff7-4a25-95c7-ce9da541242f/resourceGroups/databoxbvt1/providers/Microsoft.Storage/storageAccounts/databoxbvttestaccount2" } }; destinationAccountsList[0].SharePassword = "Abcd223@22344Abcd223@22344"; JobDetails jobDetails = new DataBoxJobDetails { ContactDetails = contactDetails, ShippingAddress = shippingAddress, DevicePassword = "Abcd223@22344" }; jobDetails.DataImportDetails = new List<DataImportDetails>(); jobDetails.DataImportDetails.Add(new DataImportDetails(destinationAccountsList.FirstOrDefault())); var jobResource = new JobResource { Sku = sku, Location = TestConstants.DefaultResourceLocation, Details = jobDetails, }; this.RMClient.ResourceGroups.CreateOrUpdate( resourceGroupName, new ResourceGroup { Location = TestConstants.DefaultResourceLocation }); var job = this.Client.Jobs.Create(resourceGroupName, jobName, jobResource); var getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details); ValidateJobWithoutDetails(jobName, sku, job); ValidateJobDetails(contactDetails, shippingAddress, getJob, JobDeliveryType.NonScheduled); Assert.Equal(StageName.DeviceOrdered, job.Status); } [Fact] public void CmkEnablementTest() { var resourceGroupName = TestUtilities.GenerateName("SdkRg"); var jobName = TestUtilities.GenerateName("SdkJob"); //var jobName = "SdkJob5929"; ContactDetails contactDetails = GetDefaultContactDetails(); ShippingAddress shippingAddress = GetDefaultShippingAddress(); Sku sku = GetDefaultSku(); var destinationAccountsList = new List<StorageAccountDetails> { new StorageAccountDetails { StorageAccountId = "/subscriptions/fa68082f-8ff7-4a25-95c7-ce9da541242f/resourceGroups/databoxbvt1/providers/Microsoft.Storage/storageAccounts/databoxbvttestaccount2" } }; JobDetails jobDetails = new DataBoxJobDetails { ContactDetails = contactDetails, ShippingAddress = shippingAddress }; jobDetails.DataImportDetails = new List<DataImportDetails>(); jobDetails.DataImportDetails.Add(new DataImportDetails(destinationAccountsList.FirstOrDefault())); var jobResource = new JobResource { Sku = sku, Location = TestConstants.DefaultResourceLocation, Details = jobDetails, }; this.RMClient.ResourceGroups.CreateOrUpdate( resourceGroupName, new ResourceGroup { Location = TestConstants.DefaultResourceLocation }); var job = this.Client.Jobs.Create(resourceGroupName, jobName, jobResource); ValidateJobWithoutDetails(jobName, sku, job); Assert.Equal(StageName.DeviceOrdered, job.Status); // Set Msi details. string tenantId = "72f988bf-86f1-41af-91ab-2d7cd011db47"; string identityType = "SystemAssigned"; var identity = new ResourceIdentity(identityType, Guid.NewGuid().ToString(), tenantId); var updateParams = new JobResourceUpdateParameter { Identity = identity }; var updateJob = this.Client.Jobs.Update(resourceGroupName, jobName, updateParams); ValidateJobWithoutDetails(jobName, sku, updateJob); var getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details); ValidateJobWithoutDetails(jobName, sku, job); ValidateJobDetails(contactDetails, shippingAddress, getJob, JobDeliveryType.NonScheduled); Assert.Equal(StageName.DeviceOrdered, updateJob.Status); Assert.Equal(identityType, updateJob.Identity.Type); var keyEncryptionKey = new KeyEncryptionKey(KekType.CustomerManaged) { KekUrl = @"https://sdkkeyvault.vault.azure.net/keys/SSDKEY/", KekVaultResourceID = "/subscriptions/fa68082f-8ff7-4a25-95c7-ce9da541242f/resourceGroups/akvenkat/providers/Microsoft.KeyVault/vaults/SDKKeyVault" }; var details = new UpdateJobDetails { KeyEncryptionKey = keyEncryptionKey }; updateParams = new JobResourceUpdateParameter { Details = details }; updateJob = this.Client.Jobs.Update(resourceGroupName, jobName, updateParams); ValidateJobWithoutDetails(jobName, sku, updateJob); getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details); ValidateJobDetails(contactDetails, shippingAddress, getJob, JobDeliveryType.NonScheduled); Assert.Equal(StageName.DeviceOrdered, updateJob.Status); Assert.Equal(KekType.CustomerManaged, getJob.Details.KeyEncryptionKey.KekType); } [Fact] public void DoubleEncryptionTest() { var resourceGroupName = TestUtilities.GenerateName("SdkRg"); var jobName = TestUtilities.GenerateName("SdkJob"); ContactDetails contactDetails = GetDefaultContactDetails(); ShippingAddress shippingAddress = GetDefaultShippingAddress(); Preferences preferences = new Preferences { EncryptionPreferences = new EncryptionPreferences { DoubleEncryption = DoubleEncryption.Enabled } }; Sku sku = GetDefaultSku(); var destinationAccountsList = GetDestinationAccountsList(); JobDetails jobDetails = new DataBoxJobDetails { ContactDetails = contactDetails, ShippingAddress = shippingAddress, Preferences=preferences }; jobDetails.DataImportDetails = new List<DataImportDetails>(); jobDetails.DataImportDetails.Add(new DataImportDetails(destinationAccountsList.FirstOrDefault())); var jobResource = new JobResource { Sku = sku, Location = TestConstants.DefaultResourceLocation, Details = jobDetails }; this.RMClient.ResourceGroups.CreateOrUpdate( resourceGroupName, new ResourceGroup { Location = TestConstants.DefaultResourceLocation }); var job = this.Client.Jobs.Create(resourceGroupName, jobName, jobResource); ValidateJobWithoutDetails(jobName, sku, job); Assert.Equal(StageName.DeviceOrdered, job.Status); var getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details); ValidateJobWithoutDetails(jobName, sku, getJob); ValidateJobDetails(contactDetails, shippingAddress, getJob, JobDeliveryType.NonScheduled); Assert.Equal(StageName.DeviceOrdered, job.Status); Assert.Equal(DoubleEncryption.Enabled, getJob.Details.Preferences.EncryptionPreferences.DoubleEncryption); contactDetails.ContactName = "Update Job"; getJob.Details.ContactDetails = contactDetails; var Details = new UpdateJobDetails { ContactDetails = getJob.Details.ContactDetails, ShippingAddress = getJob.Details.ShippingAddress }; var updateParams = new JobResourceUpdateParameter { Details = Details }; var updateJob = this.Client.Jobs.Update(resourceGroupName, jobName, updateParams); ValidateJobWithoutDetails(jobName, sku, updateJob); Assert.Equal(StageName.DeviceOrdered, updateJob.Status); getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details); ValidateJobWithoutDetails(jobName, sku, getJob); ValidateJobDetails(contactDetails, shippingAddress, getJob, JobDeliveryType.NonScheduled); Assert.Equal(StageName.DeviceOrdered, getJob.Status); var jobList = this.Client.Jobs.List(); Assert.NotNull(jobList); jobList = this.Client.Jobs.ListByResourceGroup(resourceGroupName); Assert.NotNull(jobList); this.Client.Jobs.Cancel(resourceGroupName, jobName, "CancelTest"); getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details); Assert.Equal(StageName.Cancelled, getJob.Status); while (!string.IsNullOrWhiteSpace(getJob.Details.ContactDetails.ContactName)) { Wait(TimeSpan.FromMinutes(5)); getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details); } this.Client.Jobs.Delete(resourceGroupName, jobName); } [Fact] public void CreateJobWithUserAssignedIdentity() { var resourceGroupName = TestUtilities.GenerateName("SdkRg"); var jobName = TestUtilities.GenerateName("SdkJob"); //var jobName = "SdkJob5929"; ContactDetails contactDetails = GetDefaultContactDetails(); ShippingAddress shippingAddress = GetDefaultShippingAddress(); Sku sku = GetDefaultSku(); var destinationAccountsList = new List<StorageAccountDetails> { new StorageAccountDetails { StorageAccountId = "/subscriptions/fa68082f-8ff7-4a25-95c7-ce9da541242f/resourceGroups/databoxbvt1/providers/Microsoft.Storage/storageAccounts/databoxbvttestaccount2" } }; var uaiId = "/subscriptions/fa68082f-8ff7-4a25-95c7-ce9da541242f/resourceGroups/akvenkat/providers/Microsoft.ManagedIdentity/userAssignedIdentities/sdkIdentity"; var kekDetails = new KeyEncryptionKey(KekType.CustomerManaged) { KekType = KekType.CustomerManaged, KekUrl = @"https://sdkkeyvault.vault.azure.net/keys/SSDKEY/", KekVaultResourceID = "/subscriptions/fa68082f-8ff7-4a25-95c7-ce9da541242f/resourceGroups/akvenkat/providers/Microsoft.KeyVault/vaults/SDKKeyVault", IdentityProperties = new IdentityProperties { Type = "UserAssigned", UserAssigned = new UserAssignedProperties { ResourceId = uaiId } } }; JobDetails jobDetails = new DataBoxJobDetails(contactDetails, default(IList<JobStages>),shippingAddress, default(PackageShippingDetails), default(PackageShippingDetails), default(IList<DataImportDetails>), default(IList<DataExportDetails>),default(Preferences), default(IList<CopyLogDetails>),default(string),default(string), kekDetails); jobDetails.DataImportDetails = new List<DataImportDetails>(); jobDetails.DataImportDetails.Add(new DataImportDetails(destinationAccountsList.FirstOrDefault())); var jobResource = new JobResource { Sku = sku, Location = TestConstants.DefaultResourceLocation, Details = jobDetails, }; UserAssignedIdentity uid = new UserAssignedIdentity(); var identity = new ResourceIdentity//ResourceIdentity checked by auto mapper { Type = "UserAssigned", UserAssignedIdentities = new Dictionary<string, UserAssignedIdentity> { { uaiId, uid } }, }; jobResource.Identity = identity; this.RMClient.ResourceGroups.CreateOrUpdate( resourceGroupName, new ResourceGroup { Location = TestConstants.DefaultResourceLocation }); var job = this.Client.Jobs.Create(resourceGroupName, jobName, jobResource); ValidateJobWithoutDetails(jobName, sku, job); Assert.Equal(StageName.DeviceOrdered, job.Status); String iden ="UserAssigned"; Assert.Equal(iden, job.Identity.Type); var getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details); ValidateJobWithoutDetails(jobName, sku, getJob); ValidateJobDetails(contactDetails, shippingAddress, getJob, JobDeliveryType.NonScheduled); Assert.Equal(StageName.DeviceOrdered, getJob.Status); Assert.True(!string.IsNullOrEmpty(getJob.Identity.UserAssignedIdentities[uaiId].ClientId)); Assert.True(!string.IsNullOrEmpty(getJob.Identity.UserAssignedIdentities[uaiId].PrincipalId)); Assert.Equal(KekType.CustomerManaged, getJob.Details.KeyEncryptionKey.KekType); } [Fact] public void UpdateSystemAssignedToUserAssigned() { var resourceGroupName = TestUtilities.GenerateName("SdkRg"); var jobName = TestUtilities.GenerateName("SdkJob"); //var jobName = "SdkJob5929"; ContactDetails contactDetails = GetDefaultContactDetails(); ShippingAddress shippingAddress = GetDefaultShippingAddress(); Sku sku = GetDefaultSku(); var destinationAccountsList = new List<StorageAccountDetails> { new StorageAccountDetails { StorageAccountId = "/subscriptions/fa68082f-8ff7-4a25-95c7-ce9da541242f/resourceGroups/databoxbvt1/providers/Microsoft.Storage/storageAccounts/databoxbvttestaccount2" } }; JobDetails jobDetails = new DataBoxJobDetails { ContactDetails = contactDetails, ShippingAddress = shippingAddress }; jobDetails.DataImportDetails = new List<DataImportDetails>(); jobDetails.DataImportDetails.Add(new DataImportDetails(destinationAccountsList.FirstOrDefault())); var jobResource = new JobResource { Sku = sku, Location = TestConstants.DefaultResourceLocation, Details = jobDetails, }; this.RMClient.ResourceGroups.CreateOrUpdate( resourceGroupName, new ResourceGroup { Location = TestConstants.DefaultResourceLocation }); var job = this.Client.Jobs.Create(resourceGroupName, jobName, jobResource); ValidateJobWithoutDetails(jobName, sku, job); Assert.Equal(StageName.DeviceOrdered, job.Status); // Set Msi details. string tenantId = "72f988bf-86f1-41af-91ab-2d7cd011db47"; string identityType = "SystemAssigned"; var identity = new ResourceIdentity(identityType, Guid.NewGuid().ToString(), tenantId); var updateParams = new JobResourceUpdateParameter { Identity = identity }; var updateJob = this.Client.Jobs.Update(resourceGroupName, jobName, updateParams); ValidateJobWithoutDetails(jobName, sku, updateJob); var getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details); ValidateJobWithoutDetails(jobName, sku, job); ValidateJobDetails(contactDetails, shippingAddress, getJob, JobDeliveryType.NonScheduled); Assert.Equal(StageName.DeviceOrdered, updateJob.Status); Assert.Equal(identityType, updateJob.Identity.Type); //Updating to User Assigned var uaiId = "/subscriptions/fa68082f-8ff7-4a25-95c7-ce9da541242f/resourceGroups/akvenkat/providers/Microsoft.ManagedIdentity/userAssignedIdentities/sdkIdentity"; var keyEncryptionKey = new KeyEncryptionKey(KekType.CustomerManaged) { KekUrl = @"https://sdkkeyvault.vault.azure.net/keys/SSDKEY/", KekVaultResourceID = "/subscriptions/fa68082f-8ff7-4a25-95c7-ce9da541242f/resourceGroups/akvenkat/providers/Microsoft.KeyVault/vaults/SDKKeyVault", IdentityProperties = new IdentityProperties { Type = "UserAssigned", UserAssigned = new UserAssignedProperties { ResourceId = uaiId } } }; UserAssignedIdentity uid = new UserAssignedIdentity(); identity = new ResourceIdentity//ResourceIdentity checked by auto mapper { Type = "SystemAssigned,UserAssigned", UserAssignedIdentities = new Dictionary<string, UserAssignedIdentity> { { uaiId, uid } }, }; var details = new UpdateJobDetails { KeyEncryptionKey = keyEncryptionKey }; updateParams = new JobResourceUpdateParameter { Details = details, Identity = identity }; updateJob = this.Client.Jobs.Update(resourceGroupName, jobName, updateParams); ValidateJobWithoutDetails(jobName, sku, updateJob); getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details); ValidateJobDetails(contactDetails, shippingAddress, getJob, JobDeliveryType.NonScheduled); Assert.Equal(StageName.DeviceOrdered, getJob.Status); Assert.True(!string.IsNullOrEmpty(getJob.Identity.UserAssignedIdentities[uaiId].ClientId)); Assert.True(!string.IsNullOrEmpty(getJob.Identity.UserAssignedIdentities[uaiId].PrincipalId)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection.Metadata.Ecma335; namespace System.Reflection.Metadata { public struct DocumentHandleCollection : IReadOnlyCollection<DocumentHandle> { private readonly MetadataReader _reader; private readonly int _firstRowId; private readonly int _lastRowId; internal DocumentHandleCollection(MetadataReader reader) { Debug.Assert(reader != null); _reader = reader; _firstRowId = 1; _lastRowId = reader.DocumentTable.NumberOfRows; } public int Count { get { return _lastRowId - _firstRowId + 1; } } public Enumerator GetEnumerator() { return new Enumerator(_reader, _firstRowId, _lastRowId); } IEnumerator<DocumentHandle> IEnumerable<DocumentHandle>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public struct Enumerator : IEnumerator<DocumentHandle>, IEnumerator { private readonly MetadataReader _reader; private readonly int _lastRowId; // inclusive // first Parameter rid - 1: initial state // EnumEnded: enumeration ended private int _currentRowId; // greater than any RowId and with last 24 bits clear, so that Current returns nil token private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1; internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId) { _reader = reader; _lastRowId = lastRowId; _currentRowId = firstRowId - 1; } public DocumentHandle Current { get { // PERF: keep this code small to enable inlining. return DocumentHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask)); } } public bool MoveNext() { // PERF: keep this code small to enable inlining. if (_currentRowId >= _lastRowId) { _currentRowId = EnumEnded; return false; } else { _currentRowId++; return true; } } object IEnumerator.Current { get { return Current; } } void IEnumerator.Reset() { throw new NotSupportedException(); } void IDisposable.Dispose() { } } } public struct MethodDebugInformationHandleCollection : IReadOnlyCollection<MethodDebugInformationHandle> { private readonly MetadataReader _reader; private readonly int _firstRowId; private readonly int _lastRowId; internal MethodDebugInformationHandleCollection(MetadataReader reader) { Debug.Assert(reader != null); _reader = reader; _firstRowId = 1; _lastRowId = reader.MethodDebugInformationTable.NumberOfRows; } public int Count { get { return _lastRowId - _firstRowId + 1; } } public Enumerator GetEnumerator() { return new Enumerator(_reader, _firstRowId, _lastRowId); } IEnumerator<MethodDebugInformationHandle> IEnumerable<MethodDebugInformationHandle>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public struct Enumerator : IEnumerator<MethodDebugInformationHandle>, IEnumerator { private readonly MetadataReader _reader; private readonly int _lastRowId; // inclusive // first Parameter rid - 1: initial state // EnumEnded: enumeration ended private int _currentRowId; // greater than any RowId and with last 24 bits clear, so that Current returns nil token private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1; internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId) { _reader = reader; _lastRowId = lastRowId; _currentRowId = firstRowId - 1; } public MethodDebugInformationHandle Current { get { // PERF: keep this code small to enable inlining. return MethodDebugInformationHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask)); } } public bool MoveNext() { // PERF: keep this code small to enable inlining. if (_currentRowId >= _lastRowId) { _currentRowId = EnumEnded; return false; } else { _currentRowId++; return true; } } object IEnumerator.Current { get { return Current; } } void IEnumerator.Reset() { throw new NotSupportedException(); } void IDisposable.Dispose() { } } } public struct LocalScopeHandleCollection : IReadOnlyCollection<LocalScopeHandle> { private readonly MetadataReader _reader; private readonly int _firstRowId; private readonly int _lastRowId; internal LocalScopeHandleCollection(MetadataReader reader, int methodDefinitionRowId) { Debug.Assert(reader != null); _reader = reader; if (methodDefinitionRowId == 0) { _firstRowId = 1; _lastRowId = reader.LocalScopeTable.NumberOfRows; } else { reader.LocalScopeTable.GetLocalScopeRange(methodDefinitionRowId, out _firstRowId, out _lastRowId); } } public int Count { get { return _lastRowId - _firstRowId + 1; } } public Enumerator GetEnumerator() { return new Enumerator(_reader, _firstRowId, _lastRowId); } IEnumerator<LocalScopeHandle> IEnumerable<LocalScopeHandle>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public struct Enumerator : IEnumerator<LocalScopeHandle>, IEnumerator { private readonly MetadataReader _reader; private readonly int _lastRowId; // inclusive // first Parameter rid - 1: initial state // EnumEnded: enumeration ended private int _currentRowId; // greater than any RowId and with last 24 bits clear, so that Current returns nil token private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1; internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId) { _reader = reader; _lastRowId = lastRowId; _currentRowId = firstRowId - 1; } public LocalScopeHandle Current { get { // PERF: keep this code small to enable inlining. return LocalScopeHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask)); } } public bool MoveNext() { // PERF: keep this code small to enable inlining. if (_currentRowId >= _lastRowId) { _currentRowId = EnumEnded; return false; } else { _currentRowId++; return true; } } object IEnumerator.Current { get { return Current; } } void IEnumerator.Reset() { throw new NotSupportedException(); } void IDisposable.Dispose() { } } public struct ChildrenEnumerator : IEnumerator<LocalScopeHandle>, IEnumerator { private readonly MetadataReader _reader; private readonly int _parentEndOffset; private readonly int _parentRowId; private readonly MethodDefinitionHandle _parentMethodRowId; // parent rid: initial state // EnumEnded: enumeration ended private int _currentRowId; // greater than any RowId and with last 24 bits clear, so that Current returns nil token private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1; internal ChildrenEnumerator(MetadataReader reader, int parentRowId) { _reader = reader; _parentEndOffset = reader.LocalScopeTable.GetEndOffset(parentRowId); _parentMethodRowId = reader.LocalScopeTable.GetMethod(parentRowId); _currentRowId = 0; _parentRowId = parentRowId; } public LocalScopeHandle Current { get { // PERF: keep this code small to enable inlining. return LocalScopeHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask)); } } public bool MoveNext() { int currentRowId = _currentRowId; if (currentRowId == EnumEnded) { return false; } int currentEndOffset; int nextRowId; if (currentRowId == 0) { currentEndOffset = -1; nextRowId = _parentRowId + 1; } else { currentEndOffset = _reader.LocalScopeTable.GetEndOffset(currentRowId); nextRowId = currentRowId + 1; } int rowCount = _reader.LocalScopeTable.NumberOfRows; while (true) { if (nextRowId > rowCount || _parentMethodRowId != _reader.LocalScopeTable.GetMethod(nextRowId)) { _currentRowId = EnumEnded; return false; } int nextEndOffset = _reader.LocalScopeTable.GetEndOffset(nextRowId); // If the end of the next scope is lesser than or equal the current end // then it's nested into the current scope and thus not a child of // the current scope parent. if (nextEndOffset > currentEndOffset) { // If the end of the next scope is greater than the parent end, // then we ran out of the children. if (nextEndOffset > _parentEndOffset) { _currentRowId = EnumEnded; return false; } _currentRowId = nextRowId; return true; } nextRowId++; } } object IEnumerator.Current { get { return Current; } } void IEnumerator.Reset() { throw new NotSupportedException(); } void IDisposable.Dispose() { } } } public struct LocalVariableHandleCollection : IReadOnlyCollection<LocalVariableHandle> { private readonly MetadataReader _reader; private readonly int _firstRowId; private readonly int _lastRowId; internal LocalVariableHandleCollection(MetadataReader reader, LocalScopeHandle scope) { Debug.Assert(reader != null); _reader = reader; if (scope.IsNil) { _firstRowId = 1; _lastRowId = reader.LocalVariableTable.NumberOfRows; } else { reader.GetLocalVariableRange(scope, out _firstRowId, out _lastRowId); } } public int Count { get { return _lastRowId - _firstRowId + 1; } } public Enumerator GetEnumerator() { return new Enumerator(_reader, _firstRowId, _lastRowId); } IEnumerator<LocalVariableHandle> IEnumerable<LocalVariableHandle>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public struct Enumerator : IEnumerator<LocalVariableHandle>, IEnumerator { private readonly MetadataReader _reader; private readonly int _lastRowId; // inclusive // first Parameter rid - 1: initial state // EnumEnded: enumeration ended private int _currentRowId; // greater than any RowId and with last 24 bits clear, so that Current returns nil token private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1; internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId) { _reader = reader; _lastRowId = lastRowId; _currentRowId = firstRowId - 1; } public LocalVariableHandle Current { get { // PERF: keep this code small to enable inlining. return LocalVariableHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask)); } } public bool MoveNext() { // PERF: keep this code small to enable inlining. if (_currentRowId >= _lastRowId) { _currentRowId = EnumEnded; return false; } else { _currentRowId++; return true; } } object IEnumerator.Current { get { return Current; } } void IEnumerator.Reset() { throw new NotSupportedException(); } void IDisposable.Dispose() { } } } public struct LocalConstantHandleCollection : IReadOnlyCollection<LocalConstantHandle> { private readonly MetadataReader _reader; private readonly int _firstRowId; private readonly int _lastRowId; internal LocalConstantHandleCollection(MetadataReader reader, LocalScopeHandle scope) { Debug.Assert(reader != null); _reader = reader; if (scope.IsNil) { _firstRowId = 1; _lastRowId = reader.LocalConstantTable.NumberOfRows; } else { reader.GetLocalConstantRange(scope, out _firstRowId, out _lastRowId); } } public int Count { get { return _lastRowId - _firstRowId + 1; } } public Enumerator GetEnumerator() { return new Enumerator(_reader, _firstRowId, _lastRowId); } IEnumerator<LocalConstantHandle> IEnumerable<LocalConstantHandle>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public struct Enumerator : IEnumerator<LocalConstantHandle>, IEnumerator { private readonly MetadataReader _reader; private readonly int _lastRowId; // inclusive // first Parameter rid - 1: initial state // EnumEnded: enumeration ended private int _currentRowId; // greater than any RowId and with last 24 bits clear, so that Current returns nil token private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1; internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId) { _reader = reader; _lastRowId = lastRowId; _currentRowId = firstRowId - 1; } public LocalConstantHandle Current { get { // PERF: keep this code small to enable inlining. return LocalConstantHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask)); } } public bool MoveNext() { // PERF: keep this code small to enable inlining. if (_currentRowId >= _lastRowId) { _currentRowId = EnumEnded; return false; } else { _currentRowId++; return true; } } object IEnumerator.Current { get { return Current; } } void IEnumerator.Reset() { throw new NotSupportedException(); } void IDisposable.Dispose() { } } } public struct ImportScopeCollection : IReadOnlyCollection<ImportScopeHandle> { private readonly MetadataReader _reader; private readonly int _firstRowId; private readonly int _lastRowId; internal ImportScopeCollection(MetadataReader reader) { Debug.Assert(reader != null); _reader = reader; _firstRowId = 1; _lastRowId = reader.ImportScopeTable.NumberOfRows; } public int Count { get { return _lastRowId - _firstRowId + 1; } } public Enumerator GetEnumerator() { return new Enumerator(_reader, _firstRowId, _lastRowId); } IEnumerator<ImportScopeHandle> IEnumerable<ImportScopeHandle>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public struct Enumerator : IEnumerator<ImportScopeHandle>, IEnumerator { private readonly MetadataReader _reader; private readonly int _lastRowId; // inclusive // first Parameter rid - 1: initial state // EnumEnded: enumeration ended private int _currentRowId; // greater than any RowId and with last 24 bits clear, so that Current returns nil token private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1; internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId) { _reader = reader; _lastRowId = lastRowId; _currentRowId = firstRowId - 1; } public ImportScopeHandle Current { get { // PERF: keep this code small to enable inlining. return ImportScopeHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask)); } } public bool MoveNext() { // PERF: keep this code small to enable inlining. if (_currentRowId >= _lastRowId) { _currentRowId = EnumEnded; return false; } else { _currentRowId++; return true; } } object IEnumerator.Current { get { return Current; } } void IEnumerator.Reset() { throw new NotSupportedException(); } void IDisposable.Dispose() { } } } public struct CustomDebugInformationHandleCollection : IReadOnlyCollection<CustomDebugInformationHandle> { private readonly MetadataReader _reader; private readonly int _firstRowId; private readonly int _lastRowId; internal CustomDebugInformationHandleCollection(MetadataReader reader) { Debug.Assert(reader != null); _reader = reader; _firstRowId = 1; _lastRowId = reader.CustomDebugInformationTable.NumberOfRows; } internal CustomDebugInformationHandleCollection(MetadataReader reader, EntityHandle handle) { Debug.Assert(reader != null); _reader = reader; reader.CustomDebugInformationTable.GetRange(handle, out _firstRowId, out _lastRowId); } public int Count { get { return _lastRowId - _firstRowId + 1; } } public Enumerator GetEnumerator() { return new Enumerator(_reader, _firstRowId, _lastRowId); } IEnumerator<CustomDebugInformationHandle> IEnumerable<CustomDebugInformationHandle>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public struct Enumerator : IEnumerator<CustomDebugInformationHandle>, IEnumerator { private readonly MetadataReader _reader; private readonly int _lastRowId; // inclusive // first Parameter rid - 1: initial state // EnumEnded: enumeration ended private int _currentRowId; // greater than any RowId and with last 24 bits clear, so that Current returns nil token private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1; internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId) { _reader = reader; _lastRowId = lastRowId; _currentRowId = firstRowId - 1; } public CustomDebugInformationHandle Current { get { // PERF: keep this code small to enable inlining. return CustomDebugInformationHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask)); } } public bool MoveNext() { // PERF: keep this code small to enable inlining. if (_currentRowId >= _lastRowId) { _currentRowId = EnumEnded; return false; } else { _currentRowId++; return true; } } object IEnumerator.Current { get { return Current; } } void IEnumerator.Reset() { throw new NotSupportedException(); } void IDisposable.Dispose() { } } } }
// Copyright ?2004, 2015, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // <http://www.mysql.com/about/legal/licensing/foss-exception.html>. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections; using System.Text; using MySql.Data.Common; using System.Collections.Generic; using System.Data; namespace MySql.Data.MySqlClient { /// <summary> /// Summary description for CharSetMap. /// </summary> internal class CharSetMap { private static Dictionary<string, string> defaultCollations; private static Dictionary<string, int> maxLengths; private static Dictionary<string, CharacterSet> mapping; private static object lockObject; // we use a static constructor here since we only want to init // the mapping once static CharSetMap() { lockObject = new Object(); InitializeMapping(); } public static CharacterSet GetCharacterSet(DBVersion version, string CharSetName) { CharacterSet cs = null; if(mapping.ContainsKey(CharSetName)) cs = (CharacterSet)mapping[CharSetName]; if (cs == null) throw new MySqlException("Character set '" + CharSetName + "' is not supported by .Net Framework."); return cs; } /// <summary> /// Returns the text encoding for a given MySQL character set name /// </summary> /// <param name="version">Version of the connection requesting the encoding</param> /// <param name="CharSetName">Name of the character set to get the encoding for</param> /// <returns>Encoding object for the given character set name</returns> public static Encoding GetEncoding(DBVersion version, string CharSetName) { try { CharacterSet cs = GetCharacterSet(version, CharSetName); return Encoding.GetEncoding(cs.name); } catch (NotSupportedException) { return Encoding.GetEncoding("utf-8"); } } /// <summary> /// /// </summary> private static void InitializeMapping() { LoadCharsetMap(); } private static void LoadCharsetMap() { mapping = new Dictionary<string, CharacterSet>(); mapping.Add("latin1", new CharacterSet("windows-1252", 1)); mapping.Add("big5", new CharacterSet("big5", 2)); mapping.Add("dec8", mapping["latin1"]); mapping.Add("cp850", new CharacterSet("ibm850", 1)); mapping.Add("hp8", mapping["latin1"]); mapping.Add("koi8r", new CharacterSet("koi8-u", 1)); mapping.Add("latin2", new CharacterSet("latin2", 1)); mapping.Add("swe7", mapping["latin1"]); mapping.Add("ujis", new CharacterSet("EUC-JP", 3)); mapping.Add("eucjpms", mapping["ujis"]); mapping.Add("sjis", new CharacterSet("sjis", 2)); mapping.Add("cp932", mapping["sjis"]); mapping.Add("hebrew", new CharacterSet("hebrew", 1)); mapping.Add("tis620", new CharacterSet("windows-874", 1)); mapping.Add("euckr", new CharacterSet("euc-kr", 2)); mapping.Add("euc_kr", mapping["euckr"]); mapping.Add("koi8u", new CharacterSet("koi8-u", 1)); mapping.Add("koi8_ru", mapping["koi8u"]); mapping.Add("gb2312", new CharacterSet("gb2312", 2)); mapping.Add("gbk", mapping["gb2312"]); mapping.Add("greek", new CharacterSet("greek", 1)); mapping.Add("cp1250", new CharacterSet("windows-1250", 1)); mapping.Add("win1250", mapping["cp1250"]); mapping.Add("latin5", new CharacterSet("latin5", 1)); mapping.Add("armscii8", mapping["latin1"]); mapping.Add("utf8", new CharacterSet("utf-8", 3)); mapping.Add("ucs2", new CharacterSet("UTF-16BE", 2)); mapping.Add("cp866", new CharacterSet("cp866", 1)); mapping.Add("keybcs2", mapping["latin1"]); mapping.Add("macce", new CharacterSet("x-mac-ce", 1)); mapping.Add("macroman", new CharacterSet("x-mac-romanian", 1)); mapping.Add("cp852", new CharacterSet("ibm852", 2)); mapping.Add("latin7", new CharacterSet("iso-8859-7", 1)); mapping.Add("cp1251", new CharacterSet("windows-1251", 1)); mapping.Add("win1251ukr", mapping["cp1251"]); mapping.Add("cp1251csas", mapping["cp1251"]); mapping.Add("cp1251cias", mapping["cp1251"]); mapping.Add("win1251", mapping["cp1251"]); mapping.Add("cp1256", new CharacterSet("cp1256", 1)); mapping.Add("cp1257", new CharacterSet("windows-1257", 1)); mapping.Add("ascii", new CharacterSet("us-ascii", 1)); mapping.Add("usa7", mapping["ascii"]); mapping.Add("binary", mapping["ascii"]); mapping.Add("latin3", new CharacterSet("latin3", 1)); mapping.Add("latin4", new CharacterSet("latin4", 1)); mapping.Add("latin1_de", new CharacterSet("iso-8859-1", 1)); mapping.Add("german1", new CharacterSet("iso-8859-1", 1)); mapping.Add("danish", new CharacterSet("iso-8859-1", 1)); mapping.Add("czech", new CharacterSet("iso-8859-2", 1)); mapping.Add("hungarian", new CharacterSet("iso-8859-2", 1)); mapping.Add("croat", new CharacterSet("iso-8859-2", 1)); mapping.Add("latvian", new CharacterSet("iso-8859-13", 1)); mapping.Add("latvian1", new CharacterSet("iso-8859-13", 1)); mapping.Add("estonia", new CharacterSet("iso-8859-13", 1)); mapping.Add("dos", new CharacterSet("ibm437", 1)); mapping.Add("utf8mb4", new CharacterSet("utf-8", 4)); mapping.Add("utf16", new CharacterSet("utf-16BE", 2)); mapping.Add("utf16le", new CharacterSet("utf-16", 2)); mapping.Add("utf32", new CharacterSet("utf-32BE", 4)); mapping.Add("gb18030", new CharacterSet("gb18030", 4)); } internal static void InitCollections(MySqlConnection connection) { defaultCollations = new Dictionary<string, string>(); maxLengths = new Dictionary<string, int>(); MySqlCommand cmd = new MySqlCommand("SHOW CHARSET", connection); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { defaultCollations.Add(reader.GetString(0), reader.GetString(2)); maxLengths.Add(reader.GetString(0), Convert.ToInt32(reader.GetValue(3))); } } } internal static string GetDefaultCollation(string charset, MySqlConnection connection) { lock (lockObject) { if (defaultCollations == null) InitCollections(connection); } if (!defaultCollations.ContainsKey(charset)) return null; return defaultCollations[charset]; } internal static int GetMaxLength(string charset, MySqlConnection connection) { lock (lockObject) { if (maxLengths == null) InitCollections(connection); } if (!maxLengths.ContainsKey(charset)) return 1; return maxLengths[charset]; } } internal class CharacterSet { public string name; public int byteCount; public CharacterSet(string name, int byteCount) { this.name = name; this.byteCount = byteCount; } } }
// 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; //StackFrame using System.IO; using System.Text; namespace OLEDB.Test.ModuleCore { //////////////////////////////////////////////////////////////// // CError // //////////////////////////////////////////////////////////////// public class CError { //Data private static IError s_rIError; private static ITestConsole s_rITestConsole; private static CLTMConsole s_rLTMConsole; //Constructor public CError() { } static public IError Error { set { //Set the static Error interface... s_rIError = value; //Setup the standard c# Console to log to LTM instead... //i.e.: Console.WriteLine will automatically log to LTM if (s_rLTMConsole == null) { s_rLTMConsole = new CLTMConsole(); } //The Error object may also support additional interfaces s_rITestConsole = value as ITestConsole; //Disable Asserts DisableAsserts(); } get { return s_rIError; } } static public TextWriter Out { get { return s_rLTMConsole; } } static public ITestConsole TestConsole { get { return s_rITestConsole; } } static internal void Dispose() { //Reset the info. s_rIError = null; s_rITestConsole = null; //Remove listeners s_rLTMConsole = null; } static internal void DisableAsserts() { } //Helpers static public void Increment() { Error.Increment(); } static public tagERRORLEVEL ErrorLevel { get { if (Error != null) return Error.GetErrorLevel(); return tagERRORLEVEL.HR_STRICT; } set { if (Error != null) Error.SetErrorLevel(value); } } static public void Transmit(string text) { Write(text); } static public string NewLine { get { return "\n"; } } static public void Write(object value) { if (value != null) Write(value.ToString()); } static public void WriteLine(object value) { Write(value); WriteLine(); } static public void Write(string text) { Write(tagCONSOLEFLAGS.CONSOLE_TEXT, text); } static public void WriteLine(string text) { Write(tagCONSOLEFLAGS.CONSOLE_TEXT, text); WriteLine(); } static public void Write(string text, params object[] args) { //Delegate Write(String.Format(text, args)); } static public void WriteLine(string text, params object[] args) { //Delegate WriteLine(String.Format(text, args)); } static public void Write(char[] value) { //Delegate if (value != null) Write(new string(value)); } static public void WriteLine(char[] value) { //Delegate if (value != null) Write(new string(value)); WriteLine(); } static public void WriteXml(string text) { Write(tagCONSOLEFLAGS.CONSOLE_XML, text); } static public void WriteRaw(string text) { Write(tagCONSOLEFLAGS.CONSOLE_RAW, text); } static public void WriteIgnore(string text) { Write(tagCONSOLEFLAGS.CONSOLE_IGNORE, text); } static public void WriteLineIgnore(string text) { Write(tagCONSOLEFLAGS.CONSOLE_IGNORE, text + CError.NewLine); } static public void Write(tagCONSOLEFLAGS flags, string text) { if (flags == tagCONSOLEFLAGS.CONSOLE_TEXT) { text = FixupXml(text); } //NOTE:You can also simply use Console.WriteLine and have it show up in LTM... //Is the new ITestConsole interface available (using a new LTM) if (TestConsole != null) { TestConsole.Write(flags, text); } else if (Error != null) { //Otherwise Error.Transmit(text); } } static public void WriteLine() { if (TestConsole != null) TestConsole.WriteLine(); else if (Error != null) Error.Transmit(CError.NewLine); } static public bool Compare(bool equal, string message) { if (equal) return true; return Compare(false, true, message); } static public bool Compare(object actual, object expected, string message) { if (InternalEquals(actual, expected)) return true; //Compare not only compares but throws - so your test stops processing //This way processing stops upon the first error, so you don't have to check return //values or validate values afterwards. If you have other items to do, then use the //CError.Equals instead of CError.Compare Console.WriteLine("ERROR: {0}", message); Console.WriteLine("Expected: {0}", expected); Console.WriteLine("Actual : {0}", actual); throw new CTestFailedException(message, actual, expected, null); } static public bool Compare(object actual, object expected1, object expected2, string message) { if (InternalEquals(actual, expected1) || InternalEquals(actual, expected2)) return true; //Compare not only compares but throws - so your test stops processing //This way processing stops upon the first error, so you don't have to check return //values or validate values afterwards. If you have other items to do, then use the //CError.Equals instead of CError.Compare Console.WriteLine("expected1: " + expected1); Console.WriteLine("expected2: " + expected2); throw new CTestFailedException(message, actual, expected1, null); //return false; } static public bool Equals(object actual, object expected, string message) { try { //Equals is identical to Compare, except that Equals doesn't throw. //This way if We still want to throw the exception so we get the logging and compare block //but the test wants to continue to do other things. return CError.Compare(actual, expected, message); } catch (Exception e) { CTestBase.HandleException(e); return false; } } static public bool Equals(bool equal, string message) { try { //Equals is identical to Compare, except that Equals doesn't throw. //This way if We still want to throw the exception so we get the logging and compare block //but the test wants to continue to do other things. return CError.Compare(equal, message); } catch (Exception e) { CTestBase.HandleException(e); return false; } } static public bool Warning(bool equal, string message) { return Warning(equal, true, message, null); } static public bool Warning(object actual, object expected, string message) { return Warning(actual, expected, message, null); } static public bool Warning(object actual, object expected, string message, Exception inner) { //See if these are equal bool equal = InternalEquals(actual, expected); if (equal) return true; try { //Throw a warning exception throw new CTestException(CTestBase.TEST_WARNING, message, actual, expected, inner); } catch (Exception e) { //Warning should continue - not halt test progress CTestBase.HandleException(e); return false; } } static public bool Skip(string message) { //Delegate return Skip(true, message); } static public bool Skip(bool skip, string message) { if (skip) throw new CTestSkippedException(message); return false; } static internal bool InternalEquals(object actual, object expected) { //Handle null comparison if (actual == null && expected == null) return true; else if (actual == null || expected == null) return false; //Otherwise return expected.Equals(actual); } static public bool Log(object actual, object expected, string source, string message, string details, tagERRORLEVEL eErrorLevel) { //Obtain the error level tagERRORLEVEL rSavedLevel = ErrorLevel; //Set the error level ErrorLevel = eErrorLevel; try { //Get caller function, 0=current //StackTrace rStackTrace = new StackTrace(); //StackFrame rStackFrame = rStackTrace.GetFrame(1); //Log the error if (TestConsole != null) { //ITestConsole.Log TestConsole.Log(Common.Format(actual), //actual Common.Format(expected), //expected source, //source message, //message details, //details tagCONSOLEFLAGS.CONSOLE_TEXT, //flags "fake_filename", 999 ); } else if (Error != null) { //We call IError::Compare, which logs the error AND increments the error count... Console.WriteLine("Message:\t" + message); Console.WriteLine("Source:\t\t" + source); Console.WriteLine("Expected:\t" + expected); Console.WriteLine("Received:\t" + actual); Console.WriteLine("Details:" + CError.NewLine + details); } } finally { //Restore the error level ErrorLevel = rSavedLevel; } return false; } private static String FixupXml(String value) { bool escapeXmlStuff = false; if (value == null) return null; StringBuilder b = new StringBuilder(); for (int i = 0; i < value.Length; i++) { switch (value[i]) { case '&': if (escapeXmlStuff) b.Append("&amp;"); else b.Append('&'); break; case '<': if (escapeXmlStuff) b.Append("&lt;"); else b.Append('<'); break; case '>': if (escapeXmlStuff) b.Append("&gt;"); else b.Append('>'); break; case '"': if (escapeXmlStuff) b.Append("&quot;"); else b.Append('"'); break; case '\'': if (escapeXmlStuff) b.Append("&apos;"); else b.Append('\''); break; case '\t': b.Append('\t'); break; case '\r': b.Append('\r'); break; case '\n': b.Append('\n'); break; default: if ((value[i] < 0x20) || value[i] >= 0x80) { b.Append(PrintUnknownCharacter(value[i])); } else { b.Append(value[i]); } break; } } return b.ToString(); } private static string PrintUnknownCharacter(char ch) { int number = ch; string result = string.Empty; if (number == 0) { result = "0"; } while (number > 0) { int n = number % 16; number = number / 16; if (n < 10) { result = (char)(n + (int)'0') + result; } else { result = (char)(n - 10 + (int)'A') + result; } } return "_x" + result + "_"; } } }
using System; using System.Collections.Generic; using System.Text; using Platform.Runtime; using System.Data.Common; using System.Runtime.InteropServices; using System.ServiceModel; using System.Runtime.Serialization; using System.Web.Services; using System.Web.UI; /* * High performance automated object model * Created by an automatic tool * */ namespace Platform.Module.UndoRedo.Services.Packages { /// <summary> /// Defines the contract for the UndoRedoOptions class /// </summary> [ComVisible(true)] [Guid("7b0f86c0-961e-a5c4-12e2-ac012dc7e158")] [InterfaceType(ComInterfaceType.InterfaceIsDual)] public interface IUndoRedoOptions { bool Exists { get; } System.String EntityType { get; set; } System.Int64 ItemsAllowed { get; set; } System.Boolean IsEnabled { get; set; } void Read(System.String __EntityType); void Reload(); void Create(); void Update(); void Delete(); void CopyWithKeysFrom(UndoRedoOptions _object); void CopyWithKeysTo(UndoRedoOptions _object); void CopyFrom(UndoRedoOptions _object); void CopyTo(UndoRedoOptions _object); } /// <summary> /// Defines the contract for all the service-based types which can /// apply servicing on Platform.Module.UndoRedo.Services.Packages.UndoRedoOptions type. /// </summary> [ComVisible(true)] [Guid("1c2dc3c6-8214-7da1-2d14-91b84f6114da")] [InterfaceType(ComInterfaceType.InterfaceIsDual)] [ServiceContract(Namespace="http://services.msd.com")] public interface IUndoRedoOptionsService { string Uri { get; set; } [OperationContract] bool Exists(UndoRedoOptions _UndoRedoOptions); [OperationContract] UndoRedoOptions Read(System.String __EntityType); [OperationContract] UndoRedoOptions Reload(UndoRedoOptions _UndoRedoOptions); [OperationContract] UndoRedoOptions Create(System.String __EntityType); [OperationContract] void Delete(System.String __EntityType); [OperationContract] void UpdateObject(UndoRedoOptions _UndoRedoOptions); [OperationContract] void CreateObject(UndoRedoOptions _UndoRedoOptions); [OperationContract] void DeleteObject(UndoRedoOptions _UndoRedoOptions); [OperationContract] void Undo(); [OperationContract] void Redo(); [OperationContract] UndoRedoOptionsCollection SearchByEntityType(System.String EntityType ); [OperationContract] UndoRedoOptionsCollection SearchByEntityTypePaged(System.String EntityType , long PagingStart, long PagingCount); [OperationContract] long SearchByEntityTypeCount(System.String EntityType ); } /// <summary> /// WCF and default implementation of a service object for Platform.Module.UndoRedo.Services.Packages.UndoRedoOptions type. /// </summary> [ComVisible(true)] [ClassInterface(ClassInterfaceType.None)] [Guid("b0b68d93-8777-ac06-1bfa-864614029bc2")] [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, UseSynchronizationContext=false, IncludeExceptionDetailInFaults = true, AddressFilterMode=AddressFilterMode.Any, Namespace="http://services.msd.com")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute] sealed public class UndoRedoOptionsService : IUndoRedoOptionsService { /// <summary> /// Not supported. Throws a NotSupportedException on get or set. /// </summary> public string Uri { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } [WebMethod] public bool Exists(UndoRedoOptions _UndoRedoOptions) { return _UndoRedoOptions.Exists; } [WebMethod] public UndoRedoOptions Read(System.String __EntityType) { return new UndoRedoOptions(__EntityType); } [WebMethod] public UndoRedoOptions Reload(UndoRedoOptions _UndoRedoOptions) { _UndoRedoOptions.Reload(); return _UndoRedoOptions; } [WebMethod] public UndoRedoOptions Create(System.String __EntityType) { return UndoRedoOptions.CreateUndoRedoOptions(__EntityType); } [WebMethod] public void Delete(System.String __EntityType) { UndoRedoOptions.DeleteUndoRedoOptions(__EntityType); } [WebMethod] public void UpdateObject(UndoRedoOptions _UndoRedoOptions) { _UndoRedoOptions.Update(); } [WebMethod] public void CreateObject(UndoRedoOptions _UndoRedoOptions) { _UndoRedoOptions.Create(); } [WebMethod] public void DeleteObject(UndoRedoOptions _UndoRedoOptions) { _UndoRedoOptions.Delete(); } [WebMethod] public void Undo() { UndoRedoOptions.Undo(); } [WebMethod] public void Redo() { UndoRedoOptions.Redo(); } [WebMethod] public UndoRedoOptionsCollection SearchByEntityType(System.String EntityType ) { return UndoRedoOptions.SearchByEntityType(EntityType ); } [WebMethod] public UndoRedoOptionsCollection SearchByEntityTypePaged(System.String EntityType , long PagingStart, long PagingCount) { return UndoRedoOptions.SearchByEntityTypePaged(EntityType , PagingStart, PagingCount); } [WebMethod] public long SearchByEntityTypeCount(System.String EntityType ) { return UndoRedoOptions.SearchByEntityTypeCount(EntityType ); } } /// <summary> /// Provides the implementation of Platform.Module.UndoRedo.Services.Packages.UndoRedoOptions model that acts as DAL for /// a database table. /// </summary> [ComVisible(true)] [ClassInterface(ClassInterfaceType.None)] [Guid("258bcc05-88d0-3ea4-e492-4d09050b56b0")] [DataContract] [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute] [Serializable] public class UndoRedoOptions : IUndoRedoOptions, IHierarchyData, global::Platform.Runtime.Data.IModelHierachyData { #region Servicing support // Synchronized replication [NonSerialized] static List<IUndoRedoOptionsService> replicationServices = null; // Scaling proxy objects (using 1 object you get forwarding) [NonSerialized] static List<IUndoRedoOptionsService> scalingServices = null; // static IServiceSelectionAlgorithm serviceSelectionAlgorithm = null; // Failover scenario [NonSerialized] static List<IUndoRedoOptionsService> failoverServices = null; #endregion #region Connection provider and DbConnection selection support [NonSerialized] static string classConnectionString = null; [NonSerialized] string instanceConnectionString = null; [System.Xml.Serialization.XmlIgnoreAttribute] public static string ClassConnectionString { get { if (!String.IsNullOrEmpty(classConnectionString)) return classConnectionString; if (global::System.Configuration.ConfigurationManager.ConnectionStrings["Platform.Module.UndoRedo.Services.Packages.UndoRedoOptions"] != null) classConnectionString = global::System.Configuration.ConfigurationManager.ConnectionStrings["Platform.Module.UndoRedo.Services.Packages.UndoRedoOptions"].ConnectionString; if (!String.IsNullOrEmpty(classConnectionString)) return classConnectionString; if (!String.IsNullOrEmpty(Platform.Module.Packages.ConnectionString)) return Platform.Module.Packages.ConnectionString; throw new InvalidOperationException("The sql connection string has not been set up in any level"); } set { classConnectionString = value; } } [System.Xml.Serialization.XmlIgnoreAttribute] public string ConnectionString { get { if (!String.IsNullOrEmpty(instanceConnectionString)) return instanceConnectionString; return ClassConnectionString; } set { instanceConnectionString = value; } } [NonSerialized] static global::Platform.Runtime.SqlProviderType classSqlProviderType = global::Platform.Runtime.SqlProviderType.NotSpecified; [NonSerialized] global::Platform.Runtime.SqlProviderType instanceSqlProviderType = global::Platform.Runtime.SqlProviderType.NotSpecified; [System.Xml.Serialization.XmlIgnoreAttribute] public static global::Platform.Runtime.SqlProviderType ClassSqlProviderType { get { if (classSqlProviderType != global::Platform.Runtime.SqlProviderType.NotSpecified) return classSqlProviderType; classSqlProviderType = global::Platform.Runtime.Sql.GetProviderConfiguration("Platform.Module.UndoRedo.Services.Packages.UndoRedoOptions.ProviderType"); if (classSqlProviderType != global::Platform.Runtime.SqlProviderType.NotSpecified) return classSqlProviderType; if (global::Platform.Module.Packages.SqlProviderType != global::Platform.Runtime.SqlProviderType.NotSpecified) return Platform.Module.Packages.SqlProviderType; throw new InvalidOperationException("The sql provider type has not been set up in any level"); } set { classSqlProviderType = value; } } [System.Xml.Serialization.XmlIgnoreAttribute] public global::Platform.Runtime.SqlProviderType InstanceSqlProviderType { get { if (instanceSqlProviderType != global::Platform.Runtime.SqlProviderType.NotSpecified) return instanceSqlProviderType; return ClassSqlProviderType; } set { instanceSqlProviderType = value; } } [NonSerialized] private static global::Platform.Runtime.IConnectionProvider instanceConnectionProvider; [NonSerialized] private static global::Platform.Runtime.IConnectionProvider classConnectionProvider; [System.Xml.Serialization.XmlIgnoreAttribute] public global::Platform.Runtime.IConnectionProvider InstanceConnectionProvider { get { if (String.IsNullOrEmpty(ConnectionString) || InstanceSqlProviderType == Platform.Runtime.SqlProviderType.NotSpecified) return ClassConnectionProvider; if (instanceConnectionProvider == null) { instanceConnectionProvider = Platform.Runtime.Sql.CreateProvider(InstanceSqlProviderType, ConnectionString); } return instanceConnectionProvider; } } [System.Xml.Serialization.XmlIgnoreAttribute] public static global::Platform.Runtime.IConnectionProvider ClassConnectionProvider { get { if (String.IsNullOrEmpty(ClassConnectionString) || ClassSqlProviderType == Platform.Runtime.SqlProviderType.NotSpecified) return Platform.Module.Packages.ConnectionProvider; if (classConnectionProvider == null) { classConnectionProvider = Platform.Runtime.Sql.CreateProvider(ClassSqlProviderType, ClassConnectionString); } return classConnectionProvider; } } [System.Xml.Serialization.XmlIgnoreAttribute] public global::Platform.Runtime.IConnectionProvider ConnectionProvider { get { if (InstanceConnectionProvider != null) return InstanceConnectionProvider; return ClassConnectionProvider; } } #endregion #region Data row consistency and state RowState __databaseState = RowState.Empty; bool __hasBeenReadOnce = false; #endregion #region Main implementation - Properties, Relations, CRUD System.String _EntityType; // Key member [DataMember] [global::System.ComponentModel.Bindable(true)] public System.String EntityType { get { return _EntityType; } set { if (_EntityType != value) __hasBeenReadOnce = false; _EntityType = value; } } System.Int64 _ItemsAllowed; [DataMember] [global::System.ComponentModel.Bindable(true)] public System.Int64 ItemsAllowed { get { return _ItemsAllowed; } set { _ItemsAllowed = value; } } System.Boolean _IsEnabled; [DataMember] [global::System.ComponentModel.Bindable(true)] public System.Boolean IsEnabled { get { return _IsEnabled; } set { _IsEnabled = value; } } public static UndoRedoOptionsCollection SearchByEntityType(System.String _EntityType) { UndoRedoOptionsCollection _UndoRedoOptionsCollection = new UndoRedoOptionsCollection(); // sql read using (DbConnection dbconn = ClassConnectionProvider.GetDatabaseConnection(ClassConnectionString)) { dbconn.Open(); DbCommand command = ClassConnectionProvider.GetDatabaseCommand("UnReOpSeByEnTy", dbconn); command.CommandType = global::System.Data.CommandType.StoredProcedure; _EntityType = ClassConnectionProvider.Escape(_EntityType); DbParameter param_EntityType = ClassConnectionProvider.GetDatabaseParameter("EntityType", typeof(System.String), -1); param_EntityType.Value = ClassConnectionProvider.FromValueToSqlModelType(_EntityType); command.Parameters.Add(param_EntityType); ClassConnectionProvider.OnBeforeExecuted(command); DbDataReader dr = command.ExecuteReader(global::System.Data.CommandBehavior.CloseConnection); while (dr.Read()) { UndoRedoOptions o = new UndoRedoOptions(); o.__databaseState = RowState.Initialized; o._EntityType = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["EntityType"], typeof(System.String)); o._ItemsAllowed = (System.Int64) global::Platform.Runtime.Utilities.FromSqlToValue(dr["ItemsAllowed"], typeof(System.Int64)); o._IsEnabled = (System.Boolean) global::Platform.Runtime.Utilities.FromSqlToValue(dr["IsEnabled"], typeof(System.Boolean)); _UndoRedoOptionsCollection.Add(o); } dr.Close(); } return _UndoRedoOptionsCollection; } public static UndoRedoOptionsCollection SearchByEntityTypePaged(System.String _EntityType, long PagingStart, long PagingCount) { UndoRedoOptionsCollection _UndoRedoOptionsCollection = new UndoRedoOptionsCollection(); // sql read using (DbConnection dbconn = ClassConnectionProvider.GetDatabaseConnection(ClassConnectionString)) { dbconn.Open(); DbCommand command = ClassConnectionProvider.GetDatabaseCommand("UnReOpSeByEnTyPaged", dbconn); command.CommandType = global::System.Data.CommandType.StoredProcedure; _EntityType = ClassConnectionProvider.Escape(_EntityType); DbParameter param_EntityType = ClassConnectionProvider.GetDatabaseParameter("EntityType", typeof(System.String), -1); param_EntityType.Value = ClassConnectionProvider.FromValueToSqlModelType(_EntityType); command.Parameters.Add(param_EntityType); DbParameter __param_PagingStart = ClassConnectionProvider.GetDatabaseParameter("PagingStart", PagingStart); command.Parameters.Add(__param_PagingStart); DbParameter __param_PagingCount = ClassConnectionProvider.GetDatabaseParameter("PagingCount", PagingCount); command.Parameters.Add(__param_PagingCount); ClassConnectionProvider.OnBeforeExecuted(command); DbDataReader dr = command.ExecuteReader(global::System.Data.CommandBehavior.CloseConnection); if (ClassSqlProviderType == global::Platform.Runtime.SqlProviderType.SqlServer) { while (PagingStart > 0 && dr.Read()) --PagingStart; } while (PagingCount > 0 && dr.Read()) { UndoRedoOptions o = new UndoRedoOptions(); o.__databaseState = RowState.Initialized; o._EntityType = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["EntityType"], typeof(System.String)); o._ItemsAllowed = (System.Int64) global::Platform.Runtime.Utilities.FromSqlToValue(dr["ItemsAllowed"], typeof(System.Int64)); o._IsEnabled = (System.Boolean) global::Platform.Runtime.Utilities.FromSqlToValue(dr["IsEnabled"], typeof(System.Boolean)); _UndoRedoOptionsCollection.Add(o); --PagingCount; } dr.Close(); } return _UndoRedoOptionsCollection; } public static long SearchByEntityTypeCount(System.String _EntityType) { long count = 0; // sql read using (DbConnection dbconn = ClassConnectionProvider.GetDatabaseConnection(ClassConnectionString)) { dbconn.Open(); DbCommand command = ClassConnectionProvider.GetDatabaseCommand("UnReOpSeByEnTyCount", dbconn); command.CommandType = global::System.Data.CommandType.StoredProcedure; _EntityType = ClassConnectionProvider.Escape(_EntityType); DbParameter param_EntityType = ClassConnectionProvider.GetDatabaseParameter("EntityType", typeof(System.String), -1); param_EntityType.Value = ClassConnectionProvider.FromValueToSqlModelType(_EntityType); command.Parameters.Add(param_EntityType); ClassConnectionProvider.OnBeforeExecuted(command); count = (int)command.ExecuteScalar(); if (count < 0) count = 0; } return count; } public bool Exists { get { if (!__hasBeenReadOnce) Exist(); return __databaseState == RowState.Initialized; } } public UndoRedoOptions() {} public UndoRedoOptions(System.String __EntityType) { Read(__EntityType); } #region CRUD void Exist() { // sql read - should be changed to specific exist implementation using (DbConnection dbconn = InstanceConnectionProvider.GetDatabaseConnection(ConnectionString)) { dbconn.Open(); DbCommand command = InstanceConnectionProvider.GetDatabaseCommand("UnReOpRead", dbconn); command.CommandType = global::System.Data.CommandType.StoredProcedure; DbParameter param_EntityType = ClassConnectionProvider.GetDatabaseParameter("EntityType", typeof(System.String), 128); param_EntityType.Value = ClassConnectionProvider.FromValueToSqlModelType(_EntityType); command.Parameters.Add(param_EntityType); InstanceConnectionProvider.OnBeforeExecuted(command); DbDataReader dr = command.ExecuteReader(global::System.Data.CommandBehavior.CloseConnection); if (dr.Read()) { __databaseState = RowState.Initialized; } else { __databaseState = RowState.Empty; } __hasBeenReadOnce = true; dr.Close(); } } public void Read(System.String __EntityType) { if (scalingServices != null) { // Forwarding can be used in any scenario (read & write) if (scalingServices.Count == 1) { scalingServices[0].Read(__EntityType); return; } // Get a service via an algorithm // int nextIndex = serviceSelectionAlgorithm.Pick(scalingServices, "UnReOp"); // Perfect for read operations, but not for write // scalingServices[nextIndex].Read(__EntityType); // return; throw new NotImplementedException(); } try { // sql read using (DbConnection dbconn = InstanceConnectionProvider.GetDatabaseConnection(ConnectionString)) { dbconn.Open(); DbCommand command = InstanceConnectionProvider.GetDatabaseCommand("UnReOpRead", dbconn); command.CommandType = global::System.Data.CommandType.StoredProcedure; _EntityType = __EntityType; DbParameter param_EntityType = ClassConnectionProvider.GetDatabaseParameter("EntityType", typeof(System.String), 128); param_EntityType.Value = ClassConnectionProvider.FromValueToSqlModelType(__EntityType); command.Parameters.Add(param_EntityType); InstanceConnectionProvider.OnBeforeExecuted(command); DbDataReader dr = command.ExecuteReader(global::System.Data.CommandBehavior.CloseConnection); if (dr.Read()) { _EntityType = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["EntityType"], typeof(System.String)); _ItemsAllowed = (System.Int64) global::Platform.Runtime.Utilities.FromSqlToValue(dr["ItemsAllowed"], typeof(System.Int64)); _IsEnabled = (System.Boolean) global::Platform.Runtime.Utilities.FromSqlToValue(dr["IsEnabled"], typeof(System.Boolean)); __databaseState = RowState.Initialized; } else { __databaseState = RowState.Empty; } __hasBeenReadOnce = true; dr.Close(); } } catch (Exception ex) { if (failoverServices != null) { bool foundFailsafe = false; for (int n = 0; n < failoverServices.Count; ++n) { try { failoverServices[n].Read(__EntityType); foundFailsafe = true; break; } catch { // Do not request again from failed services failoverServices.RemoveAt(n); --n; } } if (failoverServices.Count == 0) failoverServices = null; if (!foundFailsafe) throw ex; } else throw ex; } } public void Reload() { if (scalingServices != null) { // Forwarding can be used in any scenario (read & write) if (scalingServices.Count == 1) { scalingServices[0].Reload(this); return; } // Get a service via an algorithm // int nextIndex = serviceSelectionAlgorithm.GetNext(scalingServices, "UnReOp"); // Perfect for read operations, but not for write // return scalingServices[nextIndex].Reload(); throw new NotImplementedException(); } try { // sql read using (DbConnection dbconn = InstanceConnectionProvider.GetDatabaseConnection(ConnectionString)) { dbconn.Open(); DbCommand command = InstanceConnectionProvider.GetDatabaseCommand("UnReOpRead", dbconn); command.CommandType = global::System.Data.CommandType.StoredProcedure; DbParameter param_EntityType = ClassConnectionProvider.GetDatabaseParameter("EntityType", typeof(System.String), 128); param_EntityType.Value = ClassConnectionProvider.FromValueToSqlModelType(_EntityType); command.Parameters.Add(param_EntityType); InstanceConnectionProvider.OnBeforeExecuted(command); DbDataReader dr = command.ExecuteReader(global::System.Data.CommandBehavior.CloseConnection); if (dr.Read()) { _EntityType = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["EntityType"], typeof(System.String)); _ItemsAllowed = (System.Int64) global::Platform.Runtime.Utilities.FromSqlToValue(dr["ItemsAllowed"], typeof(System.Int64)); _IsEnabled = (System.Boolean) global::Platform.Runtime.Utilities.FromSqlToValue(dr["IsEnabled"], typeof(System.Boolean)); __databaseState = RowState.Initialized; } else { __databaseState = RowState.Empty; } __hasBeenReadOnce = true; dr.Close(); } } catch (Exception ex) { if (failoverServices != null) { bool foundFailsafe = false; for (int n = 0; n < failoverServices.Count; ++n) { try { failoverServices[n].Reload(this); foundFailsafe = true; break; } catch { // Do not request again from failed services failoverServices.RemoveAt(n); --n; } } if (failoverServices.Count == 0) failoverServices = null; if (!foundFailsafe) throw ex; } else throw ex; } } public void Create() { if (scalingServices != null) { // Forwarding can be used in any scenario (read & write) if (scalingServices.Count == 1) { scalingServices[0].CreateObject(this); return; } // Create/Update/Delete supports scaling only by synchronizing // scalingServices[0].CreateObject(this); // scalingServices[0].SynchronizeTo(scalingServices); throw new NotImplementedException(); } try { if (!Exists) { // Mark undo if possible /* if (IsUndoRedoSupported) MarkUndo(this, true, false, false); //*/ // sql create using (DbConnection dbconn = InstanceConnectionProvider.GetDatabaseConnection(ConnectionString)) { dbconn.Open(); DbCommand command = InstanceConnectionProvider.GetDatabaseCommand("UnReOpCreate", dbconn); command.CommandType = global::System.Data.CommandType.StoredProcedure; DbParameter param_EntityType = ClassConnectionProvider.GetDatabaseParameter("EntityType", typeof(System.String), 128); param_EntityType.Value = ClassConnectionProvider.FromValueToSqlModelType(_EntityType); command.Parameters.Add(param_EntityType); DbParameter param_ItemsAllowed = ClassConnectionProvider.GetDatabaseParameter("ItemsAllowed", typeof(System.Int64), -1); param_ItemsAllowed.Value = ClassConnectionProvider.FromValueToSqlModelType(_ItemsAllowed); command.Parameters.Add(param_ItemsAllowed); DbParameter param_IsEnabled = ClassConnectionProvider.GetDatabaseParameter("IsEnabled", typeof(System.Boolean), -1); param_IsEnabled.Value = ClassConnectionProvider.FromValueToSqlModelType(_IsEnabled); command.Parameters.Add(param_IsEnabled); InstanceConnectionProvider.OnBeforeExecuted(command); DbDataReader dr = command.ExecuteReader(global::System.Data.CommandBehavior.CloseConnection); if (dr.Read()) { _EntityType = (System.String) global::Platform.Runtime.Utilities.FromSqlToValue(dr["EntityType"], typeof(System.String)); _ItemsAllowed = (System.Int64) global::Platform.Runtime.Utilities.FromSqlToValue(dr["ItemsAllowed"], typeof(System.Int64)); _IsEnabled = (System.Boolean) global::Platform.Runtime.Utilities.FromSqlToValue(dr["IsEnabled"], typeof(System.Boolean)); } __databaseState = RowState.Initialized; } } else Update(); } catch (Exception) { // Failsafe scenarios cannot be used for create/update/delete // Must be handled as an error throw; } // Everything went ok; now replicate in a synchronous way if (replicationServices != null) { // this is only for write/delete operations for (int n = 0; n < replicationServices.Count; ++n) { try { replicationServices[n].CreateObject(this); } catch { // Do not request again from failed services replicationServices.RemoveAt(n); --n; } } if (replicationServices.Count == 0) replicationServices = null; } } static public UndoRedoOptions CreateUndoRedoOptions(System.String __EntityType) { UndoRedoOptions o = new UndoRedoOptions(__EntityType); if (!o.Exists) o.Create(); return o; } public void Update() { if (scalingServices != null) { // Forwarding can be used in any scenario (read & write) if (scalingServices.Count == 1) { scalingServices[0].UpdateObject(this); return; } // Create/Update/Delete supports scaling only by synchronizing // scalingServices[0].UpdateObject(this); throw new NotImplementedException(); } try { if (!Exists) { this.Create(); return; } // Mark undo if possible /* if (IsUndoRedoSupported) MarkUndo(this, false, false, true); //*/ // sql update using (DbConnection dbconn = InstanceConnectionProvider.GetDatabaseConnection(ConnectionString)) { dbconn.Open(); DbCommand command = InstanceConnectionProvider.GetDatabaseCommand("UnReOpUpdate", dbconn); command.CommandType = global::System.Data.CommandType.StoredProcedure; DbParameter param_EntityType = ClassConnectionProvider.GetDatabaseParameter("EntityType", typeof(System.String), 128); param_EntityType.Value = ClassConnectionProvider.FromValueToSqlModelType(_EntityType); command.Parameters.Add(param_EntityType); DbParameter param_ItemsAllowed = ClassConnectionProvider.GetDatabaseParameter("ItemsAllowed", typeof(System.Int64), -1); param_ItemsAllowed.Value = ClassConnectionProvider.FromValueToSqlModelType(_ItemsAllowed); command.Parameters.Add(param_ItemsAllowed); DbParameter param_IsEnabled = ClassConnectionProvider.GetDatabaseParameter("IsEnabled", typeof(System.Boolean), -1); param_IsEnabled.Value = ClassConnectionProvider.FromValueToSqlModelType(_IsEnabled); command.Parameters.Add(param_IsEnabled); command.ExecuteNonQuery(); } } catch (Exception) { // Failsafe scenarios cannot be used for create/update/delete // Must be handled as an error throw; } // Everything went ok; now replicate in a synchronous way if (replicationServices != null) { // this is only for write/delete operations for (int n = 0; n < replicationServices.Count; ++n) { try { replicationServices[n].UpdateObject(this); } catch { // Do not request again from failed services replicationServices.RemoveAt(n); --n; } } if (replicationServices.Count == 0) replicationServices = null; } } public void Delete() { if (scalingServices != null) { // Forwarding can be used in any scenario (read & write) if (scalingServices.Count == 1) { scalingServices[0].DeleteObject(this); return; } // Create/Update/Delete supports scaling only by synchronizing // scalingServices[0].DeleteObject(this); throw new NotImplementedException(); } try { if (!Exists) return; // Mark undo if possible /* if (IsUndoRedoSupported) MarkUndo(this, false, true, false); //*/ // sql-delete using (DbConnection dbconn = InstanceConnectionProvider.GetDatabaseConnection(ConnectionString)) { dbconn.Open(); DbCommand command = InstanceConnectionProvider.GetDatabaseCommand("UnReOpDelete", dbconn); command.CommandType = global::System.Data.CommandType.StoredProcedure; DbParameter param_EntityType = ClassConnectionProvider.GetDatabaseParameter("EntityType", typeof(System.String), 128); param_EntityType.Value = ClassConnectionProvider.FromValueToSqlModelType(_EntityType); command.Parameters.Add(param_EntityType); command.ExecuteNonQuery(); __databaseState = RowState.Empty; } } catch (Exception) { // Failsafe scenarios cannot be used for create/update/delete // Must be handled as an error throw; } // Everything went ok; now replicate in a synchronous way if (replicationServices != null) { // this is only for write/delete operations for (int n = 0; n < replicationServices.Count; ++n) { try { replicationServices[n].DeleteObject(this); } catch { // Do not request again from failed services replicationServices.RemoveAt(n); --n; } } if (replicationServices.Count == 0) replicationServices = null; } } static public void DeleteUndoRedoOptions(System.String __EntityType) { UndoRedoOptions o = new UndoRedoOptions(__EntityType); if (o.Exists) o.Delete(); } #endregion #region Copying instances public void CopyWithKeysFrom(UndoRedoOptions _object) { _EntityType = _object._EntityType; _ItemsAllowed = _object._ItemsAllowed; _IsEnabled = _object._IsEnabled; } public void CopyWithKeysTo(UndoRedoOptions _object) { _object._EntityType = _EntityType; _object._ItemsAllowed = _ItemsAllowed; _object._IsEnabled = _IsEnabled; } static public void CopyWithKeysObject(UndoRedoOptions _objectFrom, UndoRedoOptions _objectTo) { _objectFrom.CopyWithKeysTo(_objectTo); } public void CopyFrom(UndoRedoOptions _object) { _ItemsAllowed = _object._ItemsAllowed; _IsEnabled = _object._IsEnabled; } public void CopyTo(UndoRedoOptions _object) { _object._ItemsAllowed = _ItemsAllowed; _object._IsEnabled = _IsEnabled; } static public void CopyObject(UndoRedoOptions _objectFrom, UndoRedoOptions _objectTo) { _objectFrom.CopyTo(_objectTo); } #endregion #region Undo / Redo functionality /* private static bool isUndoRedoSupported = false; private static bool isUndoRedoSupportedHasBeenLoaded = false; private static long undoRedoMaximumObjects = -1; public static bool IsUndoRedoSupported { get { if (!isUndoRedoSupportedHasBeenLoaded) { // Load options undo entity once isUndoRedoSupportedHasBeenLoaded = true; Platform.Module.UndoRedo.Services.Packages.UndoRedoOptions options = new Platform.Module.UndoRedo.Services.Packages.UndoRedoOptions(typeof(UndoRedoOptions).FullName); if (!options.Exists) { undoRedoMaximumObjects = options.ItemsAllowed = 1000; options.IsEnabled = true; options.Create(); isUndoRedoSupported = true; } else { isUndoRedoSupported = options.IsEnabled; undoRedoMaximumObjects = options.ItemsAllowed; } } return isUndoRedoSupported; } set { isUndoRedoSupportedHasBeenLoaded = true; isUndoRedoSupported = value; Platform.Module.UndoRedo.Services.Packages.UndoRedoOptions options = new Platform.Module.UndoRedo.Services.Packages.UndoRedoOptions(typeof(UndoRedoOptions).FullName); if (!options.Exists) { undoRedoMaximumObjects = options.ItemsAllowed = 1000; } options.IsEnabled = isUndoRedoSupported; options.Update(); } } static void MarkUndo(UndoRedoOptions _object, bool IsCreatedUndoDeletes, bool IsDeletedUndoCreates, bool IsUpdatedUndoUpdates) { // Delete already undone entries (steps that have been undone but not redone) UndoRedoOptionsUndoRedoCollection allUndidAndNotRedoneEntries = UndoRedoOptionsUndoRedo.GetAllFilterByIsUndone(true); for(int n = 0; n < allUndidAndNotRedoneEntries.Count; ++n) allUndidAndNotRedoneEntries[n].Delete(); // Create one undo entry UndoRedoOptionsUndoRedo _urobject = new UndoRedoOptionsUndoRedo(); // Enumerate all properties and add them to the UndoRedo object _urobject.EntityType = _object._EntityType; _urobject.ItemsAllowed = _object._ItemsAllowed; _urobject.IsEnabled = _object._IsEnabled; _urobject.IsCreatedUndoDeletes = IsCreatedUndoDeletes; _urobject.IsDeletedUndoCreates = IsDeletedUndoCreates; _urobject.IsUpdatedUndoUpdates = IsUpdatedUndoUpdates; _urobject.Create(); // Add this to all groups if needed Platform.Module.UndoRedo.Services.Packages.Grouping.GroupEntry(typeof(UndoRedoOptions).FullName, _urobject.UndoRedoId); // Check if we have too many - if yes delete the oldest entry long count = UndoRedoOptionsUndoRedo.GetAllWithNoFilterCount(true) - undoRedoMaximumObjects; if (count > 0) { UndoRedoOptionsUndoRedoCollection allOldUndoEntries = UndoRedoOptionsUndoRedo.GetAllWithNoFilterOppositeSortingPaged(true, 0, count); for(int n = 0; n < allOldUndoEntries.Count; ++n) allOldUndoEntries[n].Delete(); } } static public void Undo() { // Load the last undo, and execute it UndoRedoOptionsUndoRedoCollection firstUndoEntries = UndoRedoOptionsUndoRedo.GetAllFilterByIsUndonePaged(false, 0, 1); if (firstUndoEntries.Count < 1) return; UndoRedoOptionsUndoRedo _urobject = firstUndoEntries[0]; UndoRedoOptions _object = new UndoRedoOptions(); _object._EntityType = _urobject.EntityType; _object._ItemsAllowed = _urobject.ItemsAllowed; _object._IsEnabled = _urobject.IsEnabled; _urobject.IsUndone = true; _urobject.Update(); // Do the opposite action if (_urobject.IsDeletedUndoCreates || _urobject.IsUpdatedUndoUpdates) _object.Create(); // Create or update store else if (_urobject.IsCreatedUndoDeletes) _object.Delete(); // Delete } static public void Redo() { // Get the last already undone and load it UndoRedoOptionsUndoRedoCollection firstEntryToRedoEntries = UndoRedoOptionsUndoRedo.GetAllFilterByIsUndoneOppositeOrderPaged(true, 0, 1); if (firstEntryToRedoEntries.Count < 1) return; UndoRedoOptionsUndoRedo _urobject = firstEntryToRedoEntries[0]; UndoRedoOptions _object = new UndoRedoOptions(); _object._EntityType = _urobject.EntityType; _object._ItemsAllowed = _urobject.ItemsAllowed; _object._IsEnabled = _urobject.IsEnabled; _urobject.IsUndone = false; _urobject.Update(); // Do the opposite action if (_urobject.IsDeletedUndoCreates) _object.Delete(); // Delete again else if (_urobject.IsCreatedUndoDeletes || _urobject.IsUpdatedUndoUpdates) _object.Create(); // Create or update again } //*/ // Undo redo enabled //* static public void Undo() { throw new NotImplementedException("This feature is not implemented in this class."); } static public void Redo() { throw new NotImplementedException("This feature is not implemented in this class."); } //*/ // Undo redo disabled #endregion #endregion #region IHierarchyData Members IHierarchicalEnumerable IHierarchyData.GetChildren() { string selectedProperty = (__level < __childProperties.Length ? __childProperties[__level] : __childProperties[__childProperties.Length - 1]); global::System.Reflection.PropertyInfo pi = this.GetType().GetProperty(selectedProperty); if (pi == null) throw new NullReferenceException("Property '" + selectedProperty + "' does not exist in type " + this.GetType().FullName); IHierarchicalEnumerable dataSource = pi.GetValue(this, null) as IHierarchicalEnumerable; foreach (IHierarchyData ihd in dataSource) { global::Platform.Runtime.Data.IModelHierachyData imhd = ihd as global::Platform.Runtime.Data.IModelHierachyData; if (imhd != null) { imhd.Level = __level + 1; imhd.ParentProperties = __parentProperties; imhd.ChildProperties = __childProperties; } } return dataSource; } IHierarchyData IHierarchyData.GetParent() { string selectedProperty = (__level < __parentProperties.Length ? __parentProperties[__level] : __parentProperties[__parentProperties.Length - 1]); global::System.Reflection.PropertyInfo pi = this.GetType().GetProperty(selectedProperty); if (pi == null) throw new NullReferenceException("Property '" + selectedProperty + "' does not exist in type " + this.GetType().FullName); IHierarchyData data = pi.GetValue(this, null) as IHierarchyData; global::Platform.Runtime.Data.IModelHierachyData imhd = data as global::Platform.Runtime.Data.IModelHierachyData; if (imhd != null) { imhd.Level = __level - 1; imhd.ParentProperties = __parentProperties; imhd.ChildProperties = __childProperties; } return data; } bool IHierarchyData.HasChildren { get { string selectedProperty = (__level < __childProperties.Length ? __childProperties[__level] : __childProperties[__childProperties.Length - 1]); global::System.Reflection.PropertyInfo pi = this.GetType().GetProperty(selectedProperty); if (pi == null) throw new NullReferenceException("Property '" + selectedProperty + "' does not exist in type " + this.GetType().FullName); IHierarchicalEnumerable value = pi.GetValue(this, null) as IHierarchicalEnumerable; bool exists = false; foreach(IHierarchyData ihd in value) { exists = true; break; } return exists; } } object IHierarchyData.Item { get { return this; } } string IHierarchyData.Path { get { return ""; } } string IHierarchyData.Type { get { return this.GetType().FullName; } } #endregion #region Platform.Runtime.Data.IHierarchyData explicit Members [NonSerialized] string[] __childProperties = null; [NonSerialized] string[] __parentProperties = null; [NonSerialized] int __level = -1; string[] Platform.Runtime.Data.IModelHierachyData.ChildProperties { get { return __childProperties; } set { __childProperties = value; } } string[] Platform.Runtime.Data.IModelHierachyData.ParentProperties { get { return __parentProperties; } set { __parentProperties = value; } } int Platform.Runtime.Data.IModelHierachyData.Level { get { return __level; } set { __level = value; } } #endregion } /// <summary> /// Defines the contract for the UndoRedoOptionsCollection class /// </summary> [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsDual)] [Guid("a06dd1cd-3011-3ee0-bd80-011afb5b682a")] public interface IUndoRedoOptionsCollection : IEnumerable<UndoRedoOptions> { int IndexOf(UndoRedoOptions item); void Insert(int index, UndoRedoOptions item); void RemoveAt(int index); UndoRedoOptions this[int index] { get; set; } void Add(UndoRedoOptions item); void Clear(); bool Contains(UndoRedoOptions item); void CopyTo(UndoRedoOptions[] array, int arrayIndex); int Count { get; } bool IsReadOnly { get; } bool Remove(UndoRedoOptions item); } /// <summary> /// Provides the implementation of the class that represents a list of Platform.Module.UndoRedo.Services.Packages.UndoRedoOptions /// </summary> [ClassInterface(ClassInterfaceType.None)] [Guid("82b3ce79-efd5-0b0a-e877-cce539fca70f")] [DataContract] [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute] [Serializable] public class UndoRedoOptionsCollection : IUndoRedoOptionsCollection, IList<UndoRedoOptions>, IHierarchicalEnumerable { List<UndoRedoOptions> _list = new List<UndoRedoOptions>(); public static implicit operator List<UndoRedoOptions>(UndoRedoOptionsCollection collection) { return collection._list; } #region IList<UndoRedoOptions> Members public int IndexOf(UndoRedoOptions item) { return _list.IndexOf(item); } public void Insert(int index, UndoRedoOptions item) { _list.Insert(index, item); } public void RemoveAt(int index) { _list.RemoveAt(index); } public UndoRedoOptions this[int index] { get { return _list[index]; } set { _list[index] = value; } } #endregion #region ICollection<UndoRedoOptions> Members public void Add(UndoRedoOptions item) { _list.Add(item); } public void Clear() { _list.Clear(); } public bool Contains(UndoRedoOptions item) { return _list.Contains(item); } public void CopyTo(UndoRedoOptions[] array, int arrayIndex) { _list.CopyTo(array, arrayIndex); } public int Count { get { return _list.Count; } } public bool IsReadOnly { get { return false; } } public bool Remove(UndoRedoOptions item) { return _list.Remove(item); } #endregion #region IEnumerable<UndoRedoOptions> Members public IEnumerator<UndoRedoOptions> GetEnumerator() { return _list.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((System.Collections.IEnumerable)_list).GetEnumerator(); } #endregion #region IHierarchicalEnumerable Members public IHierarchyData GetHierarchyData(object enumeratedItem) { return enumeratedItem as IHierarchyData; } #endregion } namespace Web { /// <summary> /// The WebService service provider that allows to create web services /// that share Platform.Module.UndoRedo.Services.Packages.UndoRedoOptions objects. /// </summary> /// <example> /// You can use that in the header of an asmx file like this: /// <%@ WebService Language="C#" Class="Platform.Module.UndoRedo.Services.Packages.Web.UndoRedoOptionsWebService" %> /// </example> [WebService(Namespace="http://services.msd.com")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute] [ComVisible(false)] sealed public class UndoRedoOptionsWebService : WebService, IUndoRedoOptionsService { /// <summary> /// Gets the Uri if the service. Setting property is not supported. /// </summary> public string Uri { get { return "http://services.msd.com"; } set { throw new NotSupportedException(); } } [WebMethod] public bool Exists(UndoRedoOptions _UndoRedoOptions) { return _UndoRedoOptions.Exists; } [WebMethod] public UndoRedoOptions Read(System.String __EntityType) { return new UndoRedoOptions(__EntityType); } [WebMethod] public UndoRedoOptions Reload(UndoRedoOptions _UndoRedoOptions) { _UndoRedoOptions.Reload(); return _UndoRedoOptions; } [WebMethod] public UndoRedoOptions Create(System.String __EntityType) { return UndoRedoOptions.CreateUndoRedoOptions(__EntityType); } [WebMethod] public void Delete(System.String __EntityType) { UndoRedoOptions.DeleteUndoRedoOptions(__EntityType); } [WebMethod] public void UpdateObject(UndoRedoOptions _UndoRedoOptions) { _UndoRedoOptions.Update(); } [WebMethod] public void CreateObject(UndoRedoOptions _UndoRedoOptions) { _UndoRedoOptions.Create(); } [WebMethod] public void DeleteObject(UndoRedoOptions _UndoRedoOptions) { _UndoRedoOptions.Delete(); } [WebMethod] public void Undo() { UndoRedoOptions.Undo(); } [WebMethod] public void Redo() { UndoRedoOptions.Redo(); } [WebMethod] public UndoRedoOptionsCollection SearchByEntityType(System.String EntityType ) { return UndoRedoOptions.SearchByEntityType(EntityType ); } [WebMethod] public UndoRedoOptionsCollection SearchByEntityTypePaged(System.String EntityType , long PagingStart, long PagingCount) { return UndoRedoOptions.SearchByEntityTypePaged(EntityType , PagingStart, PagingCount); } [WebMethod] public long SearchByEntityTypeCount(System.String EntityType ) { return UndoRedoOptions.SearchByEntityTypeCount(EntityType ); } } /// <summary> /// The WebService client service /// </summary> [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Web.Services.WebServiceBindingAttribute(Name="UndoRedoOptionsWebServiceSoap", Namespace="http://services.msd.com")] [System.Xml.Serialization.XmlIncludeAttribute(typeof(MarshalByRefObject))] [ComVisible(true)] [ClassInterface(ClassInterfaceType.None)] [Guid("4278d6a4-fa95-d4b0-ec4d-6750868a4388")] sealed public class UndoRedoOptionsWebServiceClient : System.Web.Services.Protocols.SoapHttpClientProtocol, IUndoRedoOptionsService { static string globalUrl; /// <summary> /// By setting this value, all the subsequent clients that using the default /// constructor will point to the service that this url points to. /// </summary> static public string GlobalUrl { get { return globalUrl; } set { globalUrl = value; } } /// <summary> /// Initializes a web service client using the url as the service endpoint. /// </summary> /// <param name="url">The service url that the object will point to</param> public UndoRedoOptionsWebServiceClient(string url) { this.Url = url; } /// <summary> /// Initializes a web service client without a specific service url. /// If the GlobalUrl value is set, is been used as the Url. /// </summary> public UndoRedoOptionsWebServiceClient() { if (!String.IsNullOrEmpty(globalUrl)) this.Url = globalUrl; } /// <summary> /// Allows the service to set the Uri for COM compatibility. Is the same with Url property. /// </summary> public string Uri { get { return this.Url; } set { this.Url = value; } } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/Exists", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public bool Exists(UndoRedoOptions _UndoRedoOptions) { object[] results = this.Invoke("Exists", new object[] {_UndoRedoOptions}); return ((bool)(results[0])); } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/Read", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public UndoRedoOptions Read(System.String __EntityType) { object[] results = this.Invoke("Read", new object[] {__EntityType}); return ((UndoRedoOptions)(results[0])); } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/Reload", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public UndoRedoOptions Reload(UndoRedoOptions _UndoRedoOptions) { object[] results = this.Invoke("Reload", new object[] {_UndoRedoOptions}); return ((UndoRedoOptions)(results[0])); } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/Create", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public UndoRedoOptions Create(System.String __EntityType) { object[] results = this.Invoke("Create", new object[] {__EntityType}); return ((UndoRedoOptions)(results[0])); } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/Delete", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void Delete(System.String __EntityType) { this.Invoke("Delete", new object[] {__EntityType}); return; } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/UpdateObject", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void UpdateObject(UndoRedoOptions _UndoRedoOptions) { this.Invoke("UpdateObject", new object[] {_UndoRedoOptions}); return; } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/CreateObject", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void CreateObject(UndoRedoOptions _UndoRedoOptions) { this.Invoke("CreateObject", new object[] {_UndoRedoOptions}); return; } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/DeleteObject", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void DeleteObject(UndoRedoOptions _UndoRedoOptions) { this.Invoke("DeleteObject", new object[] {_UndoRedoOptions}); return; } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/Undo", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void Undo() { this.Invoke("Undo", new object[] {}); return; } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/Redo", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void Redo() { this.Invoke("Redo", new object[] {}); return; } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/SearchByEntityType", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public UndoRedoOptionsCollection SearchByEntityType(System.String EntityType ) { object[] results = this.Invoke("SearchByEntityType", new object[] {EntityType}); return ((UndoRedoOptionsCollection)(results[0])); } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/SearchByEntityTypePaged", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public UndoRedoOptionsCollection SearchByEntityTypePaged(System.String EntityType , long PagingStart, long PagingCount) { object[] results = this.Invoke("SearchByEntityTypePaged", new object[] {EntityType,PagingStart,PagingCount}); return ((UndoRedoOptionsCollection)(results[0])); } [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://services.msd.com/SearchByEntityTypeCount", RequestNamespace="http://services.msd.com", ResponseNamespace="http://services.msd.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public long SearchByEntityTypeCount(System.String EntityType ) { object[] results = this.Invoke("SearchByEntityTypeCount", new object[] {EntityType}); return ((long)(results[0])); } } } // namespace Web } // namespace Platform.Module.UndoRedo.Services.Packages
//--------------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // // Description: TypefaceMap class // // Created: 5-16-2003 Worachai Chaoweeraprasit (wchao) // History: 5-19-2005 garyyang, restructure the glyphing cache structure. // //--------------------------------------------------------------------------- using System; using System.Security; using System.Security.Permissions; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Diagnostics; using System.Windows; using System.Windows.Media; using System.Windows.Media.TextFormatting; using MS.Utility; using MS.Internal; using MS.Internal.Generic; using MS.Internal.FontCache; using MS.Internal.FontFace; using MS.Internal.TextFormatting; using System.Runtime.InteropServices; using FontFace = MS.Internal.FontFace; namespace MS.Internal.Shaping { /// <summary> /// TypefaceMap class. It maps characters to corresponding ShapeTypeface through font linking logic. /// It also caches the mapping results such that same code points doesn't need to go through all /// the font linking process again. /// </summary> internal class TypefaceMap { private FontFamily[] _fontFamilies; private FontStyle _canonicalStyle; private FontWeight _canonicalWeight; private FontStretch _canonicalStretch; private bool _nullFont; private IList<ScaledShapeTypeface> _cachedScaledTypefaces = new List<ScaledShapeTypeface>(InitialScaledGlyphableTypefaceCount); private IDictionary<CultureInfo, IntMap> _intMaps = new Dictionary<CultureInfo, IntMap>(); // Constants private const int InitialScaledGlyphableTypefaceCount = 2; private const int MaxTypefaceMapDepths = 32; internal TypefaceMap( FontFamily fontFamily, FontFamily fallbackFontFamily, FontStyle canonicalStyle, FontWeight canonicalWeight, FontStretch canonicalStretch, bool nullFont ) { Invariant.Assert(fontFamily != null); _fontFamilies = fallbackFontFamily == null ? new FontFamily[] { fontFamily } : new FontFamily[] { fontFamily, fallbackFontFamily }; _canonicalStyle = canonicalStyle; _canonicalWeight = canonicalWeight; _canonicalStretch = canonicalStretch; _nullFont = nullFont; } /// <summary> /// Compute a list of shapeable text objects for the specified character string /// </summary> /// <SecurityNote> /// Critical - calls critical methods (PinAndGetCharacterPointer, Itemize) /// TreatAsSafe - only returns shaping info for the given string /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal void GetShapeableText( CharacterBufferReference characterBufferReference, int stringLength, TextRunProperties textRunProperties, CultureInfo digitCulture, bool isRightToLeftParagraph, IList<TextShapeableSymbols> shapeableList, IShapeableTextCollector collector, TextFormattingMode textFormattingMode ) { SpanVector<int> cachedScaledTypefaceIndexSpans; int ichItem = 0; CharacterBufferRange unicodeString = new CharacterBufferRange( characterBufferReference, stringLength ); CultureInfo culture = textRunProperties.CultureInfo; IList<Span> spans; GCHandle gcHandle; IntPtr ptext = characterBufferReference.CharacterBuffer.PinAndGetCharacterPointer(characterBufferReference.OffsetToFirstChar, out gcHandle); // Contextual number substitution cannot be performed on the run level, since it depends // on context - nearest preceding strong character. For this reason, contextual number // substitutions has been already done (TextStore.CreateLSRunsUniformBidiLevel) and // digitCulture has been updated to reflect culture which is dependent on the context. // NumberSubstitutionMethod.AsCulture method can be resolved to Context, hence it also needs to be resolved to appropriate // not ambiguous method. // Both of those values (Context and AsCulture) are resolved to one of following: European, Traditional or NativeNational, // which can be safely handled by DWrite without getting context information. bool ignoreUserOverride; NumberSubstitutionMethod numberSubstitutionMethod = DigitState.GetResolvedSubstitutionMethod(textRunProperties, digitCulture, out ignoreUserOverride); // Itemize the text based on DWrite's text analysis for scripts and number substitution. unsafe { checked { spans = MS.Internal.Text.TextInterface.TextAnalyzer.Itemize( (ushort*)ptext.ToPointer(), (uint)stringLength, culture, MS.Internal.FontCache.DWriteFactory.Instance, isRightToLeftParagraph, digitCulture, ignoreUserOverride, (uint)numberSubstitutionMethod, ClassificationUtility.Instance, UnsafeNativeMethods.CreateTextAnalysisSink, UnsafeNativeMethods.GetScriptAnalysisList, UnsafeNativeMethods.GetNumberSubstitutionList, UnsafeNativeMethods.CreateTextAnalysisSource ); } } characterBufferReference.CharacterBuffer.UnpinCharacterPointer(gcHandle); SpanVector itemSpans = new SpanVector(null, new FrugalStructList<Span>((ICollection<Span>)spans)); cachedScaledTypefaceIndexSpans = new SpanVector<int>(-1); foreach(Span itemSpan in itemSpans) { MapItem( new CharacterBufferRange( unicodeString, ichItem, itemSpan.length ), culture, itemSpan, ref cachedScaledTypefaceIndexSpans, ichItem ); #if DEBUG ValidateMapResult( ichItem, itemSpan.length, ref cachedScaledTypefaceIndexSpans ); #endif ichItem += itemSpan.length; } Debug.Assert(ichItem == unicodeString.Length); // intersect item spans with shapeable spans to create span of shapeable runs int ich = 0; SpanRider itemSpanRider = new SpanRider(itemSpans); SpanRider<int> typefaceIndexSpanRider = new SpanRider<int>(cachedScaledTypefaceIndexSpans); while(ich < unicodeString.Length) { itemSpanRider.At(ich); typefaceIndexSpanRider.At(ich); int index = typefaceIndexSpanRider.CurrentValue; Debug.Assert(index >= 0); int cch = unicodeString.Length - ich; cch = Math.Min(cch, itemSpanRider.Length); cch = Math.Min(cch, typefaceIndexSpanRider.Length); ScaledShapeTypeface scaledShapeTypeface = _cachedScaledTypefaces[index]; collector.Add( shapeableList, new CharacterBufferRange( unicodeString, ich, cch ), textRunProperties, (MS.Internal.Text.TextInterface.ItemProps)itemSpanRider.CurrentElement, scaledShapeTypeface.ShapeTypeface, scaledShapeTypeface.ScaleInEm, scaledShapeTypeface.NullShape, textFormattingMode ); ich += cch; } } #if DEBUG private unsafe void ValidateMapResult( int ichRange, int cchRange, ref SpanVector<int> cachedScaledTypefaceIndexSpans ) { int ich = 0; SpanRider<int> typefaceIndexSpanRider = new SpanRider<int>(cachedScaledTypefaceIndexSpans); while(ich < cchRange) { typefaceIndexSpanRider.At(ichRange + ich); if((int)typefaceIndexSpanRider.CurrentValue < 0) { Debug.Assert(false, "Invalid font face spans"); return; } int cch = Math.Min(cchRange - ich, typefaceIndexSpanRider.Length); ich += cch; } } #endif private void MapItem( CharacterBufferRange unicodeString, CultureInfo culture, Span itemSpan, ref SpanVector<int> cachedScaledTypefaceIndexSpans, int ichItem ) { CultureInfo digitCulture = ((MS.Internal.Text.TextInterface.ItemProps)itemSpan.element).DigitCulture; bool isCached = GetCachedScaledTypefaceMap( unicodeString, culture, digitCulture, ref cachedScaledTypefaceIndexSpans, ichItem ); if(!isCached) { // shapeable typeface to shape each character in the item has not been located, // look thru information in font family searching for the right shapeable typeface. SpanVector scaledTypefaceSpans = new SpanVector(null); int nextValid; // we haven't yet found a valid physical font family PhysicalFontFamily firstValidFamily = null; int firstValidLength = 0; if (!_nullFont) { MapByFontFamilyList( unicodeString, culture, digitCulture, _fontFamilies, ref firstValidFamily, ref firstValidLength, null, // device font 1.0, // default size is one em 0, // recursion depth scaledTypefaceSpans, 0, // firstCharIndex out nextValid ); } else { MapUnresolvedCharacters( unicodeString, culture, digitCulture, firstValidFamily, ref firstValidLength, scaledTypefaceSpans, 0, // firstCharIndex out nextValid ); } CacheScaledTypefaceMap( unicodeString, culture, digitCulture, scaledTypefaceSpans, ref cachedScaledTypefaceIndexSpans, ichItem ); } } /// <summary> /// Get spans of index to the list of scaled shapeable typeface of the specified /// character string from the map table /// </summary> private bool GetCachedScaledTypefaceMap( CharacterBufferRange unicodeString, CultureInfo culture, CultureInfo digitCulture, ref SpanVector<int> cachedScaledTypefaceIndexSpans, int ichItem ) { IntMap map; if (!_intMaps.TryGetValue(culture, out map)) { return false; } DigitMap digitMap = new DigitMap(digitCulture); int ich = 0; while (ich < unicodeString.Length) { // Get map entry for first character. int sizeofChar; int ch = digitMap[ Classification.UnicodeScalar( new CharacterBufferRange(unicodeString, ich, unicodeString.Length - ich), out sizeofChar ) ]; ushort firstIndex = map[ch]; if (firstIndex == 0) return false; // Advance past subsequent characters with the same mapping. int cchSpan = sizeofChar; for (; ich + cchSpan < unicodeString.Length; cchSpan += sizeofChar) { ch = digitMap[ Classification.UnicodeScalar( new CharacterBufferRange(unicodeString, ich + cchSpan, unicodeString.Length - ich - cchSpan), out sizeofChar ) ]; if (map[ch] != firstIndex && !Classification.IsCombining(ch) && !Classification.IsJoiner(ch)) break; } // map entry is stored in index+1, since 0 indicates uninitialized entry cachedScaledTypefaceIndexSpans.Set(ichItem + ich, cchSpan, firstIndex - 1); ich += cchSpan; } return true; } /// <summary> /// Cache index to the list of scaled shapeable typeface /// </summary> private void CacheScaledTypefaceMap( CharacterBufferRange unicodeString, CultureInfo culture, CultureInfo digitCulture, SpanVector scaledTypefaceSpans, ref SpanVector<int> cachedScaledTypefaceIndexSpans, int ichItem ) { IntMap map; if (!_intMaps.TryGetValue(culture, out map)) { map = new IntMap(); _intMaps.Add(culture, map); } DigitMap digitMap = new DigitMap(digitCulture); SpanRider typefaceSpanRider = new SpanRider(scaledTypefaceSpans); int ich = 0; while(ich < unicodeString.Length) { typefaceSpanRider.At(ich); int cch = Math.Min(unicodeString.Length - ich, typefaceSpanRider.Length); int index = IndexOfScaledTypeface((ScaledShapeTypeface)typefaceSpanRider.CurrentElement); Debug.Assert(index >= 0, "Invalid scaled shapeable typeface index spans"); cachedScaledTypefaceIndexSpans.Set(ichItem + ich, cch, index); // we keep index + 1 in the map, so that we leave map entry zero // to indicate uninitialized entry. index++; int sizeofChar; for (int c = 0; c < cch; c += sizeofChar) { int ch = digitMap[ Classification.UnicodeScalar( new CharacterBufferRange(unicodeString, ich + c, unicodeString.Length - ich - c), out sizeofChar ) ]; // only cache typeface map index for base characters if(!Classification.IsCombining(ch) && !Classification.IsJoiner(ch)) { // Dump values of local variables when the condition fails for better debuggability. // We use "if" to avoid the expensive string.Format() in normal case. if (map[ch] != 0 && map[ch] != index) { Invariant.Assert( false, string.Format( CultureInfo.InvariantCulture, "shapeable cache stores conflicting info, ch = {0}, map[ch] = {1}, index = {2}", ch, map[ch], index ) ); } map[ch] = (ushort)index; } } ich += cch; } } /// <summary> /// Search and find index to the list of scaled shapeable typefaces. /// Unfound search creates a new entry in the list. /// </summary> private int IndexOfScaledTypeface(ScaledShapeTypeface scaledTypeface) { int i; for(i = 0; i < _cachedScaledTypefaces.Count; i++) { if(scaledTypeface.Equals(_cachedScaledTypefaces[i])) break; } if(i == _cachedScaledTypefaces.Count) { // encountering this face for the first time, add it to the list i = _cachedScaledTypefaces.Count; _cachedScaledTypefaces.Add(scaledTypeface); } return i; } /// <summary> /// Map characters by font family /// </summary> /// <remarks> /// Advance: /// number of characters not mapped to missing glyph /// /// NextValid: /// Offset to the nearest first character not mapped to missing glyph /// /// [Number of invalid characters following valid ones] = NextValid - Advance /// /// A B C D E F G H x x x x x F G H I J /// ---------------> /// Advance /// /// -------------------------> /// NextValid /// /// </remarks> private int MapByFontFamily( CharacterBufferRange unicodeString, CultureInfo culture, CultureInfo digitCulture, IFontFamily fontFamily, CanonicalFontFamilyReference canonicalFamilyReference, FontStyle canonicalStyle, FontWeight canonicalWeight, FontStretch canonicalStretch, ref PhysicalFontFamily firstValidFamily, ref int firstValidLength, IDeviceFont deviceFont, double scaleInEm, int recursionDepth, SpanVector scaledTypefaceSpans, int firstCharIndex, out int nextValid ) { // This is the *one* place where we check for the font mapping depths of the font linking // process. This protects the linking process against extremely long chain of linking or // circular dependencies in the composite fonts. if (recursionDepth >= MaxTypefaceMapDepths) { // Stop the recursion. In effect, this FontFamily does not map any of the input. // Higher-level code must map the input text to some other FontFamily, or to the // "null font" if there is no valid FontFamily. nextValid = 0; return 0; } // If a device font is not already specified higher up the stack, look for a device font // for this font family that matches the typeface style, weight, and stretch. if (deviceFont == null) { deviceFont = fontFamily.GetDeviceFont(_canonicalStyle, _canonicalWeight, _canonicalStretch); } DigitMap digitMap = new DigitMap(digitCulture); int advance = 0; int cchAdvance; int cchNextValid; int ich = 0; nextValid = 0; bool terminated = false; while (ich < unicodeString.Length && !terminated) { // Determine length of run with consistent mapping. Start by assuming we'll be able to // use the whole string, then reduce to the length that can be mapped consistently. int cchMap = unicodeString.Length - ich; // Determine whether the run is using a device font, and limit the run to the // first boundary between device/non-device font usage. bool useDeviceFont = false; if (deviceFont != null) { // Determine whether the first run uses a device font by inspecting the first character. // We do not support device fonts for codepoints >= U+10000 (aka surrogates), so we // don't need to call Classification.UnicodeScalar. useDeviceFont = deviceFont.ContainsCharacter(digitMap[unicodeString[ich]]); // Advance as long as 'useDeviceFont' remains unchanged. int i = ich + 1; while ( (i < unicodeString.Length) && (useDeviceFont == deviceFont.ContainsCharacter(digitMap[unicodeString[i]]))) { i++; } cchMap = i - ich; } // Map as many characters to a family as we can up to the limit (cchMap) just determined. string targetFamilyName; double mapSizeInEm; bool isCompositeFontFamily = fontFamily.GetMapTargetFamilyNameAndScale( new CharacterBufferRange( unicodeString, ich, cchMap ), culture, digitCulture, scaleInEm, out cchMap, out targetFamilyName, out mapSizeInEm ); Debug.Assert(cchMap <= unicodeString.Length - ich); CharacterBufferRange mappedString = new CharacterBufferRange( unicodeString, ich, cchMap ); if (!isCompositeFontFamily) { // not a composite font family cchAdvance = MapByFontFaceFamily( mappedString, culture, digitCulture, fontFamily, canonicalStyle, canonicalWeight, canonicalStretch, ref firstValidFamily, ref firstValidLength, useDeviceFont ? deviceFont : null, false, // nullFont mapSizeInEm, scaledTypefaceSpans, firstCharIndex + ich, false, // ignoreMissing out cchNextValid ); } else if (!string.IsNullOrEmpty(targetFamilyName)) { // The base Uri used for resolving target family names is the Uri of the composite font. Uri baseUri = (canonicalFamilyReference != null) ? canonicalFamilyReference.LocationUri : null; // map to the target of the family map cchAdvance = MapByFontFamilyName( mappedString, culture, digitCulture, targetFamilyName, baseUri, ref firstValidFamily, ref firstValidLength, useDeviceFont ? deviceFont : null, mapSizeInEm, recursionDepth + 1, // increment the depth scaledTypefaceSpans, firstCharIndex + ich, out cchNextValid ); } else { // family map lookup returned no target family cchAdvance = 0; cchNextValid = cchMap; } int cchValid = cchMap; int cchInvalid = 0; cchValid = cchAdvance; cchInvalid = cchNextValid; if(cchValid < cchMap) { terminated = true; } advance += cchValid; nextValid = ich + cchInvalid; ich += cchValid; } return advance; } /// <summary> /// Maps characters that could not be resolved to any font family either to the first /// valid physical font family or to the default font we use for display null glyphs. /// </summary> private int MapUnresolvedCharacters( CharacterBufferRange unicodeString, CultureInfo culture, CultureInfo digitCulture, PhysicalFontFamily firstValidFamily, ref int firstValidLength, SpanVector scaledTypefaceSpans, int firstCharIndex, out int nextValid ) { // If we have a valid font family use it. We don't set nullFont to true in this case. // We may end up displaying missing glyphs, but we don't need to force it. IFontFamily fontFamily = firstValidFamily; bool nullFont = false; if (firstValidLength <= 0) { // We didn't find any valid physical font family so use the default "Arial", and // set nullFont to true to ensure that we always display missing glyphs. fontFamily = FontFamily.LookupFontFamily(FontFamily.NullFontFamilyCanonicalName); Invariant.Assert(fontFamily != null); nullFont = true; } return MapByFontFaceFamily( unicodeString, culture, digitCulture, fontFamily, _canonicalStyle, _canonicalWeight, _canonicalStretch, ref firstValidFamily, ref firstValidLength, null, // device font nullFont, 1.0, scaledTypefaceSpans, firstCharIndex, true, // ignore missing out nextValid ); } /// <summary> /// Map characters by font family name /// </summary> private int MapByFontFamilyName( CharacterBufferRange unicodeString, CultureInfo culture, CultureInfo digitCulture, string familyName, Uri baseUri, ref PhysicalFontFamily firstValidFamily, ref int firstValidLength, IDeviceFont deviceFont, double scaleInEm, int fontMappingDepth, SpanVector scaledTypefaceSpans, int firstCharIndex, out int nextValid ) { if (familyName == null) { return MapUnresolvedCharacters( unicodeString, culture, digitCulture, firstValidFamily, ref firstValidLength, scaledTypefaceSpans, firstCharIndex, out nextValid ); } else { // Map as many characters as we can to families in the list. return MapByFontFamilyList( unicodeString, culture, digitCulture, new FontFamily[] { new FontFamily(baseUri, familyName) }, ref firstValidFamily, ref firstValidLength, deviceFont, scaleInEm, fontMappingDepth, scaledTypefaceSpans, firstCharIndex, out nextValid ); } } /// <summary> /// Maps as may characters as it can (or *all* characters if recursionDepth == 0) to /// font families in the specified FontFamilyList. /// </summary> private int MapByFontFamilyList( CharacterBufferRange unicodeString, CultureInfo culture, CultureInfo digitCulture, FontFamily[] familyList, ref PhysicalFontFamily firstValidFamily, ref int firstValidLength, IDeviceFont deviceFont, double scaleInEm, int recursionDepth, SpanVector scaledTypefaceSpans, int firstCharIndex, out int nextValid ) { int advance = 0; int cchAdvance; int cchNextValid = 0; int ich = 0; nextValid = 0; while (ich < unicodeString.Length) { cchAdvance = MapOnceByFontFamilyList( new CharacterBufferRange( unicodeString, ich, unicodeString.Length - ich ), culture, digitCulture, familyList, ref firstValidFamily, ref firstValidLength, deviceFont, scaleInEm, recursionDepth, scaledTypefaceSpans, firstCharIndex + ich, out cchNextValid ); if (cchAdvance <= 0) { // We could not map any characters. If this is a recursive call then it's OK to // exit the loop without mapping all the characters; the caller may be able to // map the text to some other font family. if (recursionDepth > 0) break; Debug.Assert(cchNextValid > 0 && cchNextValid <= unicodeString.Length - ich); // The top-level call has to map all the input. cchAdvance = MapUnresolvedCharacters( new CharacterBufferRange( unicodeString, ich, cchNextValid ), culture, digitCulture, firstValidFamily, ref firstValidLength, scaledTypefaceSpans, firstCharIndex + ich, out cchNextValid ); Debug.Assert(cchNextValid == 0); } ich += cchAdvance; } advance += ich; nextValid = ich + cchNextValid; // The top-level call must map all the input; recursive calls map only what they can. Debug.Assert(recursionDepth > 0 || advance == unicodeString.Length); return advance; } /// <summary> /// Maps characters to one of the font families in the specified FontFamilyList. This /// function differs from MapByFontFamilyList in that it returns as soon as at least /// one character is mapped; it does not keep going until it cannot map any more text. /// </summary> private int MapOnceByFontFamilyList( CharacterBufferRange unicodeString, CultureInfo culture, CultureInfo digitCulture, FontFamily[] familyList, ref PhysicalFontFamily firstValidFamily, ref int firstValidLength, IDeviceFont deviceFont, double scaleInEm, int recursionDepth, SpanVector scaledTypefaceSpans, int firstCharIndex, out int nextValid ) { Invariant.Assert(familyList != null); int advance = 0; nextValid = 0; CharacterBufferRange mapString = unicodeString; FontStyle canonicalStyle = _canonicalStyle; FontWeight canonicalWeight = _canonicalWeight; FontStretch canonicalStretch = _canonicalStretch; // Note: FontFamilyIdentifier limits the number of family names in a single string. We // don't want to also limit the number of iterations here because if Typeface.FontFamily // has the maximum number of tokens, this should not prevent us from falling back to the // FallbackFontFamily (PS # 1148305). // Outer loop to loop over the list of FontFamily. for (int i = 0; i < familyList.Length; i++) { // grab the font family identifier and initialize the // target family based on whether it is a named font. FontFamilyIdentifier fontFamilyIdentifier = familyList[i].FamilyIdentifier; CanonicalFontFamilyReference canonicalFamilyReference = null; IFontFamily targetFamily; if (fontFamilyIdentifier.Count != 0) { // Look up font family and face, in the case of multiple canonical families the weight/style/stretch // may not match the typeface map's, since it is created w/ the first canonical family. canonicalFamilyReference = fontFamilyIdentifier[0]; targetFamily = FontFamily.LookupFontFamilyAndFace(canonicalFamilyReference, ref canonicalStyle, ref canonicalWeight, ref canonicalStretch); } else { targetFamily = familyList[i].FirstFontFamily; } int familyNameIndex = 0; // Inner loop to loop over all name tokens of a FontFamily. for (;;) { if (targetFamily != null) { advance = MapByFontFamily( mapString, culture, digitCulture, targetFamily, canonicalFamilyReference, canonicalStyle, canonicalWeight, canonicalStretch, ref firstValidFamily, ref firstValidLength, deviceFont, scaleInEm, recursionDepth, scaledTypefaceSpans, firstCharIndex, out nextValid ); if (nextValid < mapString.Length) { // only strings before the smallest invalid needs to be mapped since // string beyond smallest invalid can already be mapped to a higher priority font. mapString = new CharacterBufferRange( unicodeString.CharacterBuffer, unicodeString.OffsetToFirstChar, nextValid ); } if (advance > 0) { // found the family that shapes this string. We terminate both the // inner and outer loops. i = familyList.Length; break; } } else { // By definition null target does not map any of the input. nextValid = mapString.Length; } if (++familyNameIndex < fontFamilyIdentifier.Count) { // Get the next canonical family name and target family. canonicalFamilyReference = fontFamilyIdentifier[familyNameIndex]; targetFamily = FontFamily.LookupFontFamilyAndFace(canonicalFamilyReference, ref canonicalStyle, ref canonicalWeight, ref canonicalStretch); } else { // Unnamed FontFamily or no more family names in this FontFamily. break; } } } nextValid = mapString.Length; return advance; } /// <summary> /// Map characters by font face family /// </summary> private int MapByFontFaceFamily( CharacterBufferRange unicodeString, CultureInfo culture, CultureInfo digitCulture, IFontFamily fontFamily, FontStyle canonicalStyle, FontWeight canonicalWeight, FontStretch canonicalStretch, ref PhysicalFontFamily firstValidFamily, ref int firstValidLength, IDeviceFont deviceFont, bool nullFont, double scaleInEm, SpanVector scaledTypefaceSpans, int firstCharIndex, bool ignoreMissing, out int nextValid ) { Invariant.Assert(fontFamily != null); PhysicalFontFamily fontFaceFamily = fontFamily as PhysicalFontFamily; Invariant.Assert(fontFaceFamily != null); int advance = unicodeString.Length; nextValid = 0; GlyphTypeface glyphTypeface = null; if(ignoreMissing) { glyphTypeface = fontFaceFamily.GetGlyphTypeface(canonicalStyle, canonicalWeight, canonicalStretch); } else if(nullFont) { glyphTypeface = fontFaceFamily.GetGlyphTypeface(canonicalStyle, canonicalWeight, canonicalStretch); advance = 0; // by definition, null font always yields missing glyphs for whatever codepoint nextValid = unicodeString.Length; } else { glyphTypeface = fontFaceFamily.MapGlyphTypeface( canonicalStyle, canonicalWeight, canonicalStretch, unicodeString, digitCulture, ref advance, ref nextValid ); } Invariant.Assert(glyphTypeface != null); int cch = unicodeString.Length; if(!ignoreMissing && advance > 0) { cch = advance; } // Do we need to set firstValidFamily? if (firstValidLength <= 0) { // Either firstValidFamily hasn't been set, or has "expired" (see below). The first valid // family is the first existing physical font in the font linking chain. We want to remember // it so we can use it to map any unresolved characters. firstValidFamily = fontFaceFamily; // Set the "expiration date" for firstValidFamily. We know that this is the first physical // font for the specified character range, but after that family map lookup may result in // a different first physical family. firstValidLength = unicodeString.Length; } // Each time we advance we near the expiration date for firstValidFamily. firstValidLength -= advance; Debug.Assert(cch > 0); scaledTypefaceSpans.SetValue( firstCharIndex, cch, new ScaledShapeTypeface( glyphTypeface, deviceFont, scaleInEm, nullFont ) ); return advance; } #region IntMap /// <summary> /// Sparse table /// </summary> internal class IntMap { private const byte NumberOfPlanes = 17; /// <summary> /// Creates an empty IntMap. /// </summary> public IntMap() { _planes = new Plane[NumberOfPlanes]; for (int i = 0; i < NumberOfPlanes; ++i) _planes[i] = EmptyPlane; } private void CreatePlane(int i) { Invariant.Assert(i < NumberOfPlanes); if(_planes[i] == EmptyPlane) { Plane plane = new Plane(); _planes[i] = plane; } } /// <summary> /// i is Unicode character value /// get looks up glyph index corresponding to it. /// put inserts glyph index corresponding to it. /// </summary> public ushort this[int i] { get { return _planes[i>>16][i>>8 & 0xff][i & 0xff]; } set { CreatePlane(i>>16); _planes[i>>16].CreatePage(i>>8 & 0xff, this); _planes[i>>16][i>>8 & 0xff][i & 0xff] = value; } } private Plane[] _planes; private static Plane EmptyPlane = new Plane(); }; internal class Plane { public Plane() { _data = new Page[256]; for (int i = 0; i < 256; ++i) _data[i] = EmptyPage; } public Page this[int index] { get { return _data[index]; } set { _data[index] = value; } } internal void CreatePage(int i, IntMap intMap) { if(this[i] == Plane.EmptyPage) { Page page = new Page(); this[i] = page; } } private Page[] _data; private static Page EmptyPage = new Page(); }; internal class Page { public Page() { _data = new ushort[256]; } public ushort this[int index] { get { return _data[index]; } set { _data[index] = value; } } private ushort[] _data; }; #endregion } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Raw { using System; using System.IO; using DiscUtils.Partitions; /// <summary> /// Represents a single raw disk image file. /// </summary> public sealed class DiskImageFile : VirtualDiskLayer { private SparseStream _content; private Ownership _ownsContent; private Geometry _geometry; /// <summary> /// Initializes a new instance of the DiskImageFile class. /// </summary> /// <param name="stream">The stream to interpret.</param> public DiskImageFile(Stream stream) : this(stream, Ownership.None, null) { } /// <summary> /// Initializes a new instance of the DiskImageFile class. /// </summary> /// <param name="stream">The stream to interpret.</param> /// <param name="ownsStream">Indicates if the new instance should control the lifetime of the stream.</param> /// <param name="geometry">The emulated geometry of the disk.</param> public DiskImageFile(Stream stream, Ownership ownsStream, Geometry geometry) { _content = stream as SparseStream; _ownsContent = ownsStream; if (_content == null) { _content = SparseStream.FromStream(stream, ownsStream); _ownsContent = Ownership.Dispose; } _geometry = geometry ?? DetectGeometry(_content); } /// <summary> /// Gets the geometry of the file. /// </summary> public override Geometry Geometry { get { return _geometry; } } /// <summary> /// Gets a value indicating if the layer only stores meaningful sectors. /// </summary> public override bool IsSparse { get { return false; } } /// <summary> /// Gets a value indicating whether the file is a differencing disk. /// </summary> public override bool NeedsParent { get { return false; } } /// <summary> /// Gets the type of disk represented by this object. /// </summary> public VirtualDiskClass DiskType { get { return DetectDiskType(Capacity); } } internal override long Capacity { get { return _content.Length; } } internal override FileLocator RelativeFileLocator { get { return null; } } internal SparseStream Content { get { return _content; } } /// <summary> /// Initializes a stream as a raw disk image. /// </summary> /// <param name="stream">The stream to initialize.</param> /// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param> /// <param name="capacity">The desired capacity of the new disk.</param> /// <param name="geometry">The geometry of the new disk.</param> /// <returns>An object that accesses the stream as a raw disk image.</returns> public static DiskImageFile Initialize(Stream stream, Ownership ownsStream, long capacity, Geometry geometry) { stream.SetLength(Utilities.RoundUp(capacity, Sizes.Sector)); // Wipe any pre-existing master boot record / BPB stream.Position = 0; stream.Write(new byte[Sizes.Sector], 0, Sizes.Sector); stream.Position = 0; return new DiskImageFile(stream, ownsStream, geometry); } /// <summary> /// Initializes a stream as an unformatted floppy disk. /// </summary> /// <param name="stream">The stream to initialize.</param> /// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param> /// <param name="type">The type of floppy disk image to create.</param> /// <returns>An object that accesses the stream as a disk.</returns> public static DiskImageFile Initialize(Stream stream, Ownership ownsStream, FloppyDiskType type) { return Initialize(stream, ownsStream, FloppyCapacity(type), null); } /// <summary> /// Gets the content of this layer. /// </summary> /// <param name="parent">The parent stream (if any).</param> /// <param name="ownsParent">Controls ownership of the parent stream.</param> /// <returns>The content as a stream.</returns> public override SparseStream OpenContent(SparseStream parent, Ownership ownsParent) { if (ownsParent == Ownership.Dispose && parent != null) { parent.Dispose(); } return SparseStream.FromStream(Content, Ownership.None); } /// <summary> /// Gets the possible locations of the parent file (if any). /// </summary> /// <returns>Array of strings, empty if no parent.</returns> public override string[] GetParentLocations() { return new string[0]; } /// <summary> /// Disposes of underlying resources. /// </summary> /// <param name="disposing">Set to <c>true</c> if called within Dispose(), /// else <c>false</c>.</param> protected override void Dispose(bool disposing) { try { if (disposing) { if (_ownsContent == Ownership.Dispose && _content != null) { _content.Dispose(); } _content = null; } } finally { base.Dispose(disposing); } } /// <summary> /// Calculates the best guess geometry of a disk. /// </summary> /// <param name="disk">The disk to detect the geometry of.</param> /// <returns>The geometry of the disk.</returns> private static Geometry DetectGeometry(Stream disk) { long capacity = disk.Length; // First, check for floppy disk capacities - these have well-defined geometries if (capacity == Sizes.Sector * 1440) { return new Geometry(80, 2, 9); } else if (capacity == Sizes.Sector * 2880) { return new Geometry(80, 2, 18); } else if (capacity == Sizes.Sector * 5760) { return new Geometry(80, 2, 36); } // Failing that, try to detect the geometry from any partition table. // Note: this call falls back to guessing the geometry from the capacity return BiosPartitionTable.DetectGeometry(disk); } /// <summary> /// Calculates the best guess disk type (i.e. floppy or hard disk). /// </summary> /// <param name="capacity">The capacity of the disk.</param> /// <returns>The disk type.</returns> private static VirtualDiskClass DetectDiskType(long capacity) { if (capacity == Sizes.Sector * 1440 || capacity == Sizes.Sector * 2880 || capacity == Sizes.Sector * 5760) { return VirtualDiskClass.FloppyDisk; } else { return VirtualDiskClass.HardDisk; } } private static long FloppyCapacity(FloppyDiskType type) { switch (type) { case FloppyDiskType.DoubleDensity: return Sizes.Sector * 1440; case FloppyDiskType.HighDensity: return Sizes.Sector * 2880; case FloppyDiskType.Extended: return Sizes.Sector * 5760; default: throw new ArgumentException("Invalid floppy disk type", "type"); } } } }
// Copyright 2011, Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Author: [email protected] (Anash P. Oommen) using Google.Api.Ads.AdWords.Lib; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Diagnostics; using ExamplePair = System.Collections.Generic.KeyValuePair<string, object>; using System.Threading; using Google.Api.Ads.AdWords.v201309; using Google.Api.Ads.AdWords.Util.Reports; namespace Google.Api.Ads.AdWords.Examples.CSharp { /// <summary> /// The Main class for this application. /// </summary> class Program { /// <summary> /// A map to hold the code examples to be executed. /// </summary> static List<ExamplePair> codeExampleMap = new List<ExamplePair>(); /// <summary> /// A flag to keep track of whether help message was shown earlier. /// </summary> private static bool helpShown = false; private static string v201309; /// <summary> /// Registers the code example. /// </summary> /// <param name="key">The code example name.</param> /// <param name="value">The code example instance.</param> static void RegisterCodeExample(string key, object value) { codeExampleMap.Add(new ExamplePair(key, value)); } /// <summary> /// Static constructor to initialize the sample map. /// </summary> static Program() { Type[] types = Assembly.GetExecutingAssembly().GetTypes(); foreach (Type type in types) { if (type.IsSubclassOf(typeof(ExampleBase))) { RegisterCodeExample(type.FullName.Replace(typeof(Program).Namespace + ".", ""), Activator.CreateInstance(type)); } } } /// <summary> /// The main method. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { if (args.Length == 0) { AdWordsUser user = new AdWordsUser(); user.OAuthProvider.RefreshAccessTokenIfExpiring(); Selector managedSelector = new Selector(); managedSelector.fields = new string[] { "Name", "CustomerId", "CanManageClients"}; managedSelector.paging = new Paging(); managedSelector.paging.startIndex = 0; managedSelector.paging.numberResults = 100; ManagedCustomerService managedCustomerService = (ManagedCustomerService)user.GetService(AdWordsService.v201309.ManagedCustomerService); ManagedCustomerPage managedPage = new ManagedCustomerPage(); managedPage = managedCustomerService.get(managedSelector); List<Int64> CustomerIDs = new List<Int64>(); foreach (ManagedCustomer managedCustomer in managedPage.entries) { CustomerIDs.Add(managedCustomer.customerId); } AdWordsUser Customer = new AdWordsUser(); foreach (Int64 CustomerID in CustomerIDs) { } CampaignService campaignService = (CampaignService)user.GetService(AdWordsService.v201309.CampaignService); Selector selector = new Selector(); selector.fields = new string[] { "Id", "Name" }; // Set the selector paging. selector.paging = new Paging(); int offset = 0; int pageSize = 500; CampaignPage page = new CampaignPage(); try { do { selector.paging.startIndex = offset; selector.paging.numberResults = pageSize; // Get the campaigns. page = campaignService.get(selector); // Display the results. if (page != null && page.entries != null) { int i = offset; foreach (Campaign campaign in page.entries) { Console.WriteLine("{0}) Campaign with id = '{1}', name = '{2}' " + " was found.", i + 1, campaign.id, campaign.name); i++; } } offset += pageSize; } while (offset < page.totalNumEntries); Console.WriteLine("Number of campaigns found: {0}", page.totalNumEntries); } catch (Exception ex) { throw new System.ApplicationException("Failed to retrieve campaigns", ex); } ReportDefinition definition = new ReportDefinition(); definition.reportName = "Adgroup Report"; definition.reportType = ReportDefinitionReportType.KEYWORDS_PERFORMANCE_REPORT; definition.downloadFormat = DownloadFormat.CSV; definition.dateRangeType = ReportDefinitionDateRangeType.ALL_TIME; Selector selector1 = new Selector(); selector1.fields = new string[] { "Clicks", }; definition.selector = selector1; //if (!Directory.Exists(ReportFolder)) // Directory.CreateDirectory(ReportFolder); ReportUtilities utilities = new ReportUtilities(user) { ReportVersion = "v201309" }; Console.WriteLine(utilities.ReportVersion); ClientReport report = utilities.DownloadClientReport(definition, "C:\\Bjork\\" + definition.reportName + ".xls"); foreach (string cmdArgs in args) { ExamplePair matchingPair = codeExampleMap.Find(delegate(ExamplePair pair) { return string.Compare(pair.Key, cmdArgs, true) == 0; }); if (matchingPair.Key != null) { RunACodeExample(user, matchingPair.Value); } else { ShowUsage(); } } ShowUsage(); return; } } /// <summary> /// Runs a code example. /// </summary> /// <param name="user">The user whose credentials should be used for /// running the code example.</param> /// <param name="codeExample">The code example to run.</param> private static void RunACodeExample(AdWordsUser user, object codeExample) { try { Console.WriteLine(GetDescription(codeExample)); InvokeRun(codeExample, user); } catch (Exception ex) { Console.WriteLine("An exception occurred while running this code example. {0}", ExampleUtilities.FormatException(ex)); } finally { Console.WriteLine("Press [Enter] to continue"); Console.ReadLine(); } } /// <summary> /// Gets the description for the code example. /// </summary> /// <param name="codeExample">The code example.</param> /// <returns>The description.</returns> private static object GetDescription(object codeExample) { Type exampleType = codeExample.GetType(); return exampleType.GetProperty("Description").GetValue(codeExample, null); } /// <summary> /// Gets the parameters for running a code example. /// </summary> /// <param name="user">The user.</param> /// <param name="codeExample">The code example.</param> /// <returns>The list of parameters.</returns> private static object[] GetParameters(AdWordsUser user, object codeExample) { MethodInfo methodInfo = codeExample.GetType().GetMethod("Run"); List<object> parameters = new List<object>(); parameters.Add(user); parameters.AddRange(ExampleUtilities.GetParameters(methodInfo)); return parameters.ToArray(); } /// <summary> /// Invokes the run method. /// </summary> /// <param name="codeExample">The code example.</param> /// <param name="user">The user.</param> private static void InvokeRun(object codeExample, AdWordsUser user) { MethodInfo methodInfo = codeExample.GetType().GetMethod("Run"); methodInfo.Invoke(codeExample, GetParameters(user, codeExample)); } /// <summary> /// Prints program usage message. /// </summary> private static void ShowUsage() { if (helpShown) { return; } else { helpShown = true; } string exeName = Path.GetFileName(Assembly.GetExecutingAssembly().Location); Console.WriteLine("Runs AdWords API code examples"); /* Console.WriteLine("Usage : {0} [flags]\n", exeName); Console.WriteLine("Available flags\n"); Console.WriteLine("--help\t\t : Prints this help message.", exeName); Console.WriteLine("--all\t\t : Run all code examples.", exeName); Console.WriteLine("examplename1 [examplename1 ...] : " + "Run specific code examples. Example name can be one of the following:\n", exeName); foreach (ExamplePair pair in codeExampleMap) { Console.WriteLine("{0} : {1}", pair.Key, GetDescription(pair.Value)); } */ Console.WriteLine("Press [Enter] to continue"); Console.ReadLine(); } } }
namespace Microsoft.Protocols.TestSuites.MS_OXCPERM { using System; using System.Collections.Generic; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; /// <summary> /// Adapter capture code for MS_OXCPERMAdapter /// </summary> public partial class MS_OXCPERMAdapter : ManagedAdapterBase { /// <summary> /// Verify MAPIHTTP transport. /// </summary> private void VerifyMAPITransport() { if (Common.GetConfigurationPropertyValue("TransportSeq", this.Site).ToLower() == "mapi_http" && Common.IsRequirementEnabled(1184, this.Site)) { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCPERM_R1184"); // Verify requirement MS-OXCPERM_R1184 // If the transport sequence is MAPIHTTP and the code can reach here, it means that the implementation does support MAPIHTTP transport. Site.CaptureRequirement( 1184, @"[In Appendix A: Product Behavior] Implementation does support this specification [MS-OXCMAPIHTTP]. (Exchange Server 2013 Service Pack 1 (SP1) follows this behavior.)"); } } #region Message Syntax /// <summary> /// Verify the message syntax. /// </summary> private void VerifyMessageSyntax() { // The parser has ensured the field satisfied the format, otherwise can't get the response. Site.CaptureRequirement( 3, @"[In Transport] The ROP request buffers and ROP response buffers specified in this protocol [Exchange Access and Operation Permissions Protocol] are sent to and received from the server respectively by using the underlying protocol specified by [MS-OXCROPS] section 2.1."); // The parser has ensured the field satisfied the format, otherwise can't get the response. Site.CaptureRequirement( 6, @"[In Message Syntax] Unless otherwise noted, the fields specified in this section, which are larger than a single byte, MUST be converted to little-endian order when packed in buffers."); // The parser has ensured the field satisfied the format, otherwise can't get the response. Site.CaptureRequirement( 7, @"[In Message Syntax] Unless otherwise noted, the fields specified in this section, which are larger than a single byte, MUST be converted from little-endian order when unpacked."); } #endregion #region Verify Properties /// <summary> /// Verify properties' value /// </summary> /// <param name="succeedToParse">Specify whether the data can parse successfully or not. True indicate success, else false</param> /// <param name="permissionUserList">The permission list of all users</param> private void VerifyProperties(bool succeedToParse, List<PermissionUserInfo> permissionUserList) { Site.Assert.IsTrue(succeedToParse, "True indicates the permissions list is parsed successfully."); if (permissionUserList == null || permissionUserList.Count == 0) { Site.Log.Add(LogEntryKind.Comment, "The permissions list is empty. The data related to the permission can't be verified here."); return; } // Verify MS-OXCPERM requirement: MS-OXCPERM_R1068 // If the returned data can be parsed successfully, the format is following the defined structure. bool isVerifyR1068 = succeedToParse; Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCPERM_R1068: The data is{0} same as defined.", isVerifyR1068 ? string.Empty : " not"); Site.CaptureRequirementIfIsTrue( isVerifyR1068, 1068, @"[In PidTagEntryId Property] The first two bytes of this property specify the number of bytes that follow."); // Verify MS-OXCPERM requirement: MS-OXCPERM_R1069 bool isVerifyR1069 = succeedToParse; Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCPERM_R1069: The data is{0} same as defined.", isVerifyR1069 ? string.Empty : " not"); Site.CaptureRequirementIfIsTrue( isVerifyR1069, 1069, @"[In PidTagEntryId Property] [The first two bytes of this property specify the number of bytes that follow.] The remaining bytes constitute the PermanentEntryID structure ([MS-OXNSPI] section 2.3.9.3)."); bool memberIdIsUnique = true; for (int i = 0; i < permissionUserList.Count; i++) { PermissionUserInfo permissionInfo = permissionUserList[i]; string memberName = permissionInfo.PidTagMemberName; if (memberName == this.defaultUser || memberName == this.anonymousUser) { // Verify MS-OXCPERM requirement: MS-OXCPERM_R1070 Site.CaptureRequirementIfAreEqual<int>( 0, permissionInfo.PidTagEntryId.Length, 1070, @"[In PidTagEntryId Property] If the PidTagMemberId property (section 2.2.5) is set to one of the two reserved values, the first two bytes of this property MUST be 0x0000, indicating that zero bytes follow (that is, no PermanentEntryID structure follows the first two bytes)."); } if (permissionInfo.PidTagMemberId == 0xFFFFFFFFFFFFFFFF) { // Verify MS-OXCPERM requirement: MS-OXCPERM_R1079 // That PidTagMemberId is 0xFFFFFFFFFFFFFFFF and the name is "Anonymous" must be matched. bool isVerifyR1079 = permissionInfo.PidTagMemberId == 0xFFFFFFFFFFFFFFFF && permissionInfo.PidTagMemberName == this.anonymousUser; Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCPERM_R1079: the PidTagMemberId:{0:X} and PidTagMemberName:{1} are{2} matched.", permissionInfo.PidTagMemberId, permissionInfo.PidTagMemberName, isVerifyR1079 ? string.Empty : " not"); Site.CaptureRequirementIfIsTrue( isVerifyR1079, 1079, @"[In PidTagMemberName Property] Anonymous user: Value of the PidTagMemberId is 0xFFFFFFFFFFFFFFFF and the name is ""Anonymous""."); } if (permissionInfo.PidTagMemberId == 0x0000000000000000) { // Verify MS-OXCPERM requirement: MS-OXCPERM_R1080 // That PidTagMemberId is 0x0000000000000000 and name is "" (empty string) must be matched. bool isVerifyR1080 = permissionInfo.PidTagMemberId == 0x0000000000000000 && permissionInfo.PidTagMemberName == this.defaultUser; Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCPERM_R1080: the PidTagMemberId:{0:X} and PidTagMemberName:{1} are{2} matched.", permissionInfo.PidTagMemberId, permissionInfo.PidTagMemberName, isVerifyR1080 ? string.Empty : " not"); Site.CaptureRequirementIfIsTrue( isVerifyR1080, 1080, @"[In PidTagMemberName Property] Default user: Value of the PidTagMemberId is 0x0000000000000000 and name is """" (empty string)."); } for (int j = i + 1; j < permissionUserList.Count; j++) { if (permissionInfo.PidTagMemberId == permissionUserList[j].PidTagMemberId) { memberIdIsUnique = false; } } } // Verify MS-OXCPERM requirement: MS-OXCPERM_R74 bool isVerifyR74 = memberIdIsUnique; Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCPERM_R74: the all PidTagMemberId are{0} unique.", isVerifyR74 ? string.Empty : " not"); Site.CaptureRequirementIfIsTrue( isVerifyR74, 74, @"[In PidTagMemberId Property] The PidTagMemberId property ([MS-OXPROPS] section 2.782) specifies the unique identifier that the server generates for each user."); // The PidTagMemberName is parsed as string, this requirement can be captured directly. Site.CaptureRequirement( 1081, @"[In PidTagMemberName Property] The server provides the user-readable name for all entries in the permissions list."); // The parser has ensured the field satisfies the format, otherwise can't get the response. Site.CaptureRequirement( 154, @"[In Retrieving Folder Permissions] If all three of the ROP requests [RopGetPermissionsTable, RopSetColumns, RopQueryRows] succeed, the permissions list is returned in the RowData field of the RopQueryRows ROP response buffer."); // The parser has ensured the field satisfies the format, otherwise can't get the response. Site.CaptureRequirement( 155, @"[In Retrieving Folder Permissions] The RowData field contains one PropertyRow structure ([MS-OXCDATA] section 2.8.1) for each entry in the permissions list."); // The parser has ensured the field satisfies the format, otherwise can't get the response. Site.CaptureRequirement( 1164, @"[In Processing a RopGetPermissionsTable ROP Request] The server responds with a RopGetPermissionsTable ROP response buffer."); // The parser has ensured the field satisfies the format, otherwise can't get the response. Site.CaptureRequirement( 179, @"[In Processing a RopGetPermissionsTable ROP Request] If the user does have permission to view the folder, the server MUST return a Server object handle to a Table object, which can be used to retrieve the permissions list of the folder, as specified in section 3.1.4.1."); if (this.CheckUserPermissionContained(this.anonymousUser, permissionUserList)) { // Verify MS-OXCPERM requirement: MS-OXCPERM_R189 ulong anonymousMemberID = this.GetMemberIdByName(this.anonymousUser, permissionUserList); Site.CaptureRequirementIfAreEqual<ulong>( 0xFFFFFFFFFFFFFFFF, anonymousMemberID, 189, @"[In PidTagMemberId Property] 0xFFFFFFFFFFFFFFFF: Identifier for the anonymous user entry in the permissions list."); } if (this.CheckUserPermissionContained(this.defaultUser, permissionUserList)) { // Verify MS-OXCPERM requirement: MS-OXCPERM_R190 ulong defaultUserMemberID = this.GetMemberIdByName(this.defaultUser, permissionUserList); Site.CaptureRequirementIfAreEqual<ulong>( 0x0000000000000000, defaultUserMemberID, 190, @"[In PidTagMemberId Property] 0x0000000000000000: Identifier for the default user entry in the permissions list."); } } #endregion #region Verify the return value. /// <summary> /// Verify the return value when calling RopGetPermissionsTable is successful. /// </summary> /// <param name="returnValue">The return value from the server</param> private void VerifyReturnValueSuccessForGetPermission(uint returnValue) { // Verify MS-OXCPERM requirement: MS-OXCPERM_R28 Site.CaptureRequirementIfAreEqual<uint>( UINT32SUCCESS, returnValue, 28, @"[In RopGetPermissionsTable ROP Response Buffer] ReturnValue (4 bytes): The value 0x00000000 indicates success."); } /// <summary> /// Verify the return value is 4 bytes. /// </summary> private void VerifyReturnValueForGetPermission() { // The return value is parsed as 4 bytes. Site.CaptureRequirement( 27, @"[In RopGetPermissionsTable ROP Response Buffer] ReturnValue (4 bytes): An integer that indicates the result of the operation."); } /// <summary> /// Verify the return value when calling RopModifyPermissions is successful. /// </summary> /// <param name="returnValue">The return value from the server</param> private void VerifyReturnValueSuccessForModifyPermission(uint returnValue) { // Verify MS-OXCPERM requirement: MS-OXCPERM_R66 Site.CaptureRequirementIfAreEqual<uint>( UINT32SUCCESS, returnValue, 66, @"[In RopModifyPermissions ROP Response Buffer] ReturnValue (4 bytes): The value 0x00000000 indicates success."); } /// <summary> /// Verify the return value is 4 bytes. /// </summary> private void VerifyReturnValueForModifyPermission() { // The return value is parsed as 4 bytes. Site.CaptureRequirement( 65, @"[In RopModifyPermissions ROP Response Buffer] ReturnValue (4 bytes): An integer that indicates the result of the operation."); } #endregion #region Capture requirements related to the data structure of MS-OXCPERM /// <summary> /// Capture Requirements related to the data structures for the MS-OXCPERM /// </summary> /// <param name="succeedToParse">Specify whether the data can be parsed successfully or not. True indicates success, else false.</param> /// <param name="permissionUserList">The PermissionList of all users</param> private void VerifyPropertiesOfDataStructure(bool succeedToParse, List<PermissionUserInfo> permissionUserList) { Site.Assert.IsTrue(succeedToParse, "Succeed to parse the permissions list."); const string OXCDATA = "MS-OXCDATA"; const string OXPROPS = "MS-OXPROPS"; // The parser has ensured the field satisfied the format, otherwise can't get the response. Site.CaptureRequirement( OXCDATA, 65, @"[In PropertyRow Structures] For the RopFindRow, RopGetReceiveFolderTable, and RopQueryRows ROPs, property values are returned in the order of the properties in the table, set by a prior call to a RopSetColumns ROP request ([MS-OXCROPS] section 2.2.5.1)."); // The parser has ensured the field satisfied the format, otherwise can't get the response. Site.CaptureRequirement( OXCDATA, 72, @"[In StandardPropertyRow Structure] Flag (1 byte): An unsigned integer."); // The parser has ensured the field satisfied the format, otherwise can't get the response. Site.CaptureRequirement( OXCDATA, 73, @"[In StandardPropertyRow Structure] Flag (1 byte): This value MUST be set to 0x00 to indicate that all property values are present and without error."); // The parser has ensured the field satisfied the format, otherwise can't get the response. Site.CaptureRequirement( OXPROPS, 6100, @"[In PidTagEntryId] Property ID: 0x0FFF."); // The parser has ensured the field satisfied the format, otherwise can't get the response. Site.CaptureRequirement( OXPROPS, 6101, @"[In PidTagEntryId] Data type: PtypBinary, 0x0102."); // The parser has ensured the field satisfied the format, otherwise can't get the response. Site.CaptureRequirement( OXCDATA, 2707, @"[In Property Data Types] PtypBinary (PT_BINARY) is that variable size; a COUNT field followed by that many bytes with Property Type Value 0x0102,%x02.01."); // The parser has ensured the field satisfied the format, otherwise can't get the response. Site.CaptureRequirement( 1066, @"[In PidTagEntryId Property] Type: PtypBinary ([MS-OXCDATA] section 2.11.1)"); // The parser has ensured the field satisfied the format, otherwise can't get the response. Site.CaptureRequirement( OXCDATA, 454, @"[In PropertyValue Structure] PropertyValue (variable): For multivalue types, the first element in the ROP buffer is a 16-bit integer specifying the number of entries."); // The parser has ensured the field satisfied the format, otherwise can't get the response. Site.CaptureRequirement( OXPROPS, 6904, @"[In PidTagMemberId] Property ID: 0x6671."); // PtypInteger64 is 8 bytes, so if the length of memberRight is 8 bytes, the data type of PidTagMemberRights is PtypInteger64. List<byte[]> memberIDs = this.GetMemberIDs(permissionUserList); foreach (byte[] memberID in memberIDs) { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXPROPS_R6905"); // Verify MS-OXPROPS requirement: MS-OXPROPS_R6905 Site.CaptureRequirementIfAreEqual<int>( 8, memberID.Length, OXPROPS, 6905, @"[In PidTagMemberId] Data type: PtypInteger64, 0x0014."); // Verify MS-OXCPERM requirement: MS-OXCPERM_R1071 Site.CaptureRequirementIfAreEqual<int>( 8, memberID.Length, 1071, @"[In PidTagMemberId Property] Type: PtypInteger64 ([MS-OXCDATA] section 2.11.1)"); } // The parser has ensured the field satisfied the format, otherwise can't get the response. Site.CaptureRequirement(OXPROPS, 6911, @"[In PidTagMemberName] Property ID: 0x6672."); // The parser has ensured the field satisfied the format, otherwise can't get the response. Site.CaptureRequirement(OXPROPS, 6912, @"[In PidTagMemberName] Data type: PtypString, 0x001F."); // The parser has ensured the field satisfied the format, otherwise can't get the response. Site.CaptureRequirement( OXCDATA, 2700, @"[In Property Data Types] PtypString (PT_UNICODE, string) is that Variable size; a string of Unicode characters in UTF-16LE format encoding with terminating null character (0x0000). with Property Type Value 0x001F,%x1F.00."); // The parser has ensured the field satisfied the format, otherwise can't get the response. Site.CaptureRequirement( 1076, @"[In PidTagMemberName Property] Type: PtypString ([MS-OXCDATA] section 2.11.1)"); // The parser has ensured the field satisfied the format, otherwise can't get the response. Site.CaptureRequirement( OXCDATA, 455, @"[In PropertyValue Structure] PropertyValue (variable): If the property value being passed is a string, the data includes the terminating null characters."); // The parser has ensured the field satisfied the format, otherwise can't get the response. Site.CaptureRequirement( OXPROPS, 6918, @"[In PidTagMemberRights] Property ID: 0x6673."); // PtypInteger32 is 4 bytes, so if the length of memberRight is 4 bytes, the data type of PidTagMemberRights is PtypInteger32. List<byte[]> memberRights = this.GetMemberRights(permissionUserList); foreach (byte[] memberRight in memberRights) { // Verify MS-OXPROPS requirement: MS-OXPROPS_R6919 Site.CaptureRequirementIfAreEqual<int>( 4, memberRight.Length, OXPROPS, 6919, @"[In PidTagMemberRights] Data type: PtypInteger32, 0x0003."); // Verify MS-OXPROPS requirement: MS-OXCDATA_R2691 Site.CaptureRequirementIfAreEqual<int>( 4, memberRight.Length, OXCDATA, 2691, @"[In Property Data Types] PtypInteger32 (PT_LONG, PT_I4, int, ui4) is that 4 bytes; a 32-bit integer [MS-DTYP]: INT32 with Property Type Value 0x0003,%x03.00."); // Verify MS-OXCPERM requirement: MS-OXCPERM_R1082 Site.CaptureRequirementIfAreEqual<int>( 4, memberRight.Length, 1082, @"[In PidTagMemberRights Property] Type: PtypInteger32 ([MS-OXCDATA] section 2.11.1)"); } } #endregion /// <summary> /// Verify the server object handle to a Table object /// </summary> /// <param name="responseValue">The return value from the server</param> private void VerifyGetPermissionHandle(uint responseValue) { // Add the debug information this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCPERM_R2006"); // Verify MS-OXCPERM requirement: MS-OXCPERM_R2006 this.Site.CaptureRequirementIfAreEqual<uint>( UINT32SUCCESS, responseValue, 2006, @"[In Processing a RopGetPermissionsTable ROP Request] The server MUST return a Server object handle to a Table object, which the client uses to retrieve the permissions list of the folder, as specified in section 3.1.4.1."); // That the server return Success indicates the server object handle to the Table object is returned successfully. Site.CaptureRequirementIfAreEqual<uint>( UINT32SUCCESS, responseValue, 9, "[In RopGetPermissionsTable ROP] The RopGetPermissionsTable ROP ([MS-OXCROPS] section 2.2.10.2) retrieves a Server object handle to a Table object, which is then used in other ROP requests to retrieve the current permissions list on a folder."); } /// <summary> /// Verify the RopModifyPermissions ROP response buffer /// </summary> private void VerifyModifyPermissionsResponse() { // If the RopModifyPermissions ROP response buffer can be parsed successfully, it indicates the server responds with a RopModifyPermissions ROP response buffer. Site.CaptureRequirement( 1170, @"[In Processing a RopModifyPermissions ROP Request] The server responds with a RopModifyPermissions ROP response buffer."); } #region Verify the right flags specified by PidTagMemberRights property /// <summary> /// Verify the Create flag value /// </summary> private void VerifyCreateFlagValue() { // The parser parse the Create flag in the PidTagMemberRights through the flag definition. Site.CaptureRequirement( 139, @"[In PidTagMemberRights Property] Create: Its value is 0x00000002."); } /// <summary> /// Verify the CreateSubFolder flag value /// </summary> private void VerifyCreateSubFolderFlagValue() { // The parser parse the CreateSubFolder flag in the PidTagMemberRights through the flag definition. Site.CaptureRequirement( 117, @"[In PidTagMemberRights Property] CreateSubFolder: Its value is 0x00000080."); } /// <summary> /// Verify the DeleteAny flag value /// </summary> private void VerifyDeleteAnyFlagValue() { // The parser parse the DeleteAny flag in the PidTagMemberRights through the flag definition. Site.CaptureRequirement( 120, @"[In PidTagMemberRights Property] DeleteAny: Its value is 0x00000040."); } /// <summary> /// Verify the DeleteOwned flag value /// </summary> private void VerifyDeleteOwnedFlagValue() { // The parser parse the DeleteOwned flag in the PidTagMemberRights through the flag definition. Site.CaptureRequirement( 126, @"[In PidTagMemberRights Property] DeleteOwned: Its value is 0x00000010."); } /// <summary> /// Verify the EditAny flag value /// </summary> private void VerifyEditAnyFlagValue() { // The parser parse the EditAny flag in the PidTagMemberRights through the flag definition. Site.CaptureRequirement( 123, @"[In PidTagMemberRights Property] EditAny: Its value is 0x00000020."); } /// <summary> /// Verify the EditOwned flag value /// </summary> private void VerifyEditOwnedFlagValue() { // The parser parse the EditOwned flag in the PidTagMemberRights through the flag definition. Site.CaptureRequirement( 130, @"[In PidTagMemberRights Property] EditOwned: Its value is 0x00000008."); } /// <summary> /// Verify the FolderOwner flag value /// </summary> private void VerifyFolderOwnerFlagValue() { // The parser parse the FolderOwner flag in the PidTagMemberRights through the flag definition. Site.CaptureRequirement( 114, @"[In PidTagMemberRights Property] FolderOwner: Its value is 0x00000100."); } /// <summary> /// Verify the FolderVisible flag value /// </summary> private void VerifyFolderVisibleFlagValue() { // The parser parse the FolderVisible flag in the PidTagMemberRights through the flag definition. Site.CaptureRequirement( 102, @"[In PidTagMemberRights Property] FolderVisible: Its value is 0x00000400."); } /// <summary> /// Verify the FreeBusyDetailed flag value /// </summary> private void VerifyFreeBusyDetailedFlagValue() { // The parser parse the FreeBusyDetailed flag in the PidTagMemberRights through the flag definition. Site.CaptureRequirement( 96, @"[In PidTagMemberRights Property] FreeBusySimple: Its value is 0x00000800."); } /// <summary> /// Verify the FreeBusySimple flag value /// </summary> private void VerifyFreeBusySimpleFlagValue() { // The parser parse the FreeBusySimple flag in the PidTagMemberRights through the flag definition. Site.CaptureRequirement( 90, @"[In PidTagMemberRights Property] FreeBusyDetailed: Its value is 0x00001000."); } /// <summary> /// Verify the ReadAny flag value /// </summary> private void VerifyReadAnyFlagValue() { // The parser parse the ReadAny flag in the PidTagMemberRights through the flag definition. Site.CaptureRequirement( 142, @"[In PidTagMemberRights Property] ReadAny: Its value is 0x00000001."); } #endregion /// <summary> /// Check the permissions list contains the user's permissions. /// </summary> /// <param name="user">The user name</param> /// <param name="permissionsList">User permission list</param> /// <returns>True, if the permissions list contains the user's permissions, else false.</returns> private bool CheckUserPermissionContained(string user, List<PermissionUserInfo> permissionsList) { if (permissionsList.Count > 0) { foreach (PermissionUserInfo pui in permissionsList) { if (string.Equals(pui.PidTagMemberName, user, StringComparison.OrdinalIgnoreCase)) { return true; } } } return false; } /// <summary> /// Verify the credential is provided to log on the server. /// </summary> /// <param name="user">The name of the user.</param> /// <param name="password">The password of the user.</param> /// <param name="logonReturnValue">The return value of the RopLogon.</param> private void VerifyCredential(string user, string password, uint logonReturnValue) { bool userIsEmpty = string.IsNullOrEmpty(user); bool passwordIsEmpty = string.IsNullOrEmpty(password); Site.Assert.IsFalse(userIsEmpty, "False indicates the user name is not null or empty. The user name:{0}", user); Site.Assert.IsFalse(passwordIsEmpty, "False indicates the password is not null or empty. The password:{0}", password); // Add the debug information this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCPERM_R2005"); // Verify MS-OXCPERM requirement: MS-OXCPERM_R2005 this.Site.CaptureRequirementIfAreEqual<uint>( UINT32SUCCESS, logonReturnValue, 2005, @"[In Accessing a Folder] Anonymous user permissions: the server requires that the client provide user credentials."); } } }
/* * 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.IO; using System.Threading; using System.Collections; using System.Collections.Generic; using System.Security; using System.Security.Policy; using System.Reflection; using System.Globalization; using System.Xml; using OpenMetaverse; using OpenMetaverse.StructuredData; using log4net; using Nini.Config; using Amib.Threading; using OpenSim.Framework; using OpenSim.Region.CoreModules.Framework.EventQueue; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.ScriptEngine.Shared; using OpenSim.Region.ScriptEngine.Shared.ScriptBase; using OpenSim.Region.ScriptEngine.Shared.CodeTools; using OpenSim.Region.ScriptEngine.Shared.Instance; using OpenSim.Region.ScriptEngine.Interfaces; namespace OpenSim.Region.ScriptEngine.XEngine { public class XEngine : INonSharedRegionModule, IScriptModule, IScriptEngine { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private SmartThreadPool m_ThreadPool; private int m_MaxScriptQueue; private Scene m_Scene; private IConfig m_ScriptConfig = null; private IConfigSource m_ConfigSource = null; private ICompiler m_Compiler; private int m_MinThreads; private int m_MaxThreads ; private int m_IdleTimeout; private int m_StackSize; private int m_SleepTime; private int m_SaveTime; private ThreadPriority m_Prio; private bool m_Enabled = false; private bool m_InitialStartup = true; private int m_ScriptFailCount; // Number of script fails since compile queue was last empty private string m_ScriptErrorMessage; // disable warning: need to keep a reference to XEngine.EventManager // alive to avoid it being garbage collected #pragma warning disable 414 private EventManager m_EventManager; #pragma warning restore 414 private IXmlRpcRouter m_XmlRpcRouter; private int m_EventLimit; private bool m_KillTimedOutScripts; private static List<XEngine> m_ScriptEngines = new List<XEngine>(); // Maps the local id to the script inventory items in it private Dictionary<uint, List<UUID> > m_PrimObjects = new Dictionary<uint, List<UUID> >(); // Maps the UUID above to the script instance private Dictionary<UUID, IScriptInstance> m_Scripts = new Dictionary<UUID, IScriptInstance>(); // Maps the asset ID to the assembly private Dictionary<UUID, string> m_Assemblies = new Dictionary<UUID, string>(); private Dictionary<string, int> m_AddingAssemblies = new Dictionary<string, int>(); // This will list AppDomains by script asset private Dictionary<UUID, AppDomain> m_AppDomains = new Dictionary<UUID, AppDomain>(); // List the scripts running in each appdomain private Dictionary<UUID, List<UUID> > m_DomainScripts = new Dictionary<UUID, List<UUID> >(); private Queue m_CompileQueue = new Queue(100); IWorkItemResult m_CurrentCompile = null; public string ScriptEngineName { get { return "XEngine"; } } public Scene World { get { return m_Scene; } } public static List<XEngine> ScriptEngines { get { return m_ScriptEngines; } } public IScriptModule ScriptModule { get { return this; } } // private struct RezScriptParms // { // uint LocalID; // UUID ItemID; // string Script; // } public IConfig Config { get { return m_ScriptConfig; } } public IConfigSource ConfigSource { get { return m_ConfigSource; } } public event ScriptRemoved OnScriptRemoved; public event ObjectRemoved OnObjectRemoved; // // IRegionModule functions // public void Initialise(IConfigSource configSource) { if (configSource.Configs["XEngine"] == null) return; m_ScriptConfig = configSource.Configs["XEngine"]; m_ConfigSource = configSource; } public void AddRegion(Scene scene) { if (m_ScriptConfig == null) return; m_ScriptFailCount = 0; m_ScriptErrorMessage = String.Empty; if (m_ScriptConfig == null) { // m_log.ErrorFormat("[XEngine] No script configuration found. Scripts disabled"); return; } m_Enabled = m_ScriptConfig.GetBoolean("Enabled", true); if (!m_Enabled) return; AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve; m_log.InfoFormat("[XEngine] Initializing scripts in region {0}", scene.RegionInfo.RegionName); m_Scene = scene; m_MinThreads = m_ScriptConfig.GetInt("MinThreads", 2); m_MaxThreads = m_ScriptConfig.GetInt("MaxThreads", 100); m_IdleTimeout = m_ScriptConfig.GetInt("IdleTimeout", 60); string priority = m_ScriptConfig.GetString("Priority", "BelowNormal"); m_MaxScriptQueue = m_ScriptConfig.GetInt("MaxScriptEventQueue",300); m_StackSize = m_ScriptConfig.GetInt("ThreadStackSize", 262144); m_SleepTime = m_ScriptConfig.GetInt("MaintenanceInterval", 10) * 1000; m_EventLimit = m_ScriptConfig.GetInt("EventLimit", 30); m_KillTimedOutScripts = m_ScriptConfig.GetBoolean("KillTimedOutScripts", false); m_SaveTime = m_ScriptConfig.GetInt("SaveInterval", 120) * 1000; m_Prio = ThreadPriority.BelowNormal; switch (priority) { case "Lowest": m_Prio = ThreadPriority.Lowest; break; case "BelowNormal": m_Prio = ThreadPriority.BelowNormal; break; case "Normal": m_Prio = ThreadPriority.Normal; break; case "AboveNormal": m_Prio = ThreadPriority.AboveNormal; break; case "Highest": m_Prio = ThreadPriority.Highest; break; default: m_log.ErrorFormat("[XEngine] Invalid thread priority: '{0}'. Assuming BelowNormal", priority); break; } lock (m_ScriptEngines) { m_ScriptEngines.Add(this); } // Needs to be here so we can queue the scripts that need starting // m_Scene.EventManager.OnRezScript += OnRezScript; // Complete basic setup of the thread pool // SetupEngine(m_MinThreads, m_MaxThreads, m_IdleTimeout, m_Prio, m_MaxScriptQueue, m_StackSize); m_Scene.StackModuleInterface<IScriptModule>(this); m_XmlRpcRouter = m_Scene.RequestModuleInterface<IXmlRpcRouter>(); if (m_XmlRpcRouter != null) { OnScriptRemoved += m_XmlRpcRouter.ScriptRemoved; OnObjectRemoved += m_XmlRpcRouter.ObjectRemoved; } } public void RemoveRegion(Scene scene) { lock (m_Scripts) { foreach (IScriptInstance instance in m_Scripts.Values) { // Force a final state save // if (m_Assemblies.ContainsKey(instance.AssetID)) { string assembly = m_Assemblies[instance.AssetID]; instance.SaveState(assembly); } // Clear the event queue and abort the instance thread // instance.ClearQueue(); instance.Stop(0); // Release events, timer, etc // instance.DestroyScriptInstance(); // Unload scripts and app domains // Must be done explicitly because they have infinite // lifetime // m_DomainScripts[instance.AppDomain].Remove(instance.ItemID); if (m_DomainScripts[instance.AppDomain].Count == 0) { m_DomainScripts.Remove(instance.AppDomain); UnloadAppDomain(instance.AppDomain); } } m_Scripts.Clear(); m_PrimObjects.Clear(); m_Assemblies.Clear(); m_DomainScripts.Clear(); } lock (m_ScriptEngines) { m_ScriptEngines.Remove(this); } } public void RegionLoaded(Scene scene) { if (!m_Enabled) return; m_EventManager = new EventManager(this); m_Compiler = new Compiler(this); m_Scene.EventManager.OnRemoveScript += OnRemoveScript; m_Scene.EventManager.OnScriptReset += OnScriptReset; m_Scene.EventManager.OnStartScript += OnStartScript; m_Scene.EventManager.OnStopScript += OnStopScript; m_Scene.EventManager.OnGetScriptRunning += OnGetScriptRunning; m_Scene.EventManager.OnShutdown += OnShutdown; if (m_SleepTime > 0) { m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance), new Object[]{ m_SleepTime }); } if (m_SaveTime > 0) { m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup), new Object[] { m_SaveTime }); } m_ThreadPool.Start(); } public void Close() { lock (m_ScriptEngines) { if (m_ScriptEngines.Contains(this)) m_ScriptEngines.Remove(this); } } public object DoBackup(object o) { Object[] p = (Object[])o; int saveTime = (int)p[0]; if (saveTime > 0) System.Threading.Thread.Sleep(saveTime); // m_log.Debug("[XEngine] Backing up script states"); List<IScriptInstance> instances = new List<IScriptInstance>(); lock (m_Scripts) { foreach (IScriptInstance instance in m_Scripts.Values) instances.Add(instance); } foreach (IScriptInstance i in instances) { string assembly = String.Empty; lock (m_Scripts) { if (!m_Assemblies.ContainsKey(i.AssetID)) continue; assembly = m_Assemblies[i.AssetID]; } i.SaveState(assembly); } instances.Clear(); if (saveTime > 0) m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup), new Object[] { saveTime }); return 0; } public object DoMaintenance(object p) { object[] parms = (object[])p; int sleepTime = (int)parms[0]; foreach (IScriptInstance inst in m_Scripts.Values) { if (inst.EventTime() > m_EventLimit) { inst.Stop(100); if (!m_KillTimedOutScripts) inst.Start(); } } System.Threading.Thread.Sleep(sleepTime); m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance), new Object[]{ sleepTime }); return 0; } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "XEngine"; } } public void OnRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource) { if (script.StartsWith("//MRM:")) return; List<IScriptModule> engines = new List<IScriptModule>(m_Scene.RequestModuleInterfaces<IScriptModule>()); List<string> names = new List<string>(); foreach (IScriptModule m in engines) names.Add(m.ScriptEngineName); int lineEnd = script.IndexOf('\n'); if (lineEnd > 1) { string firstline = script.Substring(0, lineEnd).Trim(); int colon = firstline.IndexOf(':'); if (firstline.Length > 2 && firstline.Substring(0, 2) == "//" && colon != -1) { string engineName = firstline.Substring(2, colon-2); if (names.Contains(engineName)) { engine = engineName; script = "//" + script.Substring(script.IndexOf(':')+1); } else { if (engine == ScriptEngineName) { SceneObjectPart part = m_Scene.GetSceneObjectPart( localID); TaskInventoryItem item = part.Inventory.GetInventoryItem(itemID); ScenePresence presence = m_Scene.GetScenePresence( item.OwnerID); if (presence != null) { presence.ControllingClient.SendAgentAlertMessage( "Selected engine unavailable. "+ "Running script on "+ ScriptEngineName, false); } } } } } if (engine != ScriptEngineName) return; Object[] parms = new Object[]{localID, itemID, script, startParam, postOnRez, (StateSource)stateSource}; if (stateSource == (int)StateSource.ScriptedRez) { DoOnRezScript(parms); } else { lock (m_CompileQueue) { m_CompileQueue.Enqueue(parms); if (m_CurrentCompile == null) { m_CurrentCompile = m_ThreadPool.QueueWorkItem( new WorkItemCallback(this.DoOnRezScriptQueue), new Object[0]); } } } } public Object DoOnRezScriptQueue(Object dummy) { if (m_InitialStartup) { m_InitialStartup = false; System.Threading.Thread.Sleep(15000); lock (m_CompileQueue) { if (m_CompileQueue.Count==0) // No scripts on region, so won't get triggered later // by the queue becoming empty so we trigger it here m_Scene.EventManager.TriggerEmptyScriptCompileQueue(0, String.Empty); } } Object o; lock (m_CompileQueue) { o = m_CompileQueue.Dequeue(); if (o == null) { m_CurrentCompile = null; return null; } } DoOnRezScript(o); lock (m_CompileQueue) { if (m_CompileQueue.Count > 0) { m_CurrentCompile = m_ThreadPool.QueueWorkItem( new WorkItemCallback(this.DoOnRezScriptQueue), new Object[0]); } else { m_CurrentCompile = null; m_Scene.EventManager.TriggerEmptyScriptCompileQueue(m_ScriptFailCount, m_ScriptErrorMessage); m_ScriptFailCount = 0; } } return null; } private bool DoOnRezScript(object parm) { Object[] p = (Object[])parm; uint localID = (uint)p[0]; UUID itemID = (UUID)p[1]; string script =(string)p[2]; int startParam = (int)p[3]; bool postOnRez = (bool)p[4]; StateSource stateSource = (StateSource)p[5]; // Get the asset ID of the script, so we can check if we // already have it. // We must look for the part outside the m_Scripts lock because GetSceneObjectPart later triggers the // m_parts lock on SOG. At the same time, a scene object that is being deleted will take the m_parts lock // and then later on try to take the m_scripts lock in this class when it calls OnRemoveScript() SceneObjectPart part = m_Scene.GetSceneObjectPart(localID); if (part == null) { m_log.Error("[Script] SceneObjectPart unavailable. Script NOT started."); m_ScriptErrorMessage += "SceneObjectPart unavailable. Script NOT started.\n"; m_ScriptFailCount++; return false; } TaskInventoryItem item = part.Inventory.GetInventoryItem(itemID); if (item == null) { m_ScriptErrorMessage += "Can't find script inventory item.\n"; m_ScriptFailCount++; return false; } UUID assetID = item.AssetID; //m_log.DebugFormat("[XEngine] Compiling script {0} ({1} on object {2})", // item.Name, itemID.ToString(), part.ParentGroup.RootPart.Name); ScenePresence presence = m_Scene.GetScenePresence(item.OwnerID); string assembly = ""; CultureInfo USCulture = new CultureInfo("en-US"); Thread.CurrentThread.CurrentCulture = USCulture; Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap; try { lock (m_AddingAssemblies) { assembly = (string)m_Compiler.PerformScriptCompile(script, assetID.ToString(), item.OwnerID); if (!m_AddingAssemblies.ContainsKey(assembly)) { m_AddingAssemblies[assembly] = 1; } else { m_AddingAssemblies[assembly]++; } linemap = m_Compiler.LineMap(); } string[] warnings = m_Compiler.GetWarnings(); if (warnings != null && warnings.Length != 0) { foreach (string warning in warnings) { try { // DISPLAY WARNING INWORLD string text = "Warning:\n" + warning; if (text.Length > 1000) text = text.Substring(0, 1000); if (!ShowScriptSaveResponse(item.OwnerID, assetID, text, true)) { if (presence != null && (!postOnRez)) presence.ControllingClient.SendAgentAlertMessage("Script saved with warnings, check debug window!", false); World.SimChat(Utils.StringToBytes(text), ChatTypeEnum.DebugChannel, 2147483647, part.AbsolutePosition, part.Name, part.UUID, false); } } catch (Exception e2) // LEGIT: User Scripting { m_log.Error("[XEngine]: " + "Error displaying warning in-world: " + e2.ToString()); m_log.Error("[XEngine]: " + "Warning:\r\n" + warning); } } } } catch (Exception e) { try { // DISPLAY ERROR INWORLD m_ScriptErrorMessage += "Failed to compile script in object: '" + part.ParentGroup.RootPart.Name + "' Script name: '" + item.Name + "' Error message: " + e.Message.ToString(); m_ScriptFailCount++; string text = "Error compiling script '" + item.Name + "':\n" + e.Message.ToString(); if (text.Length > 1000) text = text.Substring(0, 1000); if (!ShowScriptSaveResponse(item.OwnerID, assetID, text, false)) { if (presence != null && (!postOnRez)) presence.ControllingClient.SendAgentAlertMessage("Script saved with errors, check debug window!", false); World.SimChat(Utils.StringToBytes(text), ChatTypeEnum.DebugChannel, 2147483647, part.AbsolutePosition, part.Name, part.UUID, false); } } catch (Exception e2) // LEGIT: User Scripting { m_log.Error("[XEngine]: "+ "Error displaying error in-world: " + e2.ToString()); m_log.Error("[XEngine]: " + "Errormessage: Error compiling script:\r\n" + e.Message.ToString()); } return false; } lock (m_Scripts) { ScriptInstance instance = null; // Create the object record if ((!m_Scripts.ContainsKey(itemID)) || (m_Scripts[itemID].AssetID != assetID)) { UUID appDomain = assetID; if (part.ParentGroup.IsAttachment) appDomain = part.ParentGroup.RootPart.UUID; if (!m_AppDomains.ContainsKey(appDomain)) { try { AppDomainSetup appSetup = new AppDomainSetup(); // appSetup.ApplicationBase = Path.Combine( // "ScriptEngines", // m_Scene.RegionInfo.RegionID.ToString()); Evidence baseEvidence = AppDomain.CurrentDomain.Evidence; Evidence evidence = new Evidence(baseEvidence); AppDomain sandbox = AppDomain.CreateDomain( m_Scene.RegionInfo.RegionID.ToString(), evidence, appSetup); /* PolicyLevel sandboxPolicy = PolicyLevel.CreateAppDomainLevel(); AllMembershipCondition sandboxMembershipCondition = new AllMembershipCondition(); PermissionSet sandboxPermissionSet = sandboxPolicy.GetNamedPermissionSet("Internet"); PolicyStatement sandboxPolicyStatement = new PolicyStatement(sandboxPermissionSet); CodeGroup sandboxCodeGroup = new UnionCodeGroup(sandboxMembershipCondition, sandboxPolicyStatement); sandboxPolicy.RootCodeGroup = sandboxCodeGroup; sandbox.SetAppDomainPolicy(sandboxPolicy); */ m_AppDomains[appDomain] = sandbox; m_AppDomains[appDomain].AssemblyResolve += new ResolveEventHandler( AssemblyResolver.OnAssemblyResolve); m_DomainScripts[appDomain] = new List<UUID>(); } catch (Exception e) { m_log.ErrorFormat("[XEngine] Exception creating app domain:\n {0}", e.ToString()); m_ScriptErrorMessage += "Exception creating app domain:\n"; m_ScriptFailCount++; lock (m_AddingAssemblies) { m_AddingAssemblies[assembly]--; } return false; } } m_DomainScripts[appDomain].Add(itemID); instance = new ScriptInstance(this, part, itemID, assetID, assembly, m_AppDomains[appDomain], part.ParentGroup.RootPart.Name, item.Name, startParam, postOnRez, stateSource, m_MaxScriptQueue); m_log.DebugFormat("[XEngine] Loaded script {0}.{1}, script UUID {2}, prim UUID {3} @ {4}", part.ParentGroup.RootPart.Name, item.Name, assetID, part.UUID, part.ParentGroup.RootPart.AbsolutePosition.ToString()); if (presence != null) { ShowScriptSaveResponse(item.OwnerID, assetID, "Compile successful", true); } instance.AppDomain = appDomain; instance.LineMap = linemap; m_Scripts[itemID] = instance; } lock (m_PrimObjects) { if (!m_PrimObjects.ContainsKey(localID)) m_PrimObjects[localID] = new List<UUID>(); if (!m_PrimObjects[localID].Contains(itemID)) m_PrimObjects[localID].Add(itemID); } if (!m_Assemblies.ContainsKey(assetID)) m_Assemblies[assetID] = assembly; lock (m_AddingAssemblies) { m_AddingAssemblies[assembly]--; } if (instance!=null) instance.Init(); } return true; } public void OnRemoveScript(uint localID, UUID itemID) { lock (m_Scripts) { // Do we even have it? if (!m_Scripts.ContainsKey(itemID)) return; IScriptInstance instance=m_Scripts[itemID]; m_Scripts.Remove(itemID); instance.ClearQueue(); instance.Stop(0); SceneObjectPart part = m_Scene.GetSceneObjectPart(localID); if (part != null) part.RemoveScriptEvents(itemID); // bool objectRemoved = false; lock (m_PrimObjects) { // Remove the script from it's prim if (m_PrimObjects.ContainsKey(localID)) { // Remove inventory item record if (m_PrimObjects[localID].Contains(itemID)) m_PrimObjects[localID].Remove(itemID); // If there are no more scripts, remove prim if (m_PrimObjects[localID].Count == 0) { m_PrimObjects.Remove(localID); // objectRemoved = true; } } } instance.RemoveState(); instance.DestroyScriptInstance(); m_DomainScripts[instance.AppDomain].Remove(instance.ItemID); if (m_DomainScripts[instance.AppDomain].Count == 0) { m_DomainScripts.Remove(instance.AppDomain); UnloadAppDomain(instance.AppDomain); } instance = null; ObjectRemoved handlerObjectRemoved = OnObjectRemoved; if (handlerObjectRemoved != null) handlerObjectRemoved(part.UUID); CleanAssemblies(); } ScriptRemoved handlerScriptRemoved = OnScriptRemoved; if (handlerScriptRemoved != null) handlerScriptRemoved(itemID); } public void OnScriptReset(uint localID, UUID itemID) { ResetScript(itemID); } public void OnStartScript(uint localID, UUID itemID) { StartScript(itemID); } public void OnStopScript(uint localID, UUID itemID) { StopScript(itemID); } private void CleanAssemblies() { List<UUID> assetIDList = new List<UUID>(m_Assemblies.Keys); foreach (IScriptInstance i in m_Scripts.Values) { if (assetIDList.Contains(i.AssetID)) assetIDList.Remove(i.AssetID); } lock (m_AddingAssemblies) { foreach (UUID assetID in assetIDList) { // Do not remove assembly files if another instance of the script // is currently initialising if (!m_AddingAssemblies.ContainsKey(m_Assemblies[assetID]) || m_AddingAssemblies[m_Assemblies[assetID]] == 0) { // m_log.DebugFormat("[XEngine] Removing unreferenced assembly {0}", m_Assemblies[assetID]); try { if (File.Exists(m_Assemblies[assetID])) File.Delete(m_Assemblies[assetID]); if (File.Exists(m_Assemblies[assetID]+".text")) File.Delete(m_Assemblies[assetID]+".text"); if (File.Exists(m_Assemblies[assetID]+".mdb")) File.Delete(m_Assemblies[assetID]+".mdb"); if (File.Exists(m_Assemblies[assetID]+".map")) File.Delete(m_Assemblies[assetID]+".map"); } catch (Exception) { } m_Assemblies.Remove(assetID); } } } } private void UnloadAppDomain(UUID id) { if (m_AppDomains.ContainsKey(id)) { AppDomain domain = m_AppDomains[id]; m_AppDomains.Remove(id); AppDomain.Unload(domain); domain = null; // m_log.DebugFormat("[XEngine] Unloaded app domain {0}", id.ToString()); } } // // Start processing // private void SetupEngine(int minThreads, int maxThreads, int idleTimeout, ThreadPriority threadPriority, int maxScriptQueue, int stackSize) { m_MaxScriptQueue = maxScriptQueue; STPStartInfo startInfo = new STPStartInfo(); startInfo.IdleTimeout = idleTimeout*1000; // convert to seconds as stated in .ini startInfo.MaxWorkerThreads = maxThreads; startInfo.MinWorkerThreads = minThreads; startInfo.ThreadPriority = threadPriority; startInfo.StackSize = stackSize; startInfo.StartSuspended = true; m_ThreadPool = new SmartThreadPool(startInfo); } // // Used by script instances to queue event handler jobs // public IScriptWorkItem QueueEventHandler(object parms) { return new XWorkItem(m_ThreadPool.QueueWorkItem( new WorkItemCallback(this.ProcessEventHandler), parms)); } /// <summary> /// Process a previously posted script event. /// </summary> /// <param name="parms"></param> /// <returns></returns> private object ProcessEventHandler(object parms) { CultureInfo USCulture = new CultureInfo("en-US"); Thread.CurrentThread.CurrentCulture = USCulture; IScriptInstance instance = (ScriptInstance) parms; //m_log.DebugFormat("[XENGINE]: Processing event for {0}", instance); return instance.EventProcessor(); } /// <summary> /// Post event to an entire prim /// </summary> /// <param name="localID"></param> /// <param name="p"></param> /// <returns></returns> public bool PostObjectEvent(uint localID, EventParams p) { bool result = false; lock (m_PrimObjects) { if (!m_PrimObjects.ContainsKey(localID)) return false; foreach (UUID itemID in m_PrimObjects[localID]) { if (m_Scripts.ContainsKey(itemID)) { IScriptInstance instance = m_Scripts[itemID]; if (instance != null) { instance.PostEvent(p); result = true; } } } } return result; } /// <summary> /// Post an event to a single script /// </summary> /// <param name="itemID"></param> /// <param name="p"></param> /// <returns></returns> public bool PostScriptEvent(UUID itemID, EventParams p) { if (m_Scripts.ContainsKey(itemID)) { IScriptInstance instance = m_Scripts[itemID]; if (instance != null) instance.PostEvent(p); return true; } return false; } public bool PostScriptEvent(UUID itemID, string name, Object[] p) { Object[] lsl_p = new Object[p.Length]; for (int i = 0; i < p.Length ; i++) { if (p[i] is int) lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]); else if (p[i] is string) lsl_p[i] = new LSL_Types.LSLString((string)p[i]); else if (p[i] is Vector3) lsl_p[i] = new LSL_Types.Vector3(((Vector3)p[i]).X, ((Vector3)p[i]).Y, ((Vector3)p[i]).Z); else if (p[i] is Quaternion) lsl_p[i] = new LSL_Types.Quaternion(((Quaternion)p[i]).X, ((Quaternion)p[i]).Y, ((Quaternion)p[i]).Z, ((Quaternion)p[i]).W); else if (p[i] is float) lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]); else lsl_p[i] = p[i]; } return PostScriptEvent(itemID, new EventParams(name, lsl_p, new DetectParams[0])); } public bool PostObjectEvent(UUID itemID, string name, Object[] p) { SceneObjectPart part = m_Scene.GetSceneObjectPart(itemID); if (part == null) return false; Object[] lsl_p = new Object[p.Length]; for (int i = 0; i < p.Length ; i++) { if (p[i] is int) lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]); else if (p[i] is string) lsl_p[i] = new LSL_Types.LSLString((string)p[i]); else if (p[i] is Vector3) lsl_p[i] = new LSL_Types.Vector3(((Vector3)p[i]).X, ((Vector3)p[i]).Y, ((Vector3)p[i]).Z); else if (p[i] is Quaternion) lsl_p[i] = new LSL_Types.Quaternion(((Quaternion)p[i]).X, ((Quaternion)p[i]).Y, ((Quaternion)p[i]).Z, ((Quaternion)p[i]).W); else if (p[i] is float) lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]); else lsl_p[i] = p[i]; } return PostObjectEvent(part.LocalId, new EventParams(name, lsl_p, new DetectParams[0])); } public Assembly OnAssemblyResolve(object sender, ResolveEventArgs args) { if (!(sender is System.AppDomain)) return null; string[] pathList = new string[] {"bin", "ScriptEngines", Path.Combine("ScriptEngines", m_Scene.RegionInfo.RegionID.ToString())}; string assemblyName = args.Name; if (assemblyName.IndexOf(",") != -1) assemblyName = args.Name.Substring(0, args.Name.IndexOf(",")); foreach (string s in pathList) { string path = Path.Combine(Directory.GetCurrentDirectory(), Path.Combine(s, assemblyName))+".dll"; if (File.Exists(path)) return Assembly.LoadFrom(path); } return null; } private IScriptInstance GetInstance(UUID itemID) { IScriptInstance instance; lock (m_Scripts) { if (!m_Scripts.ContainsKey(itemID)) return null; instance = m_Scripts[itemID]; } return instance; } public void SetScriptState(UUID itemID, bool running) { IScriptInstance instance = GetInstance(itemID); if (instance != null) { if (running) instance.Start(); else instance.Stop(100); } } public bool GetScriptState(UUID itemID) { IScriptInstance instance = GetInstance(itemID); if (instance != null) return instance.Running; return false; } public void ApiResetScript(UUID itemID) { IScriptInstance instance = GetInstance(itemID); if (instance != null) instance.ApiResetScript(); } public void ResetScript(UUID itemID) { IScriptInstance instance = GetInstance(itemID); if (instance != null) instance.ResetScript(); } public void StartScript(UUID itemID) { IScriptInstance instance = GetInstance(itemID); if (instance != null) instance.Start(); } public void StopScript(UUID itemID) { IScriptInstance instance = GetInstance(itemID); if (instance != null) instance.Stop(0); } public DetectParams GetDetectParams(UUID itemID, int idx) { IScriptInstance instance = GetInstance(itemID); if (instance != null) return instance.GetDetectParams(idx); return null; } public void SetMinEventDelay(UUID itemID, double delay) { IScriptInstance instance = GetInstance(itemID); if (instance != null) instance.MinEventDelay = delay; } public UUID GetDetectID(UUID itemID, int idx) { IScriptInstance instance = GetInstance(itemID); if (instance != null) return instance.GetDetectID(idx); return UUID.Zero; } public void SetState(UUID itemID, string newState) { IScriptInstance instance = GetInstance(itemID); if (instance == null) return; instance.SetState(newState); } public string GetState(UUID itemID) { IScriptInstance instance = GetInstance(itemID); if (instance == null) return "default"; return instance.State; } public int GetStartParameter(UUID itemID) { IScriptInstance instance = GetInstance(itemID); if (instance == null) return 0; return instance.StartParam; } public void OnShutdown() { List<IScriptInstance> instances = new List<IScriptInstance>(); lock (m_Scripts) { foreach (IScriptInstance instance in m_Scripts.Values) instances.Add(instance); } foreach (IScriptInstance i in instances) { // Stop the script, even forcibly if needed. Then flag // it as shutting down and restore the previous run state // for serialization, so the scripts don't come back // dead after region restart // bool prevRunning = i.Running; i.Stop(50); i.ShuttingDown = true; i.Running = prevRunning; } DoBackup(new Object[] {0}); } public IScriptApi GetApi(UUID itemID, string name) { IScriptInstance instance = GetInstance(itemID); if (instance == null) return null; return instance.GetApi(name); } public void OnGetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID) { IScriptInstance instance = GetInstance(itemID); if (instance == null) return; IEventQueue eq = World.RequestModuleInterface<IEventQueue>(); if (eq == null) { controllingClient.SendScriptRunningReply(objectID, itemID, GetScriptState(itemID)); } else { eq.Enqueue(EventQueueHelper.ScriptRunningReplyEvent(objectID, itemID, GetScriptState(itemID), true), controllingClient.AgentId); } } public string GetAssemblyName(UUID itemID) { IScriptInstance instance = GetInstance(itemID); if (instance == null) return ""; return instance.GetAssemblyName(); } public string GetXMLState(UUID itemID) { IScriptInstance instance = GetInstance(itemID); if (instance == null) return ""; return instance.GetXMLState(); } public bool CanBeDeleted(UUID itemID) { IScriptInstance instance = GetInstance(itemID); if (instance == null) return true; return instance.CanBeDeleted(); } private bool ShowScriptSaveResponse(UUID ownerID, UUID assetID, string text, bool compiled) { return false; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace Lucene.Net.Store { /// <summary> A memory-resident {@link Directory} implementation. Locking /// implementation is by default the {@link SingleInstanceLockFactory} /// but can be changed with {@link #setLockFactory}. /// /// </summary> [Serializable] public class RAMDirectory : Directory { private const long serialVersionUID = 1L; internal System.Collections.Hashtable fileMap = new System.Collections.Hashtable(); internal long sizeInBytes = 0; public System.Collections.Hashtable fileMap_ForNUnitTest { get { return fileMap; } } public long sizeInBytes_ForNUnitTest { get { return sizeInBytes; } set { sizeInBytes = value; } } //https://issues.apache.org/jira/browse/LUCENENET-174 [System.Runtime.Serialization.OnDeserialized] void OnDeserialized(System.Runtime.Serialization.StreamingContext context) { if (lockFactory == null) { SetLockFactory(new SingleInstanceLockFactory()); } } // ***** // Lock acquisition sequence: RAMDirectory, then RAMFile // ***** /// <summary>Constructs an empty {@link Directory}. </summary> public RAMDirectory() { SetLockFactory(new SingleInstanceLockFactory()); } /// <summary> Creates a new <code>RAMDirectory</code> instance from a different /// <code>Directory</code> implementation. This can be used to load /// a disk-based index into memory. /// <P> /// This should be used only with indices that can fit into memory. /// <P> /// Note that the resulting <code>RAMDirectory</code> instance is fully /// independent from the original <code>Directory</code> (it is a /// complete copy). Any subsequent changes to the /// original <code>Directory</code> will not be visible in the /// <code>RAMDirectory</code> instance. /// /// </summary> /// <param name="dir">a <code>Directory</code> value /// </param> /// <exception cref=""> IOException if an error occurs /// </exception> public RAMDirectory(Directory dir):this(dir, false) { } private RAMDirectory(Directory dir, bool closeDir):this() { Directory.Copy(dir, this, closeDir); } /// <summary> Creates a new <code>RAMDirectory</code> instance from the {@link FSDirectory}. /// /// </summary> /// <param name="dir">a <code>File</code> specifying the index directory /// /// </param> /// <seealso cref="RAMDirectory(Directory)"> /// </seealso> public RAMDirectory(System.IO.FileInfo dir):this(FSDirectory.GetDirectory(dir), true) { } /// <summary> Creates a new <code>RAMDirectory</code> instance from the {@link FSDirectory}. /// /// </summary> /// <param name="dir">a <code>String</code> specifying the full index directory path /// /// </param> /// <seealso cref="RAMDirectory(Directory)"> /// </seealso> public RAMDirectory(System.String dir) : this(FSDirectory.GetDirectory(dir), true) { } /// <summary>Returns an array of strings, one for each file in the directory. </summary> public override System.String[] List() { lock (this) { EnsureOpen(); System.String[] result = new System.String[fileMap.Count]; int i = 0; System.Collections.IEnumerator it = fileMap.Keys.GetEnumerator(); while (it.MoveNext()) { result[i++] = ((System.String) it.Current); } return result; } } /// <summary>Returns true iff the named file exists in this directory. </summary> public override bool FileExists(System.String name) { EnsureOpen(); RAMFile file; lock (this) { file = (RAMFile) fileMap[name]; } return file != null; } /// <summary>Returns the time the named file was last modified.</summary> /// <throws> IOException if the file does not exist </throws> public override long FileModified(System.String name) { EnsureOpen(); RAMFile file; lock (this) { file = (RAMFile) fileMap[name]; } if (file == null) throw new System.IO.FileNotFoundException(name); return file.GetLastModified(); } /// <summary>Set the modified time of an existing file to now.</summary> /// <throws> IOException if the file does not exist </throws> public override void TouchFile(System.String name) { EnsureOpen(); RAMFile file; lock (this) { file = (RAMFile) fileMap[name]; } if (file == null) throw new System.IO.FileNotFoundException(name); long ts2, ts1 = System.DateTime.Now.Ticks; do { try { System.Threading.Thread.Sleep(new System.TimeSpan((System.Int64) 10000 * 0 + 100 * 1)); } catch (System.Threading.ThreadInterruptedException) { } ts2 = System.DateTime.Now.Ticks; } while (ts1 == ts2); file.SetLastModified(ts2); } /// <summary>Returns the length in bytes of a file in the directory.</summary> /// <throws> IOException if the file does not exist </throws> public override long FileLength(System.String name) { EnsureOpen(); RAMFile file; lock (this) { file = (RAMFile) fileMap[name]; } if (file == null) throw new System.IO.FileNotFoundException(name); return file.GetLength(); } /// <summary>Return total size in bytes of all files in this /// directory. This is currently quantized to /// RAMOutputStream.BUFFER_SIZE. /// </summary> public long SizeInBytes() { lock (this) { EnsureOpen(); return sizeInBytes; } } /// <summary>Removes an existing file in the directory.</summary> /// <throws> IOException if the file does not exist </throws> public override void DeleteFile(System.String name) { lock (this) { EnsureOpen(); RAMFile file = (RAMFile) fileMap[name]; if (file != null) { fileMap.Remove(name); file.directory = null; sizeInBytes -= file.sizeInBytes; // updates to RAMFile.sizeInBytes synchronized on directory } else throw new System.IO.FileNotFoundException(name); } } /// <summary>Renames an existing file in the directory.</summary> /// <throws> FileNotFoundException if from does not exist </throws> /// <deprecated> /// </deprecated> public override void RenameFile(System.String from, System.String to) { lock (this) { EnsureOpen(); RAMFile fromFile = (RAMFile) fileMap[from]; if (fromFile == null) throw new System.IO.FileNotFoundException(from); RAMFile toFile = (RAMFile) fileMap[to]; if (toFile != null) { sizeInBytes -= toFile.sizeInBytes; // updates to RAMFile.sizeInBytes synchronized on directory toFile.directory = null; } fileMap.Remove(from); fileMap[to] = fromFile; } } /// <summary>Creates a new, empty file in the directory with the given name. Returns a stream writing this file. </summary> public override IndexOutput CreateOutput(System.String name) { EnsureOpen(); RAMFile file = new RAMFile(this); lock (this) { RAMFile existing = (RAMFile) fileMap[name]; if (existing != null) { sizeInBytes -= existing.sizeInBytes; existing.directory = null; } fileMap[name] = file; } return new RAMOutputStream(file); } /// <summary>Returns a stream reading an existing file. </summary> public override IndexInput OpenInput(System.String name) { EnsureOpen(); RAMFile file; lock (this) { file = (RAMFile) fileMap[name]; } if (file == null) throw new System.IO.FileNotFoundException(name); return new RAMInputStream(file); } /// <summary>Closes the store to future operations, releasing associated memory. </summary> public override void Close() { isOpen = false; fileMap = null; } /// <throws> AlreadyClosedException if this IndexReader is closed </throws> protected internal override void EnsureOpen() { if (fileMap == null) { throw new AlreadyClosedException("this RAMDirectory is closed"); } } } }
using System; using System.Collections.Generic; using Fairweather.Service; using Versioning; namespace Common { public enum Command_Line_Switch { } public static class Enum_Service { public static string Friendly_String(this Payment_Type type) { var ret = type.Get_String().Replace("_", " ").Replace("que", "ques").Replace("ost ", "ost-"); return ret; } public static string Friendly_String(this EOS_Breakdown_Type type) { var ret = type.Get_String().Replace("_", " "); return ret; } static Dictionary<Sub_App, string> Sub_App_Friendly = new Dictionary<Sub_App, string> { {Sub_App.Products, "Point Of Sales"}, {Sub_App.Ses_Cfg, "Sage Entry Screens Configuration"}, {Sub_App.Entry_Customers, "Customer Receipts"}, {Sub_App.Entry_Suppliers, "Supplier Payments"}, //{Sub_App.Documents_Transfer, "Documents Transfer"}, }; public static string Friendly_String(this Sub_App module) { var ret = Sub_App_Friendly.Get_Or_Default(module, () => module.Get_String().Replace("_", " ")); return ret; } const int _flag1 = 0x1; const int _flag2 = 2 * _flag1; const int _flag3 = 2 * _flag2; const int _flag4 = 2 * _flag3; const int _flag5 = 2 * _flag4; const int _flag6 = 2 * _flag5; const int flag1 = 0x00100000; const int flag2 = 2 * flag1; const int flag3 = 2 * flag2; const int flag4 = 2 * flag3; const int flag5 = 2 * flag4; const int flag6 = 2 * flag5; public const int Command_Line_Status_Valid = flag1, Command_Line_Status_Has_Company = flag2 | Command_Line_Status_Valid, Command_Line_Status_Has_Company_Username_Password = flag3 | Command_Line_Status_Has_Company; public const int SES_suite = flag1; public const int SIT_suite = flag2; public const int SES_app = flag1; public const int SESCFG_app = flag2; public const int SIT_app = flag1; public const int Switch_Takes_Param = flag1; public static bool Is_Valid(this Command_Line_Status status) { return status.Contains(Command_Line_Status_Valid); } public static App Application(this Sub_App status) { if (status.Contains(App.Entry_Screens)) return App.Entry_Screens; if (status.Contains(App.Ses_Cfg)) return App.Ses_Cfg; if (status.Contains(App.Sit_Exe)) return App.Sit_Exe; true.tift(); throw new InvalidOperationException(); } public static bool Takes_Parameter(this Command_Line_Switch cswitch) { return cswitch.Contains(Switch_Takes_Param); } public static int Return(this Return_Code code) { return (int)code; } public static int MaxLength(this Record_Type type) { var dict = new Dictionary<Record_Type, int> { {Record_Type.Sales, 8}, {Record_Type.Purchase, 8}, {Record_Type.Bank, 8}, {Record_Type.Stock, 30}, {Record_Type.Department, 4}, {Record_Type.Expense, 8}, {Record_Type.TT, 2}, {Record_Type.Tax_Code, 3}, {Record_Type.Project, 8}, {Record_Type.Cost_Code, 8}, }; return dict[type]; } static public string Friendly_String(this Receipt_Layout layout) { return new Dictionary<Receipt_Layout, string>{ {Receipt_Layout.Standard_Vertical, "Standard Vertical"}}[layout]; } static readonly Twoway<Document_Type, InvoiceType> doc_to_invoice = new Twoway<Document_Type, InvoiceType> { {Document_Type.Product_Invoice, InvoiceType.sdoProductInvoice}, {Document_Type.Product_Credit, InvoiceType.sdoProductCredit}, }; static readonly Twoway<Document_Type, int> doc_to_combo_box_index = new Twoway<Document_Type, int> { {Document_Type.Product_Invoice, 0}, {Document_Type.Product_Credit, 1}, }; static readonly Twoway<Document_Type, Grid_Mode> doc_to_grid = new Twoway<Document_Type, Grid_Mode> { {Document_Type.Product_Invoice, Grid_Mode.Invoice }, {Document_Type.Product_Credit, Grid_Mode.Credit_Note}, }; public static Document_Type To_Document_Type(this InvoiceType invoice_type) { return doc_to_invoice[invoice_type]; } public static Grid_Mode To_Grid_Mode(this Document_Type document_type) { return doc_to_grid[document_type]; } public static Document_Type To_Document_Type(this Grid_Mode grid_mode) { Document_Type ret; if (grid_mode == Grid_Mode.Invoice_Against_Credit_Note) ret = Document_Type.Product_Invoice; else ret = doc_to_grid[grid_mode]; return ret; } public static InvoiceType To_Invoice_Type(this Document_Type document_type) { return doc_to_invoice[document_type]; } public static int To_Combobox_Index(this Document_Type document_type) { return doc_to_combo_box_index[document_type]; } public static Document_Type From_Combo_Box_Index(int index) { return doc_to_combo_box_index[index]; } public static bool Own_Msg(this Sage_Connection_Error error) { return false; } public static bool Show_Msg(this Sage_Connection_Error error) { return true; } public static bool Try_Again_Later(this Sage_Connection_Error error) { return error != Sage_Connection_Error.Invalid_Credentials; } public static bool Can_Retry(this Sage_Connection_Error error) { //static readonly Set<Sage_Connection_Error> //can_retry = new Set<Sage_Connection_Error> { Sage_Connection_Error.Exclusive_Mode }; return error == Sage_Connection_Error.Exclusive_Mode || error == Sage_Connection_Error.Username_In_Use_Generic || error == Sage_Connection_Error.Logon_Count_Exceeded || error == Sage_Connection_Error.Unspecified ; } } }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Relational.Migrations.Infrastructure; using WebApplication5.Data; namespace WebApplication5.Migrations { [ContextType(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { public override void BuildModel(ModelBuilder builder) { builder .Annotation("SqlServer:ValueGeneration", "Identity"); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 0); b.Property<string>("ConcurrencyStamp") .ConcurrencyToken() .Annotation("OriginalValueIndex", 1); b.Property<string>("Name") .Annotation("OriginalValueIndex", 2); b.Property<string>("NormalizedName") .Annotation("OriginalValueIndex", 3); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetRoles"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity) .Annotation("OriginalValueIndex", 0); b.Property<string>("ClaimType") .Annotation("OriginalValueIndex", 1); b.Property<string>("ClaimValue") .Annotation("OriginalValueIndex", 2); b.Property<string>("RoleId") .Annotation("OriginalValueIndex", 3); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetRoleClaims"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity) .Annotation("OriginalValueIndex", 0); b.Property<string>("ClaimType") .Annotation("OriginalValueIndex", 1); b.Property<string>("ClaimValue") .Annotation("OriginalValueIndex", 2); b.Property<string>("UserId") .Annotation("OriginalValueIndex", 3); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetUserClaims"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 0); b.Property<string>("ProviderKey") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 1); b.Property<string>("ProviderDisplayName") .Annotation("OriginalValueIndex", 2); b.Property<string>("UserId") .Annotation("OriginalValueIndex", 3); b.Key("LoginProvider", "ProviderKey"); b.Annotation("Relational:TableName", "AspNetUserLogins"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId") .Annotation("OriginalValueIndex", 0); b.Property<string>("RoleId") .Annotation("OriginalValueIndex", 1); b.Key("UserId", "RoleId"); b.Annotation("Relational:TableName", "AspNetUserRoles"); }); builder.Entity("WebApplication5.Models.ApplicationUser", b => { b.Property<string>("Id") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 0); b.Property<int>("AccessFailedCount") .Annotation("OriginalValueIndex", 1); b.Property<string>("ConcurrencyStamp") .ConcurrencyToken() .Annotation("OriginalValueIndex", 2); b.Property<string>("Email") .Annotation("OriginalValueIndex", 3); b.Property<bool>("EmailConfirmed") .Annotation("OriginalValueIndex", 4); b.Property<bool>("LockoutEnabled") .Annotation("OriginalValueIndex", 5); b.Property<DateTimeOffset?>("LockoutEnd") .Annotation("OriginalValueIndex", 6); b.Property<string>("NormalizedEmail") .Annotation("OriginalValueIndex", 7); b.Property<string>("NormalizedUserName") .Annotation("OriginalValueIndex", 8); b.Property<string>("PasswordHash") .Annotation("OriginalValueIndex", 9); b.Property<string>("PhoneNumber") .Annotation("OriginalValueIndex", 10); b.Property<bool>("PhoneNumberConfirmed") .Annotation("OriginalValueIndex", 11); b.Property<string>("SecurityStamp") .Annotation("OriginalValueIndex", 12); b.Property<bool>("TwoFactorEnabled") .Annotation("OriginalValueIndex", 13); b.Property<string>("UserName") .Annotation("OriginalValueIndex", 14); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetUsers"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .InverseCollection() .ForeignKey("RoleId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Reference("WebApplication5.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Reference("WebApplication5.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .InverseCollection() .ForeignKey("RoleId"); b.Reference("WebApplication5.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); } } }
using System; namespace Microsoft.VisualStudio.Services.Agent { public enum RunMode { Normal, // Keep "Normal" first (default value). Local, } public enum WellKnownDirectory { Bin, Diag, Externals, LegacyPSHost, Root, ServerOM, Tasks, Tee, Temp, Tools, Update, Work, } public enum WellKnownConfigFile { Agent, Credentials, RSACredentials, Service, CredentialStore, Certificates, Proxy, ProxyCredentials, ProxyBypass, Autologon, Options, } public static class Constants { /// <summary>Path environment varible name.</summary> #if OS_WINDOWS public static readonly string PathVariable = "Path"; #else public static readonly string PathVariable = "PATH"; #endif public static string TFBuild = "TF_BUILD"; public static string ProcessLookupId = "VSTS_PROCESS_LOOKUP_ID"; // This enum is embedded within the Constants class to make it easier to reference and avoid // ambiguous type reference with System.Runtime.InteropServices.OSPlatform. public enum OSPlatform { OSX, Linux, Windows } public static class Agent { public static readonly string Version = "2.138.5"; #if OS_LINUX public static readonly OSPlatform Platform = OSPlatform.Linux; #elif OS_OSX public static readonly OSPlatform Platform = OSPlatform.OSX; #elif OS_WINDOWS public static readonly OSPlatform Platform = OSPlatform.Windows; #endif public static readonly TimeSpan ExitOnUnloadTimeout = TimeSpan.FromSeconds(30); public static class CommandLine { //if you are adding a new arg, please make sure you update the //validArgs array as well present in the CommandSettings.cs public static class Args { public static readonly string Agent = "agent"; public static readonly string Auth = "auth"; public static readonly string CollectionName = "collectionname"; public static readonly string DeploymentGroupName = "deploymentgroupname"; public static readonly string DeploymentPoolName = "deploymentpoolname"; public static readonly string DeploymentGroupTags = "deploymentgrouptags"; public static readonly string MachineGroupName = "machinegroupname"; public static readonly string MachineGroupTags = "machinegrouptags"; public static readonly string Matrix = "matrix"; public static readonly string NotificationPipeName = "notificationpipename"; public static readonly string NotificationSocketAddress = "notificationsocketaddress"; public static readonly string Phase = "phase"; public static readonly string Pool = "pool"; public static readonly string ProjectName = "projectname"; public static readonly string ProxyUrl = "proxyurl"; public static readonly string ProxyUserName = "proxyusername"; public static readonly string SslCACert = "sslcacert"; public static readonly string SslClientCert = "sslclientcert"; public static readonly string SslClientCertKey = "sslclientcertkey"; public static readonly string SslClientCertArchive = "sslclientcertarchive"; public static readonly string SslClientCertPassword = "sslclientcertpassword"; public static readonly string StartupType = "startuptype"; public static readonly string Url = "url"; public static readonly string UserName = "username"; public static readonly string WindowsLogonAccount = "windowslogonaccount"; public static readonly string Work = "work"; public static readonly string Yml = "yml"; // Secret args. Must be added to the "Secrets" getter as well. public static readonly string Password = "password"; public static readonly string ProxyPassword = "proxypassword"; public static readonly string Token = "token"; public static readonly string WindowsLogonPassword = "windowslogonpassword"; public static string[] Secrets => new[] { Password, ProxyPassword, SslClientCertPassword, Token, WindowsLogonPassword, }; } public static class Commands { public static readonly string Configure = "configure"; public static readonly string LocalRun = "localRun"; public static readonly string Remove = "remove"; public static readonly string Run = "run"; } //if you are adding a new flag, please make sure you update the //validFlags array as well present in the CommandSettings.cs public static class Flags { public static readonly string AcceptTeeEula = "acceptteeeula"; public static readonly string AddDeploymentGroupTags = "adddeploymentgrouptags"; public static readonly string AddMachineGroupTags = "addmachinegrouptags"; public static readonly string Commit = "commit"; public static readonly string DeploymentGroup = "deploymentgroup"; public static readonly string DeploymentPool = "deploymentpool"; public static readonly string OverwriteAutoLogon = "overwriteautologon"; public static readonly string GitUseSChannel = "gituseschannel"; public static readonly string Help = "help"; public static readonly string MachineGroup = "machinegroup"; public static readonly string Replace = "replace"; public static readonly string NoRestart = "norestart"; public static readonly string RunAsAutoLogon = "runasautologon"; public static readonly string RunAsService = "runasservice"; public static readonly string SslSkipCertValidation = "sslskipcertvalidation"; public static readonly string Unattended = "unattended"; public static readonly string Version = "version"; public static readonly string WhatIf = "whatif"; } } public static class ReturnCode { public const int Success = 0; public const int TerminatedError = 1; public const int RetryableError = 2; public const int AgentUpdating = 3; } public static class AgentConfigurationProvider { public static readonly string BuildReleasesAgentConfiguration = "BuildReleasesAgentConfiguration"; public static readonly string DeploymentAgentConfiguration = "DeploymentAgentConfiguration"; public static readonly string SharedDeploymentAgentConfiguration = "SharedDeploymentAgentConfiguration"; } } public static class Build { public static readonly string NoCICheckInComment = "***NO_CI***"; public static class Path { public static readonly string ArtifactsDirectory = "a"; public static readonly string BinariesDirectory = "b"; public static readonly string GarbageCollectionDirectory = "GC"; public static readonly string LegacyArtifactsDirectory = "artifacts"; public static readonly string LegacyStagingDirectory = "staging"; public static readonly string SourceRootMappingDirectory = "SourceRootMapping"; public static readonly string SourcesDirectory = "s"; public static readonly string TestResultsDirectory = "TestResults"; public static readonly string TopLevelTrackingConfigFile = "Mappings.json"; public static readonly string TrackingConfigFile = "SourceFolder.json"; } } public static class Configuration { public static readonly string PAT = "PAT"; public static readonly string Alternate = "ALT"; public static readonly string Negotiate = "Negotiate"; public static readonly string Integrated = "Integrated"; public static readonly string OAuth = "OAuth"; public static readonly string ServiceIdentity = "ServiceIdentity"; } public static class EndpointData { public static readonly string SourcesDirectory = "SourcesDirectory"; public static readonly string SourceVersion = "SourceVersion"; public static readonly string SourceBranch = "SourceBranch"; public static readonly string SourceTfvcShelveset = "SourceTfvcShelveset"; public static readonly string GatedShelvesetName = "GatedShelvesetName"; public static readonly string GatedRunCI = "GatedRunCI"; } public static class Expressions { public static readonly string Always = "always"; public static readonly string Canceled = "canceled"; public static readonly string Failed = "failed"; public static readonly string Succeeded = "succeeded"; public static readonly string SucceededOrFailed = "succeededOrFailed"; public static readonly string Variables = "variables"; } public static class Path { public static readonly string BinDirectory = "bin"; public static readonly string DiagDirectory = "_diag"; public static readonly string ExternalsDirectory = "externals"; public static readonly string LegacyPSHostDirectory = "vstshost"; public static readonly string ServerOMDirectory = "vstsom"; public static readonly string TempDirectory = "_temp"; public static readonly string TeeDirectory = "tee"; public static readonly string ToolDirectory = "_tool"; public static readonly string TaskJsonFile = "task.json"; public static readonly string TasksDirectory = "_tasks"; public static readonly string UpdateDirectory = "_update"; public static readonly string WorkDirectory = "_work"; } public static class Release { public static readonly string Map = "Map"; public static class Path { public static readonly string ArtifactsDirectory = "a"; public static readonly string CommitsDirectory = "c"; public static readonly string DefinitionMapping = "DefinitionMapping.json"; public static readonly string ReleaseDirectoryPrefix = "r"; public static readonly string ReleaseTempDirectoryPrefix = "t"; public static readonly string RootMappingDirectory = "ReleaseRootMapping"; public static readonly string TrackingConfigFile = "DefinitionMapping.json"; public static readonly string GarbageCollectionDirectory = "GC"; } } // Related to definition variables. public static class Variables { public static readonly string MacroPrefix = "$("; public static readonly string MacroSuffix = ")"; public static class Agent { // // Keep alphabetical // public static readonly string AcceptTeeEula = "agent.acceptteeeula"; public static readonly string AllowAllEndpoints = "agent.allowAllEndpoints"; // remove after sprint 120 or so. public static readonly string AllowAllSecureFiles = "agent.allowAllSecureFiles"; // remove after sprint 121 or so. public static readonly string BuildDirectory = "agent.builddirectory"; public static readonly string ContainerId = "agent.containerid"; public static readonly string ContainerNetwork = "agent.containernetwork"; public static readonly string Diagnostic = "agent.diagnostic"; public static readonly string HomeDirectory = "agent.homedirectory"; public static readonly string Id = "agent.id"; public static readonly string GitUseSChannel = "agent.gituseschannel"; public static readonly string JobName = "agent.jobname"; public static readonly string JobStatus = "agent.jobstatus"; public static readonly string MachineName = "agent.machinename"; public static readonly string Name = "agent.name"; public static readonly string OS = "agent.os"; public static readonly string OSVersion = "agent.osversion"; public static readonly string ProxyUrl = "agent.proxyurl"; public static readonly string ProxyUsername = "agent.proxyusername"; public static readonly string ProxyPassword = "agent.proxypassword"; public static readonly string ProxyBypassList = "agent.proxybypasslist"; public static readonly string RootDirectory = "agent.RootDirectory"; public static readonly string RunMode = "agent.runmode"; public static readonly string ServerOMDirectory = "agent.ServerOMDirectory"; public static readonly string SslCAInfo = "agent.cainfo"; public static readonly string SslClientCert = "agent.clientcert"; public static readonly string SslClientCertKey = "agent.clientcertkey"; public static readonly string SslClientCertArchive = "agent.clientcertarchive"; public static readonly string SslClientCertPassword = "agent.clientcertpassword"; public static readonly string SslSkipCertValidation = "agent.skipcertvalidation"; public static readonly string TempDirectory = "agent.TempDirectory"; public static readonly string ToolsDirectory = "agent.ToolsDirectory"; public static readonly string Version = "agent.version"; public static readonly string WorkFolder = "agent.workfolder"; public static readonly string WorkingDirectory = "agent.WorkingDirectory"; } public static class Build { // // Keep alphabetical // public static readonly string ArtifactStagingDirectory = "build.artifactstagingdirectory"; public static readonly string BinariesDirectory = "build.binariesdirectory"; public static readonly string Number = "build.buildNumber"; public static readonly string Clean = "build.clean"; public static readonly string DefinitionName = "build.definitionname"; public static readonly string GatedRunCI = "build.gated.runci"; public static readonly string GatedShelvesetName = "build.gated.shelvesetname"; public static readonly string RepoClean = "build.repository.clean"; public static readonly string RepoGitSubmoduleCheckout = "build.repository.git.submodulecheckout"; public static readonly string RepoId = "build.repository.id"; public static readonly string RepoLocalPath = "build.repository.localpath"; public static readonly string RepoName = "build.Repository.name"; public static readonly string RepoProvider = "build.repository.provider"; public static readonly string RepoTfvcWorkspace = "build.repository.tfvc.workspace"; public static readonly string RepoUri = "build.repository.uri"; public static readonly string SourceBranch = "build.sourcebranch"; public static readonly string SourceTfvcShelveset = "build.sourcetfvcshelveset"; public static readonly string SourceVersion = "build.sourceversion"; public static readonly string SourcesDirectory = "build.sourcesdirectory"; public static readonly string StagingDirectory = "build.stagingdirectory"; public static readonly string SyncSources = "build.syncSources"; } public static class Common { public static readonly string TestResultsDirectory = "common.testresultsdirectory"; } public static class Features { // // Keep alphabetical // public static readonly string BuildDirectoryClean = "agent.clean.buildDirectory"; public static readonly string GitLfsSupport = "agent.source.git.lfs"; public static readonly string GitShallowDepth = "agent.source.git.shallowFetchDepth"; public static readonly string SkipSyncSource = "agent.source.skip"; } public static class Release { // // Keep alphabetical // public static readonly string AgentReleaseDirectory = "agent.releaseDirectory"; public static readonly string ArtifactsDirectory = "system.artifactsDirectory"; public static readonly string AttemptNumber = "release.attemptNumber"; public static readonly string DisableRobocopy = "release.disableRobocopy"; public static readonly string ReleaseDefinitionName = "release.definitionName"; public static readonly string ReleaseEnvironmentName = "release.environmentName"; public static readonly string ReleaseEnvironmentUri = "release.environmentUri"; public static readonly string ReleaseDefinitionId = "release.definitionId"; public static readonly string ReleaseDescription = "release.releaseDescription"; public static readonly string ReleaseId = "release.releaseId"; public static readonly string ReleaseName = "release.releaseName"; public static readonly string ReleaseRequestedForId = "release.requestedForId"; public static readonly string ReleaseUri = "release.releaseUri"; public static readonly string ReleaseDownloadBufferSize = "release.artifact.download.buffersize"; public static readonly string ReleaseParallelDownloadLimit = "release.artifact.download.parallellimit"; public static readonly string ReleaseWebUrl = "release.releaseWebUrl"; public static readonly string RequestorId = "release.requestedFor"; public static readonly string RobocopyMT = "release.robocopyMT"; public static readonly string SkipArtifactsDownload = "release.skipartifactsDownload"; } public static class System { // // Keep alphabetical // public static readonly string AccessToken = "system.accessToken"; public static readonly string ArtifactsDirectory = "system.artifactsdirectory"; public static readonly string CollectionId = "system.collectionid"; public static readonly string Culture = "system.culture"; public static readonly string Debug = "system.debug"; public static readonly string DefaultWorkingDirectory = "system.defaultworkingdirectory"; public static readonly string DefinitionId = "system.definitionid"; public static readonly string EnableAccessToken = "system.enableAccessToken"; public static readonly string HostType = "system.hosttype"; public static readonly string PhaseDisplayName = "system.phaseDisplayName"; public static readonly string PreferGitFromPath = "system.prefergitfrompath"; public static readonly string SelfManageGitCreds = "system.selfmanagegitcreds"; public static readonly string ServerType = "system.servertype"; public static readonly string TFServerUrl = "system.TeamFoundationServerUri"; // back compat variable, do not document public static readonly string TeamProject = "system.teamproject"; public static readonly string TeamProjectId = "system.teamProjectId"; public static readonly string WorkFolder = "system.workfolder"; } public static class Task { public static readonly string DisplayName = "task.displayname"; } } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// TriggerResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Api.V2010.Account.Usage { public class TriggerResource : Resource { public sealed class UsageCategoryEnum : StringEnum { private UsageCategoryEnum(string value) : base(value) {} public UsageCategoryEnum() {} public static implicit operator UsageCategoryEnum(string value) { return new UsageCategoryEnum(value); } public static readonly UsageCategoryEnum AgentConference = new UsageCategoryEnum("agent-conference"); public static readonly UsageCategoryEnum AnsweringMachineDetection = new UsageCategoryEnum("answering-machine-detection"); public static readonly UsageCategoryEnum AuthyAuthentications = new UsageCategoryEnum("authy-authentications"); public static readonly UsageCategoryEnum AuthyCallsOutbound = new UsageCategoryEnum("authy-calls-outbound"); public static readonly UsageCategoryEnum AuthyMonthlyFees = new UsageCategoryEnum("authy-monthly-fees"); public static readonly UsageCategoryEnum AuthyPhoneIntelligence = new UsageCategoryEnum("authy-phone-intelligence"); public static readonly UsageCategoryEnum AuthyPhoneVerifications = new UsageCategoryEnum("authy-phone-verifications"); public static readonly UsageCategoryEnum AuthySmsOutbound = new UsageCategoryEnum("authy-sms-outbound"); public static readonly UsageCategoryEnum CallProgessEvents = new UsageCategoryEnum("call-progess-events"); public static readonly UsageCategoryEnum Calleridlookups = new UsageCategoryEnum("calleridlookups"); public static readonly UsageCategoryEnum Calls = new UsageCategoryEnum("calls"); public static readonly UsageCategoryEnum CallsClient = new UsageCategoryEnum("calls-client"); public static readonly UsageCategoryEnum CallsGlobalconference = new UsageCategoryEnum("calls-globalconference"); public static readonly UsageCategoryEnum CallsInbound = new UsageCategoryEnum("calls-inbound"); public static readonly UsageCategoryEnum CallsInboundLocal = new UsageCategoryEnum("calls-inbound-local"); public static readonly UsageCategoryEnum CallsInboundMobile = new UsageCategoryEnum("calls-inbound-mobile"); public static readonly UsageCategoryEnum CallsInboundTollfree = new UsageCategoryEnum("calls-inbound-tollfree"); public static readonly UsageCategoryEnum CallsOutbound = new UsageCategoryEnum("calls-outbound"); public static readonly UsageCategoryEnum CallsPayVerbTransactions = new UsageCategoryEnum("calls-pay-verb-transactions"); public static readonly UsageCategoryEnum CallsRecordings = new UsageCategoryEnum("calls-recordings"); public static readonly UsageCategoryEnum CallsSip = new UsageCategoryEnum("calls-sip"); public static readonly UsageCategoryEnum CallsSipInbound = new UsageCategoryEnum("calls-sip-inbound"); public static readonly UsageCategoryEnum CallsSipOutbound = new UsageCategoryEnum("calls-sip-outbound"); public static readonly UsageCategoryEnum CallsTransfers = new UsageCategoryEnum("calls-transfers"); public static readonly UsageCategoryEnum CarrierLookups = new UsageCategoryEnum("carrier-lookups"); public static readonly UsageCategoryEnum Conversations = new UsageCategoryEnum("conversations"); public static readonly UsageCategoryEnum ConversationsApiRequests = new UsageCategoryEnum("conversations-api-requests"); public static readonly UsageCategoryEnum ConversationsConversationEvents = new UsageCategoryEnum("conversations-conversation-events"); public static readonly UsageCategoryEnum ConversationsEndpointConnectivity = new UsageCategoryEnum("conversations-endpoint-connectivity"); public static readonly UsageCategoryEnum ConversationsEvents = new UsageCategoryEnum("conversations-events"); public static readonly UsageCategoryEnum ConversationsParticipantEvents = new UsageCategoryEnum("conversations-participant-events"); public static readonly UsageCategoryEnum ConversationsParticipants = new UsageCategoryEnum("conversations-participants"); public static readonly UsageCategoryEnum Cps = new UsageCategoryEnum("cps"); public static readonly UsageCategoryEnum FlexUsage = new UsageCategoryEnum("flex-usage"); public static readonly UsageCategoryEnum FraudLookups = new UsageCategoryEnum("fraud-lookups"); public static readonly UsageCategoryEnum GroupRooms = new UsageCategoryEnum("group-rooms"); public static readonly UsageCategoryEnum GroupRoomsDataTrack = new UsageCategoryEnum("group-rooms-data-track"); public static readonly UsageCategoryEnum GroupRoomsEncryptedMediaRecorded = new UsageCategoryEnum("group-rooms-encrypted-media-recorded"); public static readonly UsageCategoryEnum GroupRoomsMediaDownloaded = new UsageCategoryEnum("group-rooms-media-downloaded"); public static readonly UsageCategoryEnum GroupRoomsMediaRecorded = new UsageCategoryEnum("group-rooms-media-recorded"); public static readonly UsageCategoryEnum GroupRoomsMediaRouted = new UsageCategoryEnum("group-rooms-media-routed"); public static readonly UsageCategoryEnum GroupRoomsMediaStored = new UsageCategoryEnum("group-rooms-media-stored"); public static readonly UsageCategoryEnum GroupRoomsParticipantMinutes = new UsageCategoryEnum("group-rooms-participant-minutes"); public static readonly UsageCategoryEnum GroupRoomsRecordedMinutes = new UsageCategoryEnum("group-rooms-recorded-minutes"); public static readonly UsageCategoryEnum ImpV1Usage = new UsageCategoryEnum("imp-v1-usage"); public static readonly UsageCategoryEnum Lookups = new UsageCategoryEnum("lookups"); public static readonly UsageCategoryEnum Marketplace = new UsageCategoryEnum("marketplace"); public static readonly UsageCategoryEnum MarketplaceAlgorithmiaNamedEntityRecognition = new UsageCategoryEnum("marketplace-algorithmia-named-entity-recognition"); public static readonly UsageCategoryEnum MarketplaceCadenceTranscription = new UsageCategoryEnum("marketplace-cadence-transcription"); public static readonly UsageCategoryEnum MarketplaceCadenceTranslation = new UsageCategoryEnum("marketplace-cadence-translation"); public static readonly UsageCategoryEnum MarketplaceCapioSpeechToText = new UsageCategoryEnum("marketplace-capio-speech-to-text"); public static readonly UsageCategoryEnum MarketplaceConvrizaAbaba = new UsageCategoryEnum("marketplace-convriza-ababa"); public static readonly UsageCategoryEnum MarketplaceDeepgramPhraseDetector = new UsageCategoryEnum("marketplace-deepgram-phrase-detector"); public static readonly UsageCategoryEnum MarketplaceDigitalSegmentBusinessInfo = new UsageCategoryEnum("marketplace-digital-segment-business-info"); public static readonly UsageCategoryEnum MarketplaceFacebookOfflineConversions = new UsageCategoryEnum("marketplace-facebook-offline-conversions"); public static readonly UsageCategoryEnum MarketplaceGoogleSpeechToText = new UsageCategoryEnum("marketplace-google-speech-to-text"); public static readonly UsageCategoryEnum MarketplaceIbmWatsonMessageInsights = new UsageCategoryEnum("marketplace-ibm-watson-message-insights"); public static readonly UsageCategoryEnum MarketplaceIbmWatsonMessageSentiment = new UsageCategoryEnum("marketplace-ibm-watson-message-sentiment"); public static readonly UsageCategoryEnum MarketplaceIbmWatsonRecordingAnalysis = new UsageCategoryEnum("marketplace-ibm-watson-recording-analysis"); public static readonly UsageCategoryEnum MarketplaceIbmWatsonToneAnalyzer = new UsageCategoryEnum("marketplace-ibm-watson-tone-analyzer"); public static readonly UsageCategoryEnum MarketplaceIcehookSystemsScout = new UsageCategoryEnum("marketplace-icehook-systems-scout"); public static readonly UsageCategoryEnum MarketplaceInfogroupDataaxleBizinfo = new UsageCategoryEnum("marketplace-infogroup-dataaxle-bizinfo"); public static readonly UsageCategoryEnum MarketplaceKeenIoContactCenterAnalytics = new UsageCategoryEnum("marketplace-keen-io-contact-center-analytics"); public static readonly UsageCategoryEnum MarketplaceMarchexCleancall = new UsageCategoryEnum("marketplace-marchex-cleancall"); public static readonly UsageCategoryEnum MarketplaceMarchexSentimentAnalysisForSms = new UsageCategoryEnum("marketplace-marchex-sentiment-analysis-for-sms"); public static readonly UsageCategoryEnum MarketplaceMarketplaceNextcallerSocialId = new UsageCategoryEnum("marketplace-marketplace-nextcaller-social-id"); public static readonly UsageCategoryEnum MarketplaceMobileCommonsOptOutClassifier = new UsageCategoryEnum("marketplace-mobile-commons-opt-out-classifier"); public static readonly UsageCategoryEnum MarketplaceNexiwaveVoicemailToText = new UsageCategoryEnum("marketplace-nexiwave-voicemail-to-text"); public static readonly UsageCategoryEnum MarketplaceNextcallerAdvancedCallerIdentification = new UsageCategoryEnum("marketplace-nextcaller-advanced-caller-identification"); public static readonly UsageCategoryEnum MarketplaceNomoroboSpamScore = new UsageCategoryEnum("marketplace-nomorobo-spam-score"); public static readonly UsageCategoryEnum MarketplacePayfoneTcpaCompliance = new UsageCategoryEnum("marketplace-payfone-tcpa-compliance"); public static readonly UsageCategoryEnum MarketplaceRemeetingAutomaticSpeechRecognition = new UsageCategoryEnum("marketplace-remeeting-automatic-speech-recognition"); public static readonly UsageCategoryEnum MarketplaceTcpaDefenseSolutionsBlacklistFeed = new UsageCategoryEnum("marketplace-tcpa-defense-solutions-blacklist-feed"); public static readonly UsageCategoryEnum MarketplaceTeloOpencnam = new UsageCategoryEnum("marketplace-telo-opencnam"); public static readonly UsageCategoryEnum MarketplaceTruecnamTrueSpam = new UsageCategoryEnum("marketplace-truecnam-true-spam"); public static readonly UsageCategoryEnum MarketplaceTwilioCallerNameLookupUs = new UsageCategoryEnum("marketplace-twilio-caller-name-lookup-us"); public static readonly UsageCategoryEnum MarketplaceTwilioCarrierInformationLookup = new UsageCategoryEnum("marketplace-twilio-carrier-information-lookup"); public static readonly UsageCategoryEnum MarketplaceVoicebasePci = new UsageCategoryEnum("marketplace-voicebase-pci"); public static readonly UsageCategoryEnum MarketplaceVoicebaseTranscription = new UsageCategoryEnum("marketplace-voicebase-transcription"); public static readonly UsageCategoryEnum MarketplaceVoicebaseTranscriptionCustomVocabulary = new UsageCategoryEnum("marketplace-voicebase-transcription-custom-vocabulary"); public static readonly UsageCategoryEnum MarketplaceWhitepagesProCallerIdentification = new UsageCategoryEnum("marketplace-whitepages-pro-caller-identification"); public static readonly UsageCategoryEnum MarketplaceWhitepagesProPhoneIntelligence = new UsageCategoryEnum("marketplace-whitepages-pro-phone-intelligence"); public static readonly UsageCategoryEnum MarketplaceWhitepagesProPhoneReputation = new UsageCategoryEnum("marketplace-whitepages-pro-phone-reputation"); public static readonly UsageCategoryEnum MarketplaceWolfarmSpokenResults = new UsageCategoryEnum("marketplace-wolfarm-spoken-results"); public static readonly UsageCategoryEnum MarketplaceWolframShortAnswer = new UsageCategoryEnum("marketplace-wolfram-short-answer"); public static readonly UsageCategoryEnum MarketplaceYticaContactCenterReportingAnalytics = new UsageCategoryEnum("marketplace-ytica-contact-center-reporting-analytics"); public static readonly UsageCategoryEnum Mediastorage = new UsageCategoryEnum("mediastorage"); public static readonly UsageCategoryEnum Mms = new UsageCategoryEnum("mms"); public static readonly UsageCategoryEnum MmsInbound = new UsageCategoryEnum("mms-inbound"); public static readonly UsageCategoryEnum MmsInboundLongcode = new UsageCategoryEnum("mms-inbound-longcode"); public static readonly UsageCategoryEnum MmsInboundShortcode = new UsageCategoryEnum("mms-inbound-shortcode"); public static readonly UsageCategoryEnum MmsMessagesCarrierfees = new UsageCategoryEnum("mms-messages-carrierfees"); public static readonly UsageCategoryEnum MmsOutbound = new UsageCategoryEnum("mms-outbound"); public static readonly UsageCategoryEnum MmsOutboundLongcode = new UsageCategoryEnum("mms-outbound-longcode"); public static readonly UsageCategoryEnum MmsOutboundShortcode = new UsageCategoryEnum("mms-outbound-shortcode"); public static readonly UsageCategoryEnum MonitorReads = new UsageCategoryEnum("monitor-reads"); public static readonly UsageCategoryEnum MonitorStorage = new UsageCategoryEnum("monitor-storage"); public static readonly UsageCategoryEnum MonitorWrites = new UsageCategoryEnum("monitor-writes"); public static readonly UsageCategoryEnum Notify = new UsageCategoryEnum("notify"); public static readonly UsageCategoryEnum NotifyActionsAttempts = new UsageCategoryEnum("notify-actions-attempts"); public static readonly UsageCategoryEnum NotifyChannels = new UsageCategoryEnum("notify-channels"); public static readonly UsageCategoryEnum NumberFormatLookups = new UsageCategoryEnum("number-format-lookups"); public static readonly UsageCategoryEnum Pchat = new UsageCategoryEnum("pchat"); public static readonly UsageCategoryEnum PchatUsers = new UsageCategoryEnum("pchat-users"); public static readonly UsageCategoryEnum PeerToPeerRoomsParticipantMinutes = new UsageCategoryEnum("peer-to-peer-rooms-participant-minutes"); public static readonly UsageCategoryEnum Pfax = new UsageCategoryEnum("pfax"); public static readonly UsageCategoryEnum PfaxMinutes = new UsageCategoryEnum("pfax-minutes"); public static readonly UsageCategoryEnum PfaxMinutesInbound = new UsageCategoryEnum("pfax-minutes-inbound"); public static readonly UsageCategoryEnum PfaxMinutesOutbound = new UsageCategoryEnum("pfax-minutes-outbound"); public static readonly UsageCategoryEnum PfaxPages = new UsageCategoryEnum("pfax-pages"); public static readonly UsageCategoryEnum Phonenumbers = new UsageCategoryEnum("phonenumbers"); public static readonly UsageCategoryEnum PhonenumbersCps = new UsageCategoryEnum("phonenumbers-cps"); public static readonly UsageCategoryEnum PhonenumbersEmergency = new UsageCategoryEnum("phonenumbers-emergency"); public static readonly UsageCategoryEnum PhonenumbersLocal = new UsageCategoryEnum("phonenumbers-local"); public static readonly UsageCategoryEnum PhonenumbersMobile = new UsageCategoryEnum("phonenumbers-mobile"); public static readonly UsageCategoryEnum PhonenumbersSetups = new UsageCategoryEnum("phonenumbers-setups"); public static readonly UsageCategoryEnum PhonenumbersTollfree = new UsageCategoryEnum("phonenumbers-tollfree"); public static readonly UsageCategoryEnum Premiumsupport = new UsageCategoryEnum("premiumsupport"); public static readonly UsageCategoryEnum Proxy = new UsageCategoryEnum("proxy"); public static readonly UsageCategoryEnum ProxyActiveSessions = new UsageCategoryEnum("proxy-active-sessions"); public static readonly UsageCategoryEnum Pstnconnectivity = new UsageCategoryEnum("pstnconnectivity"); public static readonly UsageCategoryEnum Pv = new UsageCategoryEnum("pv"); public static readonly UsageCategoryEnum PvCompositionMediaDownloaded = new UsageCategoryEnum("pv-composition-media-downloaded"); public static readonly UsageCategoryEnum PvCompositionMediaEncrypted = new UsageCategoryEnum("pv-composition-media-encrypted"); public static readonly UsageCategoryEnum PvCompositionMediaStored = new UsageCategoryEnum("pv-composition-media-stored"); public static readonly UsageCategoryEnum PvCompositionMinutes = new UsageCategoryEnum("pv-composition-minutes"); public static readonly UsageCategoryEnum PvRecordingCompositions = new UsageCategoryEnum("pv-recording-compositions"); public static readonly UsageCategoryEnum PvRoomParticipants = new UsageCategoryEnum("pv-room-participants"); public static readonly UsageCategoryEnum PvRoomParticipantsAu1 = new UsageCategoryEnum("pv-room-participants-au1"); public static readonly UsageCategoryEnum PvRoomParticipantsBr1 = new UsageCategoryEnum("pv-room-participants-br1"); public static readonly UsageCategoryEnum PvRoomParticipantsIe1 = new UsageCategoryEnum("pv-room-participants-ie1"); public static readonly UsageCategoryEnum PvRoomParticipantsJp1 = new UsageCategoryEnum("pv-room-participants-jp1"); public static readonly UsageCategoryEnum PvRoomParticipantsSg1 = new UsageCategoryEnum("pv-room-participants-sg1"); public static readonly UsageCategoryEnum PvRoomParticipantsUs1 = new UsageCategoryEnum("pv-room-participants-us1"); public static readonly UsageCategoryEnum PvRoomParticipantsUs2 = new UsageCategoryEnum("pv-room-participants-us2"); public static readonly UsageCategoryEnum PvRooms = new UsageCategoryEnum("pv-rooms"); public static readonly UsageCategoryEnum PvSipEndpointRegistrations = new UsageCategoryEnum("pv-sip-endpoint-registrations"); public static readonly UsageCategoryEnum Recordings = new UsageCategoryEnum("recordings"); public static readonly UsageCategoryEnum Recordingstorage = new UsageCategoryEnum("recordingstorage"); public static readonly UsageCategoryEnum RoomsGroupBandwidth = new UsageCategoryEnum("rooms-group-bandwidth"); public static readonly UsageCategoryEnum RoomsGroupMinutes = new UsageCategoryEnum("rooms-group-minutes"); public static readonly UsageCategoryEnum RoomsPeerToPeerMinutes = new UsageCategoryEnum("rooms-peer-to-peer-minutes"); public static readonly UsageCategoryEnum Shortcodes = new UsageCategoryEnum("shortcodes"); public static readonly UsageCategoryEnum ShortcodesCustomerowned = new UsageCategoryEnum("shortcodes-customerowned"); public static readonly UsageCategoryEnum ShortcodesMmsEnablement = new UsageCategoryEnum("shortcodes-mms-enablement"); public static readonly UsageCategoryEnum ShortcodesMps = new UsageCategoryEnum("shortcodes-mps"); public static readonly UsageCategoryEnum ShortcodesRandom = new UsageCategoryEnum("shortcodes-random"); public static readonly UsageCategoryEnum ShortcodesUk = new UsageCategoryEnum("shortcodes-uk"); public static readonly UsageCategoryEnum ShortcodesVanity = new UsageCategoryEnum("shortcodes-vanity"); public static readonly UsageCategoryEnum SmallGroupRooms = new UsageCategoryEnum("small-group-rooms"); public static readonly UsageCategoryEnum SmallGroupRoomsDataTrack = new UsageCategoryEnum("small-group-rooms-data-track"); public static readonly UsageCategoryEnum SmallGroupRoomsParticipantMinutes = new UsageCategoryEnum("small-group-rooms-participant-minutes"); public static readonly UsageCategoryEnum Sms = new UsageCategoryEnum("sms"); public static readonly UsageCategoryEnum SmsInbound = new UsageCategoryEnum("sms-inbound"); public static readonly UsageCategoryEnum SmsInboundLongcode = new UsageCategoryEnum("sms-inbound-longcode"); public static readonly UsageCategoryEnum SmsInboundShortcode = new UsageCategoryEnum("sms-inbound-shortcode"); public static readonly UsageCategoryEnum SmsMessagesCarrierfees = new UsageCategoryEnum("sms-messages-carrierfees"); public static readonly UsageCategoryEnum SmsMessagesFeatures = new UsageCategoryEnum("sms-messages-features"); public static readonly UsageCategoryEnum SmsMessagesFeaturesSenderid = new UsageCategoryEnum("sms-messages-features-senderid"); public static readonly UsageCategoryEnum SmsOutbound = new UsageCategoryEnum("sms-outbound"); public static readonly UsageCategoryEnum SmsOutboundContentInspection = new UsageCategoryEnum("sms-outbound-content-inspection"); public static readonly UsageCategoryEnum SmsOutboundLongcode = new UsageCategoryEnum("sms-outbound-longcode"); public static readonly UsageCategoryEnum SmsOutboundShortcode = new UsageCategoryEnum("sms-outbound-shortcode"); public static readonly UsageCategoryEnum SpeechRecognition = new UsageCategoryEnum("speech-recognition"); public static readonly UsageCategoryEnum StudioEngagements = new UsageCategoryEnum("studio-engagements"); public static readonly UsageCategoryEnum Sync = new UsageCategoryEnum("sync"); public static readonly UsageCategoryEnum SyncActions = new UsageCategoryEnum("sync-actions"); public static readonly UsageCategoryEnum SyncEndpointHours = new UsageCategoryEnum("sync-endpoint-hours"); public static readonly UsageCategoryEnum SyncEndpointHoursAboveDailyCap = new UsageCategoryEnum("sync-endpoint-hours-above-daily-cap"); public static readonly UsageCategoryEnum TaskrouterTasks = new UsageCategoryEnum("taskrouter-tasks"); public static readonly UsageCategoryEnum Totalprice = new UsageCategoryEnum("totalprice"); public static readonly UsageCategoryEnum Transcriptions = new UsageCategoryEnum("transcriptions"); public static readonly UsageCategoryEnum TrunkingCps = new UsageCategoryEnum("trunking-cps"); public static readonly UsageCategoryEnum TrunkingEmergencyCalls = new UsageCategoryEnum("trunking-emergency-calls"); public static readonly UsageCategoryEnum TrunkingOrigination = new UsageCategoryEnum("trunking-origination"); public static readonly UsageCategoryEnum TrunkingOriginationLocal = new UsageCategoryEnum("trunking-origination-local"); public static readonly UsageCategoryEnum TrunkingOriginationMobile = new UsageCategoryEnum("trunking-origination-mobile"); public static readonly UsageCategoryEnum TrunkingOriginationTollfree = new UsageCategoryEnum("trunking-origination-tollfree"); public static readonly UsageCategoryEnum TrunkingRecordings = new UsageCategoryEnum("trunking-recordings"); public static readonly UsageCategoryEnum TrunkingSecure = new UsageCategoryEnum("trunking-secure"); public static readonly UsageCategoryEnum TrunkingTermination = new UsageCategoryEnum("trunking-termination"); public static readonly UsageCategoryEnum Turnmegabytes = new UsageCategoryEnum("turnmegabytes"); public static readonly UsageCategoryEnum TurnmegabytesAustralia = new UsageCategoryEnum("turnmegabytes-australia"); public static readonly UsageCategoryEnum TurnmegabytesBrasil = new UsageCategoryEnum("turnmegabytes-brasil"); public static readonly UsageCategoryEnum TurnmegabytesGermany = new UsageCategoryEnum("turnmegabytes-germany"); public static readonly UsageCategoryEnum TurnmegabytesIndia = new UsageCategoryEnum("turnmegabytes-india"); public static readonly UsageCategoryEnum TurnmegabytesIreland = new UsageCategoryEnum("turnmegabytes-ireland"); public static readonly UsageCategoryEnum TurnmegabytesJapan = new UsageCategoryEnum("turnmegabytes-japan"); public static readonly UsageCategoryEnum TurnmegabytesSingapore = new UsageCategoryEnum("turnmegabytes-singapore"); public static readonly UsageCategoryEnum TurnmegabytesUseast = new UsageCategoryEnum("turnmegabytes-useast"); public static readonly UsageCategoryEnum TurnmegabytesUswest = new UsageCategoryEnum("turnmegabytes-uswest"); public static readonly UsageCategoryEnum TwilioInterconnect = new UsageCategoryEnum("twilio-interconnect"); public static readonly UsageCategoryEnum VerifyPush = new UsageCategoryEnum("verify-push"); public static readonly UsageCategoryEnum VideoRecordings = new UsageCategoryEnum("video-recordings"); public static readonly UsageCategoryEnum VoiceInsights = new UsageCategoryEnum("voice-insights"); public static readonly UsageCategoryEnum VoiceInsightsClientInsightsOnDemandMinute = new UsageCategoryEnum("voice-insights-client-insights-on-demand-minute"); public static readonly UsageCategoryEnum VoiceInsightsPtsnInsightsOnDemandMinute = new UsageCategoryEnum("voice-insights-ptsn-insights-on-demand-minute"); public static readonly UsageCategoryEnum VoiceInsightsSipInterfaceInsightsOnDemandMinute = new UsageCategoryEnum("voice-insights-sip-interface-insights-on-demand-minute"); public static readonly UsageCategoryEnum VoiceInsightsSipTrunkingInsightsOnDemandMinute = new UsageCategoryEnum("voice-insights-sip-trunking-insights-on-demand-minute"); public static readonly UsageCategoryEnum Wireless = new UsageCategoryEnum("wireless"); public static readonly UsageCategoryEnum WirelessOrders = new UsageCategoryEnum("wireless-orders"); public static readonly UsageCategoryEnum WirelessOrdersArtwork = new UsageCategoryEnum("wireless-orders-artwork"); public static readonly UsageCategoryEnum WirelessOrdersBulk = new UsageCategoryEnum("wireless-orders-bulk"); public static readonly UsageCategoryEnum WirelessOrdersEsim = new UsageCategoryEnum("wireless-orders-esim"); public static readonly UsageCategoryEnum WirelessOrdersStarter = new UsageCategoryEnum("wireless-orders-starter"); public static readonly UsageCategoryEnum WirelessUsage = new UsageCategoryEnum("wireless-usage"); public static readonly UsageCategoryEnum WirelessUsageCommands = new UsageCategoryEnum("wireless-usage-commands"); public static readonly UsageCategoryEnum WirelessUsageCommandsAfrica = new UsageCategoryEnum("wireless-usage-commands-africa"); public static readonly UsageCategoryEnum WirelessUsageCommandsAsia = new UsageCategoryEnum("wireless-usage-commands-asia"); public static readonly UsageCategoryEnum WirelessUsageCommandsCentralandsouthamerica = new UsageCategoryEnum("wireless-usage-commands-centralandsouthamerica"); public static readonly UsageCategoryEnum WirelessUsageCommandsEurope = new UsageCategoryEnum("wireless-usage-commands-europe"); public static readonly UsageCategoryEnum WirelessUsageCommandsHome = new UsageCategoryEnum("wireless-usage-commands-home"); public static readonly UsageCategoryEnum WirelessUsageCommandsNorthamerica = new UsageCategoryEnum("wireless-usage-commands-northamerica"); public static readonly UsageCategoryEnum WirelessUsageCommandsOceania = new UsageCategoryEnum("wireless-usage-commands-oceania"); public static readonly UsageCategoryEnum WirelessUsageCommandsRoaming = new UsageCategoryEnum("wireless-usage-commands-roaming"); public static readonly UsageCategoryEnum WirelessUsageData = new UsageCategoryEnum("wireless-usage-data"); public static readonly UsageCategoryEnum WirelessUsageDataAfrica = new UsageCategoryEnum("wireless-usage-data-africa"); public static readonly UsageCategoryEnum WirelessUsageDataAsia = new UsageCategoryEnum("wireless-usage-data-asia"); public static readonly UsageCategoryEnum WirelessUsageDataCentralandsouthamerica = new UsageCategoryEnum("wireless-usage-data-centralandsouthamerica"); public static readonly UsageCategoryEnum WirelessUsageDataCustomAdditionalmb = new UsageCategoryEnum("wireless-usage-data-custom-additionalmb"); public static readonly UsageCategoryEnum WirelessUsageDataCustomFirst5Mb = new UsageCategoryEnum("wireless-usage-data-custom-first5mb"); public static readonly UsageCategoryEnum WirelessUsageDataDomesticRoaming = new UsageCategoryEnum("wireless-usage-data-domestic-roaming"); public static readonly UsageCategoryEnum WirelessUsageDataEurope = new UsageCategoryEnum("wireless-usage-data-europe"); public static readonly UsageCategoryEnum WirelessUsageDataIndividualAdditionalgb = new UsageCategoryEnum("wireless-usage-data-individual-additionalgb"); public static readonly UsageCategoryEnum WirelessUsageDataIndividualFirstgb = new UsageCategoryEnum("wireless-usage-data-individual-firstgb"); public static readonly UsageCategoryEnum WirelessUsageDataInternationalRoamingCanada = new UsageCategoryEnum("wireless-usage-data-international-roaming-canada"); public static readonly UsageCategoryEnum WirelessUsageDataInternationalRoamingIndia = new UsageCategoryEnum("wireless-usage-data-international-roaming-india"); public static readonly UsageCategoryEnum WirelessUsageDataInternationalRoamingMexico = new UsageCategoryEnum("wireless-usage-data-international-roaming-mexico"); public static readonly UsageCategoryEnum WirelessUsageDataNorthamerica = new UsageCategoryEnum("wireless-usage-data-northamerica"); public static readonly UsageCategoryEnum WirelessUsageDataOceania = new UsageCategoryEnum("wireless-usage-data-oceania"); public static readonly UsageCategoryEnum WirelessUsageDataPooled = new UsageCategoryEnum("wireless-usage-data-pooled"); public static readonly UsageCategoryEnum WirelessUsageDataPooledDownlink = new UsageCategoryEnum("wireless-usage-data-pooled-downlink"); public static readonly UsageCategoryEnum WirelessUsageDataPooledUplink = new UsageCategoryEnum("wireless-usage-data-pooled-uplink"); public static readonly UsageCategoryEnum WirelessUsageMrc = new UsageCategoryEnum("wireless-usage-mrc"); public static readonly UsageCategoryEnum WirelessUsageMrcCustom = new UsageCategoryEnum("wireless-usage-mrc-custom"); public static readonly UsageCategoryEnum WirelessUsageMrcIndividual = new UsageCategoryEnum("wireless-usage-mrc-individual"); public static readonly UsageCategoryEnum WirelessUsageMrcPooled = new UsageCategoryEnum("wireless-usage-mrc-pooled"); public static readonly UsageCategoryEnum WirelessUsageMrcSuspended = new UsageCategoryEnum("wireless-usage-mrc-suspended"); public static readonly UsageCategoryEnum WirelessUsageSms = new UsageCategoryEnum("wireless-usage-sms"); public static readonly UsageCategoryEnum WirelessUsageVoice = new UsageCategoryEnum("wireless-usage-voice"); } public sealed class RecurringEnum : StringEnum { private RecurringEnum(string value) : base(value) {} public RecurringEnum() {} public static implicit operator RecurringEnum(string value) { return new RecurringEnum(value); } public static readonly RecurringEnum Daily = new RecurringEnum("daily"); public static readonly RecurringEnum Monthly = new RecurringEnum("monthly"); public static readonly RecurringEnum Yearly = new RecurringEnum("yearly"); public static readonly RecurringEnum Alltime = new RecurringEnum("alltime"); } public sealed class TriggerFieldEnum : StringEnum { private TriggerFieldEnum(string value) : base(value) {} public TriggerFieldEnum() {} public static implicit operator TriggerFieldEnum(string value) { return new TriggerFieldEnum(value); } public static readonly TriggerFieldEnum Count = new TriggerFieldEnum("count"); public static readonly TriggerFieldEnum Usage = new TriggerFieldEnum("usage"); public static readonly TriggerFieldEnum Price = new TriggerFieldEnum("price"); } private static Request BuildFetchRequest(FetchTriggerOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Usage/Triggers/" + options.PathSid + ".json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch and instance of a usage-trigger /// </summary> /// <param name="options"> Fetch Trigger parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Trigger </returns> public static TriggerResource Fetch(FetchTriggerOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch and instance of a usage-trigger /// </summary> /// <param name="options"> Fetch Trigger parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Trigger </returns> public static async System.Threading.Tasks.Task<TriggerResource> FetchAsync(FetchTriggerOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch and instance of a usage-trigger /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Trigger </returns> public static TriggerResource Fetch(string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new FetchTriggerOptions(pathSid){PathAccountSid = pathAccountSid}; return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch and instance of a usage-trigger /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Trigger </returns> public static async System.Threading.Tasks.Task<TriggerResource> FetchAsync(string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new FetchTriggerOptions(pathSid){PathAccountSid = pathAccountSid}; return await FetchAsync(options, client); } #endif private static Request BuildUpdateRequest(UpdateTriggerOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Usage/Triggers/" + options.PathSid + ".json", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Update an instance of a usage trigger /// </summary> /// <param name="options"> Update Trigger parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Trigger </returns> public static TriggerResource Update(UpdateTriggerOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Update an instance of a usage trigger /// </summary> /// <param name="options"> Update Trigger parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Trigger </returns> public static async System.Threading.Tasks.Task<TriggerResource> UpdateAsync(UpdateTriggerOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Update an instance of a usage trigger /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resources to update </param> /// <param name="callbackMethod"> The HTTP method to use to call callback_url </param> /// <param name="callbackUrl"> The URL we call when the trigger fires </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Trigger </returns> public static TriggerResource Update(string pathSid, string pathAccountSid = null, Twilio.Http.HttpMethod callbackMethod = null, Uri callbackUrl = null, string friendlyName = null, ITwilioRestClient client = null) { var options = new UpdateTriggerOptions(pathSid){PathAccountSid = pathAccountSid, CallbackMethod = callbackMethod, CallbackUrl = callbackUrl, FriendlyName = friendlyName}; return Update(options, client); } #if !NET35 /// <summary> /// Update an instance of a usage trigger /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resources to update </param> /// <param name="callbackMethod"> The HTTP method to use to call callback_url </param> /// <param name="callbackUrl"> The URL we call when the trigger fires </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Trigger </returns> public static async System.Threading.Tasks.Task<TriggerResource> UpdateAsync(string pathSid, string pathAccountSid = null, Twilio.Http.HttpMethod callbackMethod = null, Uri callbackUrl = null, string friendlyName = null, ITwilioRestClient client = null) { var options = new UpdateTriggerOptions(pathSid){PathAccountSid = pathAccountSid, CallbackMethod = callbackMethod, CallbackUrl = callbackUrl, FriendlyName = friendlyName}; return await UpdateAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteTriggerOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Usage/Triggers/" + options.PathSid + ".json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// delete /// </summary> /// <param name="options"> Delete Trigger parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Trigger </returns> public static bool Delete(DeleteTriggerOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="options"> Delete Trigger parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Trigger </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteTriggerOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// delete /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resources to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Trigger </returns> public static bool Delete(string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new DeleteTriggerOptions(pathSid){PathAccountSid = pathAccountSid}; return Delete(options, client); } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resources to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Trigger </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new DeleteTriggerOptions(pathSid){PathAccountSid = pathAccountSid}; return await DeleteAsync(options, client); } #endif private static Request BuildCreateRequest(CreateTriggerOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Usage/Triggers.json", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Create a new UsageTrigger /// </summary> /// <param name="options"> Create Trigger parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Trigger </returns> public static TriggerResource Create(CreateTriggerOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Create a new UsageTrigger /// </summary> /// <param name="options"> Create Trigger parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Trigger </returns> public static async System.Threading.Tasks.Task<TriggerResource> CreateAsync(CreateTriggerOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Create a new UsageTrigger /// </summary> /// <param name="callbackUrl"> The URL we call when the trigger fires </param> /// <param name="triggerValue"> The usage value at which the trigger should fire </param> /// <param name="usageCategory"> The usage category the trigger watches </param> /// <param name="pathAccountSid"> The SID of the Account that will create the resource </param> /// <param name="callbackMethod"> The HTTP method to use to call callback_url </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="recurring"> The frequency of a recurring UsageTrigger </param> /// <param name="triggerBy"> The field in the UsageRecord resource that fires the trigger </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Trigger </returns> public static TriggerResource Create(Uri callbackUrl, string triggerValue, TriggerResource.UsageCategoryEnum usageCategory, string pathAccountSid = null, Twilio.Http.HttpMethod callbackMethod = null, string friendlyName = null, TriggerResource.RecurringEnum recurring = null, TriggerResource.TriggerFieldEnum triggerBy = null, ITwilioRestClient client = null) { var options = new CreateTriggerOptions(callbackUrl, triggerValue, usageCategory){PathAccountSid = pathAccountSid, CallbackMethod = callbackMethod, FriendlyName = friendlyName, Recurring = recurring, TriggerBy = triggerBy}; return Create(options, client); } #if !NET35 /// <summary> /// Create a new UsageTrigger /// </summary> /// <param name="callbackUrl"> The URL we call when the trigger fires </param> /// <param name="triggerValue"> The usage value at which the trigger should fire </param> /// <param name="usageCategory"> The usage category the trigger watches </param> /// <param name="pathAccountSid"> The SID of the Account that will create the resource </param> /// <param name="callbackMethod"> The HTTP method to use to call callback_url </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="recurring"> The frequency of a recurring UsageTrigger </param> /// <param name="triggerBy"> The field in the UsageRecord resource that fires the trigger </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Trigger </returns> public static async System.Threading.Tasks.Task<TriggerResource> CreateAsync(Uri callbackUrl, string triggerValue, TriggerResource.UsageCategoryEnum usageCategory, string pathAccountSid = null, Twilio.Http.HttpMethod callbackMethod = null, string friendlyName = null, TriggerResource.RecurringEnum recurring = null, TriggerResource.TriggerFieldEnum triggerBy = null, ITwilioRestClient client = null) { var options = new CreateTriggerOptions(callbackUrl, triggerValue, usageCategory){PathAccountSid = pathAccountSid, CallbackMethod = callbackMethod, FriendlyName = friendlyName, Recurring = recurring, TriggerBy = triggerBy}; return await CreateAsync(options, client); } #endif private static Request BuildReadRequest(ReadTriggerOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Usage/Triggers.json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of usage-triggers belonging to the account used to make the request /// </summary> /// <param name="options"> Read Trigger parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Trigger </returns> public static ResourceSet<TriggerResource> Read(ReadTriggerOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<TriggerResource>.FromJson("usage_triggers", response.Content); return new ResourceSet<TriggerResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of usage-triggers belonging to the account used to make the request /// </summary> /// <param name="options"> Read Trigger parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Trigger </returns> public static async System.Threading.Tasks.Task<ResourceSet<TriggerResource>> ReadAsync(ReadTriggerOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<TriggerResource>.FromJson("usage_triggers", response.Content); return new ResourceSet<TriggerResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of usage-triggers belonging to the account used to make the request /// </summary> /// <param name="pathAccountSid"> The SID of the Account that created the resources to read </param> /// <param name="recurring"> The frequency of recurring UsageTriggers to read </param> /// <param name="triggerBy"> The trigger field of the UsageTriggers to read </param> /// <param name="usageCategory"> The usage category of the UsageTriggers to read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Trigger </returns> public static ResourceSet<TriggerResource> Read(string pathAccountSid = null, TriggerResource.RecurringEnum recurring = null, TriggerResource.TriggerFieldEnum triggerBy = null, TriggerResource.UsageCategoryEnum usageCategory = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadTriggerOptions(){PathAccountSid = pathAccountSid, Recurring = recurring, TriggerBy = triggerBy, UsageCategory = usageCategory, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of usage-triggers belonging to the account used to make the request /// </summary> /// <param name="pathAccountSid"> The SID of the Account that created the resources to read </param> /// <param name="recurring"> The frequency of recurring UsageTriggers to read </param> /// <param name="triggerBy"> The trigger field of the UsageTriggers to read </param> /// <param name="usageCategory"> The usage category of the UsageTriggers to read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Trigger </returns> public static async System.Threading.Tasks.Task<ResourceSet<TriggerResource>> ReadAsync(string pathAccountSid = null, TriggerResource.RecurringEnum recurring = null, TriggerResource.TriggerFieldEnum triggerBy = null, TriggerResource.UsageCategoryEnum usageCategory = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadTriggerOptions(){PathAccountSid = pathAccountSid, Recurring = recurring, TriggerBy = triggerBy, UsageCategory = usageCategory, PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<TriggerResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<TriggerResource>.FromJson("usage_triggers", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<TriggerResource> NextPage(Page<TriggerResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Api) ); var response = client.Request(request); return Page<TriggerResource>.FromJson("usage_triggers", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<TriggerResource> PreviousPage(Page<TriggerResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Api) ); var response = client.Request(request); return Page<TriggerResource>.FromJson("usage_triggers", response.Content); } /// <summary> /// Converts a JSON string into a TriggerResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> TriggerResource object represented by the provided JSON </returns> public static TriggerResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<TriggerResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The SID of the Account that this trigger monitors /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The API version used to create the resource /// </summary> [JsonProperty("api_version")] public string ApiVersion { get; private set; } /// <summary> /// The HTTP method we use to call callback_url /// </summary> [JsonProperty("callback_method")] [JsonConverter(typeof(HttpMethodConverter))] public Twilio.Http.HttpMethod CallbackMethod { get; private set; } /// <summary> /// he URL we call when the trigger fires /// </summary> [JsonProperty("callback_url")] public Uri CallbackUrl { get; private set; } /// <summary> /// The current value of the field the trigger is watching /// </summary> [JsonProperty("current_value")] public string CurrentValue { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT that the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT that the trigger was last fired /// </summary> [JsonProperty("date_fired")] public DateTime? DateFired { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT that the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The string that you assigned to describe the trigger /// </summary> [JsonProperty("friendly_name")] public string FriendlyName { get; private set; } /// <summary> /// The frequency of a recurring UsageTrigger /// </summary> [JsonProperty("recurring")] [JsonConverter(typeof(StringEnumConverter))] public TriggerResource.RecurringEnum Recurring { get; private set; } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The field in the UsageRecord resource that fires the trigger /// </summary> [JsonProperty("trigger_by")] [JsonConverter(typeof(StringEnumConverter))] public TriggerResource.TriggerFieldEnum TriggerBy { get; private set; } /// <summary> /// The value at which the trigger will fire /// </summary> [JsonProperty("trigger_value")] public string TriggerValue { get; private set; } /// <summary> /// The URI of the resource, relative to `https://api.twilio.com` /// </summary> [JsonProperty("uri")] public string Uri { get; private set; } /// <summary> /// The usage category the trigger watches /// </summary> [JsonProperty("usage_category")] [JsonConverter(typeof(StringEnumConverter))] public TriggerResource.UsageCategoryEnum UsageCategory { get; private set; } /// <summary> /// The URI of the UsageRecord resource this trigger watches /// </summary> [JsonProperty("usage_record_uri")] public string UsageRecordUri { get; private set; } private TriggerResource() { } } }
// Copyright 2014 Adrian Chlubek. This file is part of GTA Multiplayer IV project. // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. using System.Collections.Generic; using System.Linq; namespace MIVSDK { public static class ModelDictionary { private static Dictionary<string, uint> ped_models_hashes, vehicle_hashes; public static Dictionary<string, uint> getAllPedModels() { if (ped_models_hashes == null) load(); return ped_models_hashes; } public static Dictionary<string, uint> getAllVehicles() { if (vehicle_hashes == null) load(); return vehicle_hashes; } public static string getPedModelById(uint id) { if (ped_models_hashes == null) load(); return ped_models_hashes.Where(a => a.Value == id).First().Key; } public static uint getPedModelByName(string name) { if (ped_models_hashes == null) load(); return ped_models_hashes.First(a => a.Key == name.ToUpper()).Value; } public static string getVehicleById(uint id) { if (vehicle_hashes == null) load(); return vehicle_hashes.Where(a => a.Value == id).First().Key; } public static uint getVehicleByName(string name) { if (vehicle_hashes == null) load(); return vehicle_hashes.First(a => a.Key == name.ToUpper()).Value; } private static void load() { ped_models_hashes = new Dictionary<string, uint>(); ped_models_hashes.Add("IG_ANNA", 0x6E7BF45F); ped_models_hashes.Add("IG_ANTHONY", 0x9DD666EE); ped_models_hashes.Add("IG_BADMAN", 0x5927A320); ped_models_hashes.Add("IG_BERNIE_CRANE", 0x596FB508); ped_models_hashes.Add("IG_BLEDAR", 0x6734C2C8); ped_models_hashes.Add("IG_BRIAN", 0x192BDD4A); ped_models_hashes.Add("IG_BRUCIE", 0x98E29920); ped_models_hashes.Add("IG_BULGARIN", 0x0E28247F); ped_models_hashes.Add("IG_CHARISE", 0x0548F609); ped_models_hashes.Add("IG_CHARLIEUC", 0xB0D18783); ped_models_hashes.Add("IG_CLARENCE", 0x500EC110); ped_models_hashes.Add("IG_DARDAN", 0x5786C78F); ped_models_hashes.Add("IG_DARKO", 0x1709B920); ped_models_hashes.Add("IG_DERRICK_MC", 0x45B445F9); ped_models_hashes.Add("IG_DMITRI", 0x0E27ECC1); ped_models_hashes.Add("IG_DWAYNE", 0xDB354C19); ped_models_hashes.Add("IG_EDDIELOW", 0xA09901F1); ped_models_hashes.Add("IG_FAUSTIN", 0x03691799); ped_models_hashes.Add("IG_FRANCIS_MC", 0x65F4D88D); ped_models_hashes.Add("IG_FRENCH_TOM", 0x54EABEE4); ped_models_hashes.Add("IG_GORDON", 0x7EED7363); ped_models_hashes.Add("IG_GRACIE", 0xEAAEA78E); ped_models_hashes.Add("IG_HOSSAN", 0x3A7556B2); ped_models_hashes.Add("IG_ILYENA", 0xCE3779DA); ped_models_hashes.Add("IG_ISAAC", 0xE369F2A6); ped_models_hashes.Add("IG_IVAN", 0x458B61F3); ped_models_hashes.Add("IG_JAY", 0x15BCAD23); ped_models_hashes.Add("IG_JASON", 0x0A2D8896); ped_models_hashes.Add("IG_JEFF", 0x17446345); ped_models_hashes.Add("IG_JIMMY", 0xEA28DB14); ped_models_hashes.Add("IG_JOHNNYBIKER", 0xC9AB7F1C); ped_models_hashes.Add("IG_KATEMC", 0xD1E17FCA); ped_models_hashes.Add("IG_KENNY", 0x3B574ABA); ped_models_hashes.Add("IG_LILJACOB", 0x58A1E271); ped_models_hashes.Add("IG_LILJACOBW", 0xB4008E4D); ped_models_hashes.Add("IG_LUCA", 0xD75A60C8); ped_models_hashes.Add("IG_LUIS", 0xE2A57E5E); ped_models_hashes.Add("IG_MALLORIE", 0xC1FE7952); ped_models_hashes.Add("IG_MAMC", 0xECC3FBA7); ped_models_hashes.Add("IG_MANNY", 0x5629F011); ped_models_hashes.Add("IG_MARNIE", 0x188232D0); ped_models_hashes.Add("IG_MEL", 0xCFE0FB92); ped_models_hashes.Add("IG_MICHAEL", 0x2BD27039); ped_models_hashes.Add("IG_MICHELLE", 0xBF9672F4); ped_models_hashes.Add("IG_MICKEY", 0xDA0D3182); ped_models_hashes.Add("IG_PACKIE_MC", 0x64C74D3B); ped_models_hashes.Add("IG_PATHOS", 0xF6237664); ped_models_hashes.Add("IG_PETROVIC", 0x8BE8B7F2); ped_models_hashes.Add("IG_PHIL_BELL", 0x932272CA); ped_models_hashes.Add("IG_PLAYBOY_X", 0x6AF081E8); ped_models_hashes.Add("IG_RAY_BOCCINO", 0x38E02AB6); ped_models_hashes.Add("IG_RICKY", 0xDCFE251C); ped_models_hashes.Add("IG_ROMAN", 0x89395FC9); ped_models_hashes.Add("IG_ROMANW", 0x2145C7A5); ped_models_hashes.Add("IG_SARAH", 0xFEF00775); ped_models_hashes.Add("IG_TUNA", 0x528AE104); ped_models_hashes.Add("IG_VINNY_SPAZ", 0xC380AE97); ped_models_hashes.Add("IG_VLAD", 0x356E1C42); ped_models_hashes.Add("CS_ANDREI", 0x3977107D); ped_models_hashes.Add("CS_ANGIE", 0xF866DC66); ped_models_hashes.Add("CS_BADMAN", 0xFC012F67); ped_models_hashes.Add("CS_BLEDAR", 0xA2DDDBA7); ped_models_hashes.Add("CS_BULGARIN", 0x009E4F3E); ped_models_hashes.Add("CS_BULGARINHENCH", 0x1F32DB93); ped_models_hashes.Add("CS_CIA", 0x4B13F8D4); ped_models_hashes.Add("CS_DARDAN", 0xF4386436); ped_models_hashes.Add("CS_DAVETHEMATE", 0x1A5B22F0); ped_models_hashes.Add("CS_DMITRI", 0x030B4624); ped_models_hashes.Add("CS_EDTHEMATE", 0xC74969B0); ped_models_hashes.Add("CS_FAUSTIN", 0xA776BDC7); ped_models_hashes.Add("CS_FRANCIS", 0x4AA2E9EA); ped_models_hashes.Add("CS_HOSSAN", 0x2B578C90); ped_models_hashes.Add("CS_ILYENA", 0x2EB3F295); ped_models_hashes.Add("CS_IVAN", 0x4A85C1C4); ped_models_hashes.Add("CS_JAY", 0x96E9F99A); ped_models_hashes.Add("CS_JIMMY_PEGORINO", 0x7055C230); ped_models_hashes.Add("CS_MEL", 0x298ACEC3); ped_models_hashes.Add("CS_MICHELLE", 0x70AEB9C8); ped_models_hashes.Add("CS_MICKEY", 0xA1DFB431); ped_models_hashes.Add("CS_OFFICIAL", 0x311DB819); ped_models_hashes.Add("CS_RAY_BOCCINO", 0xD09ECB11); ped_models_hashes.Add("CS_SERGEI", 0xDBAC6805); ped_models_hashes.Add("CS_VLAD", 0x7F5B9540); ped_models_hashes.Add("CS_WHIPPINGGIRL", 0x5A6C9C5F); ped_models_hashes.Add("CS_MANNY", 0xD0F8F893); ped_models_hashes.Add("CS_ANTHONY", 0x6B941ABA); ped_models_hashes.Add("CS_ASHLEY", 0x26C3D079); ped_models_hashes.Add("CS_ASSISTANT", 0x394C11AD); ped_models_hashes.Add("CS_CAPTAIN", 0xE6829281); ped_models_hashes.Add("CS_CHARLIEUC", 0xEC96EE3A); ped_models_hashes.Add("CS_DARKO", 0xC4B4204C); ped_models_hashes.Add("CS_DWAYNE", 0xFB9190AC); ped_models_hashes.Add("CS_ELI_JESTER", 0x3D47C135); ped_models_hashes.Add("CS_ELIZABETA", 0xAED416AF); ped_models_hashes.Add("CS_GAYTONY", 0x04F78844); ped_models_hashes.Add("CS_GERRYMC", 0x26DE3A8A); ped_models_hashes.Add("CS_GORDON", 0x49D3EAD3); ped_models_hashes.Add("CS_ISSAC", 0xB93A5686); ped_models_hashes.Add("CS_JOHNNYTHEBIKER", 0x2E009A8D); ped_models_hashes.Add("CS_JONGRAVELLI", 0xD7D47612); ped_models_hashes.Add("CS_JORGE", 0x5906B7A5); ped_models_hashes.Add("CS_KAT", 0x71A11E4C); ped_models_hashes.Add("CS_KILLER", 0xB4D0F581); ped_models_hashes.Add("CS_LUIS", 0x5E730218); ped_models_hashes.Add("CS_MAGICIAN", 0x1B508682); ped_models_hashes.Add("CS_MAMC", 0xA17C3253); ped_models_hashes.Add("CS_MELODY", 0xEA01EFDC); ped_models_hashes.Add("CS_MITCHCOP", 0xD8BA6C47); ped_models_hashes.Add("CS_MORI", 0x9B333E73); ped_models_hashes.Add("CS_PBXGIRL2", 0xE9C3C332); ped_models_hashes.Add("CS_PHILB", 0x5BEB1A2D); ped_models_hashes.Add("CS_PLAYBOYX", 0xE9F368C6); ped_models_hashes.Add("CS_PRIEST", 0x4D6DE57E); ped_models_hashes.Add("CS_RICKY", 0x88F35A20); ped_models_hashes.Add("CS_TOMMY", 0x626C3F77); ped_models_hashes.Add("CS_TRAMP", 0x553CBE07); ped_models_hashes.Add("CS_BRIAN", 0x2AF6831D); ped_models_hashes.Add("CS_CHARISE", 0x7AE0A064); ped_models_hashes.Add("CS_CLARENCE", 0xE7AC8418); ped_models_hashes.Add("CS_EDDIELOW", 0x6463855D); ped_models_hashes.Add("CS_GRACIE", 0x999B9B33); ped_models_hashes.Add("CS_JEFF", 0x17C32FB4); ped_models_hashes.Add("CS_MARNIE", 0x574DE134); ped_models_hashes.Add("CS_MARSHAL", 0x8B0322AF); ped_models_hashes.Add("CS_PATHOS", 0xD77D71DF); ped_models_hashes.Add("CS_SARAH", 0xEFF3F84D); ped_models_hashes.Add("CS_ROMAN_D", 0x42F6375E); ped_models_hashes.Add("CS_ROMAN_T", 0x6368F847); ped_models_hashes.Add("CS_ROMAN_W", 0xE37B786A); ped_models_hashes.Add("CS_BRUCIE_B", 0x0E37C613); ped_models_hashes.Add("CS_BRUCIE_T", 0x0E1B45E6); ped_models_hashes.Add("CS_BRUCIE_W", 0x765C9667); ped_models_hashes.Add("CS_BERNIE_CRANEC", 0x7183C75F); ped_models_hashes.Add("CS_BERNIE_CRANET", 0x4231E7AC); ped_models_hashes.Add("CS_BERNIE_CRANEW", 0x1B4899DE); ped_models_hashes.Add("CS_LILJACOB_B", 0xB0B4BC37); ped_models_hashes.Add("CS_LILJACOB_J", 0x7EF858B3); ped_models_hashes.Add("CS_MALLORIE_D", 0x5DF63F45); ped_models_hashes.Add("CS_MALLORIE_J", 0xCC381BCB); ped_models_hashes.Add("CS_MALLORIE_W", 0x45768E2E); ped_models_hashes.Add("CS_DERRICKMC_B", 0x8469C377); ped_models_hashes.Add("CS_DERRICKMC_D", 0x2FBC9A1E); ped_models_hashes.Add("CS_MICHAEL_B", 0x7D0BADD3); ped_models_hashes.Add("CS_MICHAEL_D", 0xCF5FD27A); ped_models_hashes.Add("CS_PACKIEMC_B", 0x4DFB1B0C); ped_models_hashes.Add("CS_PACKIEMC_D", 0x68EED0F3); ped_models_hashes.Add("CS_KATEMC_D", 0xAF3F2AC0); ped_models_hashes.Add("CS_KATEMC_W", 0x4ABDE1C7); ped_models_hashes.Add("M_Y_GAFR_LO_01", 0xEE0BB2A4); ped_models_hashes.Add("M_Y_GAFR_LO_02", 0xBBD14E30); ped_models_hashes.Add("M_Y_GAFR_HI_01", 0x33D38899); ped_models_hashes.Add("M_Y_GAFR_HI_02", 0x25B4EC5C); ped_models_hashes.Add("M_Y_GALB_LO_01", 0xE1F6A366); ped_models_hashes.Add("M_Y_GALB_LO_02", 0xF1F54363); ped_models_hashes.Add("M_Y_GALB_LO_03", 0x0C61783B); ped_models_hashes.Add("M_Y_GALB_LO_04", 0x1EA71CCE); ped_models_hashes.Add("M_M_GBIK_LO_03", 0x029035B4); ped_models_hashes.Add("M_Y_GBIK_HI_01", 0x5044865F); ped_models_hashes.Add("M_Y_GBIK_HI_02", 0x9C071DE3); ped_models_hashes.Add("M_Y_GBIK02_LO_02", 0xA8E69DBF); ped_models_hashes.Add("M_Y_GBIK_LO_01", 0x5DDE4F9B); ped_models_hashes.Add("M_Y_GBIK_LO_02", 0x8B932B00); ped_models_hashes.Add("M_Y_GIRI_LO_01", 0x10B7B44B); ped_models_hashes.Add("M_Y_GIRI_LO_02", 0xFEDA1090); ped_models_hashes.Add("M_Y_GIRI_LO_03", 0x6DF3EEC6); ped_models_hashes.Add("M_M_GJAM_HI_01", 0x5FF2E9AF); ped_models_hashes.Add("M_M_GJAM_HI_02", 0xEC4D0269); ped_models_hashes.Add("M_M_GJAM_HI_03", 0x4295AEF5); ped_models_hashes.Add("M_Y_GJAM_LO_01", 0xA691BED3); ped_models_hashes.Add("M_Y_GJAM_LO_02", 0xCB77889E); ped_models_hashes.Add("M_Y_GKOR_LO_01", 0x5BD063B5); ped_models_hashes.Add("M_Y_GKOR_LO_02", 0x2D8D8730); ped_models_hashes.Add("M_Y_GLAT_LO_01", 0x1D55921C); ped_models_hashes.Add("M_Y_GLAT_LO_02", 0x8D32F1D9); ped_models_hashes.Add("M_Y_GLAT_HI_01", 0x45A43081); ped_models_hashes.Add("M_Y_GLAT_HI_02", 0x97E25504); ped_models_hashes.Add("M_Y_GMAF_HI_01", 0xEDFA50E3); ped_models_hashes.Add("M_Y_GMAF_HI_02", 0x9FA03430); ped_models_hashes.Add("M_Y_GMAF_LO_01", 0x03DBB737); ped_models_hashes.Add("M_Y_GMAF_LO_02", 0x1E6BEC57); ped_models_hashes.Add("M_O_GRUS_HI_01", 0x9290C4A3); ped_models_hashes.Add("M_Y_GRUS_LO_01", 0x83892528); ped_models_hashes.Add("M_Y_GRUS_LO_02", 0x75CF09B4); ped_models_hashes.Add("M_Y_GRUS_HI_02", 0x5BFE7C54); ped_models_hashes.Add("M_M_GRU2_HI_01", 0x6F31C4B4); ped_models_hashes.Add("M_M_GRU2_HI_02", 0x19BB19C8); ped_models_hashes.Add("M_M_GRU2_LO_02", 0x66CB1E64); ped_models_hashes.Add("M_Y_GRU2_LO_01", 0xB9A05501); ped_models_hashes.Add("M_M_GTRI_HI_01", 0x33EEB47F); ped_models_hashes.Add("M_M_GTRI_HI_02", 0x28C09E23); ped_models_hashes.Add("M_Y_GTRI_LO_01", 0xBF635A9F); ped_models_hashes.Add("M_Y_GTRI_LO_02", 0xF62B4836); ped_models_hashes.Add("F_O_MAID_01", 0xD33B8FE9); ped_models_hashes.Add("F_O_BINCO", 0xF97D04E6); ped_models_hashes.Add("F_Y_BANK_01", 0x516F7106); ped_models_hashes.Add("F_Y_DOCTOR_01", 0x14A4B50F); ped_models_hashes.Add("F_Y_GYMGAL_01", 0x507AAC5B); ped_models_hashes.Add("F_Y_FF_BURGER_R", 0x37214098); ped_models_hashes.Add("F_Y_FF_CLUCK_R", 0xEB5AB08B); ped_models_hashes.Add("F_Y_FF_RSCAFE", 0x8292BFB5); ped_models_hashes.Add("F_Y_FF_TWCAFE", 0x0CB09BED); ped_models_hashes.Add("F_Y_FF_WSPIZZA_R", 0xEEB5DE91); ped_models_hashes.Add("F_Y_HOOKER_01", 0x20EF1FEB); ped_models_hashes.Add("F_Y_HOOKER_03", 0x3B61D4D0); ped_models_hashes.Add("F_Y_NURSE", 0xB8D8632B); ped_models_hashes.Add("F_Y_STRIPPERC01", 0x42615D12); ped_models_hashes.Add("F_Y_STRIPPERC02", 0x50AFF9AF); ped_models_hashes.Add("F_Y_WAITRESS_01", 0x0171C5D1); ped_models_hashes.Add("M_M_ALCOHOLIC", 0x97093869); ped_models_hashes.Add("M_M_ARMOURED", 0x401C1901); ped_models_hashes.Add("M_M_BUSDRIVER", 0x07FDDC3F); ped_models_hashes.Add("M_M_CHINATOWN_01", 0x2D243DEF); ped_models_hashes.Add("M_M_CRACKHEAD", 0x9313C198); ped_models_hashes.Add("M_M_DOC_SCRUBS_01", 0x0D13AEF5); ped_models_hashes.Add("M_M_DOCTOR_01", 0xB940B896); ped_models_hashes.Add("M_M_DODGYDOC", 0x16653776); ped_models_hashes.Add("M_M_EECOOK", 0x7D77FE8D); ped_models_hashes.Add("M_M_ENFORCER", 0xF410AB9B); ped_models_hashes.Add("M_M_FACTORY_01", 0x2FB107C1); ped_models_hashes.Add("M_M_FATCOP_01", 0xE9EC3678); ped_models_hashes.Add("M_M_FBI", 0xC46CBC16); ped_models_hashes.Add("M_M_FEDCO", 0x89275CA8); ped_models_hashes.Add("M_M_FIRECHIEF", 0x24696C93); ped_models_hashes.Add("M_M_GUNNUT_01", 0x1CFC648F); ped_models_hashes.Add("M_M_HELIPILOT_01", 0xD19BD6D0); ped_models_hashes.Add("M_M_HPORTER_01", 0x2536480C); ped_models_hashes.Add("M_M_KOREACOOK_01", 0x959D9B8A); ped_models_hashes.Add("M_M_LAWYER_01", 0x918DD1CF); ped_models_hashes.Add("M_M_LAWYER_02", 0xBC5DA76E); ped_models_hashes.Add("M_M_LOONYBLACK", 0x1699B3B8); ped_models_hashes.Add("M_M_PILOT", 0x8C0F140E); ped_models_hashes.Add("M_M_PINDUS_01", 0x301D7295); ped_models_hashes.Add("M_M_POSTAL_01", 0xEF0CF791); ped_models_hashes.Add("M_M_SAXPLAYER_01", 0xB92CCD03); ped_models_hashes.Add("M_M_SECURITYMAN", 0x907AF88D); ped_models_hashes.Add("M_M_SELLER_01", 0x1916A97C); ped_models_hashes.Add("M_M_SHORTORDER", 0x6FF14E0F); ped_models_hashes.Add("M_M_STREETFOOD_01", 0x0881E67C); ped_models_hashes.Add("M_M_SWEEPER", 0xD6D5085C); ped_models_hashes.Add("M_M_TAXIDRIVER", 0x0085DCEE); ped_models_hashes.Add("M_M_TELEPHONE", 0x46B50EAA); ped_models_hashes.Add("M_M_TENNIS", 0xE96555E2); ped_models_hashes.Add("M_M_TRAIN_01", 0x452086C4); ped_models_hashes.Add("M_M_TRAMPBLACK", 0xF7835A1A); ped_models_hashes.Add("M_M_TRUCKER_01", 0xFD3979FD); ped_models_hashes.Add("M_O_JANITOR", 0xB376FD38); ped_models_hashes.Add("M_O_HOTEL_FOOT", 0x015E1A07); ped_models_hashes.Add("M_O_MPMOBBOSS", 0x463E4B5D); ped_models_hashes.Add("M_Y_AIRWORKER", 0xA8B24166); ped_models_hashes.Add("M_Y_BARMAN_01", 0x80807842); ped_models_hashes.Add("M_Y_BOUNCER_01", 0x95DCB0F5); ped_models_hashes.Add("M_Y_BOUNCER_02", 0xE79AD470); ped_models_hashes.Add("M_Y_BOWL_01", 0xD05CB843); ped_models_hashes.Add("M_Y_BOWL_02", 0xE61EE3C7); ped_models_hashes.Add("M_Y_CHINVEND_01", 0x2DCD7F4C); ped_models_hashes.Add("M_Y_CLUBFIT", 0x2851C93C); ped_models_hashes.Add("M_Y_CONSTRUCT_01", 0xD4F6DA2A); ped_models_hashes.Add("M_Y_CONSTRUCT_02", 0xC371B720); ped_models_hashes.Add("M_Y_CONSTRUCT_03", 0xD56DDB14); ped_models_hashes.Add("M_Y_COP", 0xF5148AB2); ped_models_hashes.Add("M_Y_COP_TRAFFIC", 0xA576D885); ped_models_hashes.Add("M_Y_COURIER", 0xAE46285D); ped_models_hashes.Add("M_Y_COWBOY_01", 0xDDCCAF85); ped_models_hashes.Add("M_Y_DEALER", 0xB380C536); ped_models_hashes.Add("M_Y_DRUG_01", 0x565A4099); ped_models_hashes.Add("M_Y_FF_BURGER_R", 0x000F192D); ped_models_hashes.Add("M_Y_FF_CLUCK_R", 0xC3B54549); ped_models_hashes.Add("M_Y_FF_RSCAFE", 0x75FDB605); ped_models_hashes.Add("M_Y_FF_TWCAFE", 0xD11FBA8B); ped_models_hashes.Add("M_Y_FF_WSPIZZA_R", 0x0C55ACF1); ped_models_hashes.Add("M_Y_FIREMAN", 0xDBA0B619); ped_models_hashes.Add("M_Y_GARBAGE", 0x43BD9C04); ped_models_hashes.Add("M_Y_GOON_01", 0x358464B5); ped_models_hashes.Add("M_Y_GYMGUY_01", 0x8E96352C); ped_models_hashes.Add("M_Y_MECHANIC_02", 0xEABA11B9); ped_models_hashes.Add("M_Y_MODO", 0xC10A9D57); ped_models_hashes.Add("M_Y_NHELIPILOT", 0x479F2007); ped_models_hashes.Add("M_Y_PERSEUS", 0xF6FFEBB2); ped_models_hashes.Add("M_Y_PINDUS_01", 0x1DDEBBCF); ped_models_hashes.Add("M_Y_PINDUS_02", 0x0B1F9651); ped_models_hashes.Add("M_Y_PINDUS_03", 0xF958F2C4); ped_models_hashes.Add("M_Y_PMEDIC", 0xB9F5BEA0); ped_models_hashes.Add("M_Y_PRISON", 0x9C0BF5CC); ped_models_hashes.Add("M_Y_PRISONAOM", 0x0CD38A07); ped_models_hashes.Add("M_Y_ROMANCAB", 0x5C907185); ped_models_hashes.Add("M_Y_RUNNER", 0xA7ABA2BA); ped_models_hashes.Add("M_Y_SHOPASST_01", 0x15556BF3); ped_models_hashes.Add("M_Y_STROOPER", 0xFAAD5B99); ped_models_hashes.Add("M_Y_SWAT", 0xC41C88BE); ped_models_hashes.Add("M_Y_SWORDSWALLOW", 0xFC2BE1B8); ped_models_hashes.Add("M_Y_THIEF", 0xB2F9C1A1); ped_models_hashes.Add("M_Y_VALET", 0x102B77F0); ped_models_hashes.Add("M_Y_VENDOR", 0xF4E8205B); ped_models_hashes.Add("M_Y_FRENCHTOM", 0x87DB1287); ped_models_hashes.Add("M_Y_JIM_FITZ", 0x75E29A7D); ped_models_hashes.Add("F_O_PEASTEURO_01", 0xF3D9C032); ped_models_hashes.Add("F_O_PEASTEURO_02", 0x0B50EF20); ped_models_hashes.Add("F_O_PHARBRON_01", 0xEB320486); ped_models_hashes.Add("F_O_PJERSEY_01", 0xF92630A4); ped_models_hashes.Add("F_O_PORIENT_01", 0x9AD4BE64); ped_models_hashes.Add("F_O_RICH_01", 0x0600A909); ped_models_hashes.Add("F_M_BUSINESS_01", 0x093E163C); ped_models_hashes.Add("F_M_BUSINESS_02", 0x1780B2C1); ped_models_hashes.Add("F_M_CHINATOWN", 0x51FFF4A5); ped_models_hashes.Add("F_M_PBUSINESS", 0xEF0F006B); ped_models_hashes.Add("F_M_PEASTEURO_01", 0x2864B0DC); ped_models_hashes.Add("F_M_PHARBRON_01", 0xB92CE9DD); ped_models_hashes.Add("F_M_PJERSEY_01", 0x844EA438); ped_models_hashes.Add("F_M_PJERSEY_02", 0xAF1EF9D8); ped_models_hashes.Add("F_M_PLATIN_01", 0x3067DA63); ped_models_hashes.Add("F_M_PLATIN_02", 0xF84BEA2C); ped_models_hashes.Add("F_M_PMANHAT_01", 0x32CEF1D1); ped_models_hashes.Add("F_M_PMANHAT_02", 0x04901554); ped_models_hashes.Add("F_M_PORIENT_01", 0x81BA39A8); ped_models_hashes.Add("F_M_PRICH_01", 0x605DF31F); ped_models_hashes.Add("F_Y_BUSINESS_01", 0x1B0DCC86); ped_models_hashes.Add("F_Y_CDRESS_01", 0x3120FC7F); ped_models_hashes.Add("F_Y_PBRONX_01", 0xAECAC8C7); ped_models_hashes.Add("F_Y_PCOOL_01", 0x9568444C); ped_models_hashes.Add("F_Y_PCOOL_02", 0xA52AE3D1); ped_models_hashes.Add("F_Y_PEASTEURO_01", 0xC760585B); ped_models_hashes.Add("F_Y_PHARBRON_01", 0x8D2AC355); ped_models_hashes.Add("F_Y_PHARLEM_01", 0x0A047A8F); ped_models_hashes.Add("F_Y_PJERSEY_02", 0x0006BC78); ped_models_hashes.Add("F_Y_PLATIN_01", 0x0339B6D8); ped_models_hashes.Add("F_Y_PLATIN_02", 0xEE8D8D80); ped_models_hashes.Add("F_Y_PLATIN_03", 0x67F08048); ped_models_hashes.Add("F_Y_PMANHAT_01", 0x6392D986); ped_models_hashes.Add("F_Y_PMANHAT_02", 0x50B8B3D2); ped_models_hashes.Add("F_Y_PMANHAT_03", 0x3EFE105D); ped_models_hashes.Add("F_Y_PORIENT_01", 0xB8DA98D7); ped_models_hashes.Add("F_Y_PQUEENS_01", 0x2A8A0FF0); ped_models_hashes.Add("F_Y_PRICH_01", 0x95E177F9); ped_models_hashes.Add("F_Y_PVILLBO_02", 0xC73ECED1); ped_models_hashes.Add("F_Y_SHOP_03", 0x5E8CD2B8); ped_models_hashes.Add("F_Y_SHOP_04", 0x6E2671EB); ped_models_hashes.Add("F_Y_SHOPPER_05", 0x9A8CFCFD); ped_models_hashes.Add("F_Y_SOCIALITE", 0x4680C12E); ped_models_hashes.Add("F_Y_STREET_02", 0xCA5194CB); ped_models_hashes.Add("F_Y_STREET_05", 0x110C2243); ped_models_hashes.Add("F_Y_STREET_09", 0x57D62FD6); ped_models_hashes.Add("F_Y_STREET_12", 0x91AFE421); ped_models_hashes.Add("F_Y_STREET_30", 0x4CEF5CF5); ped_models_hashes.Add("F_Y_STREET_34", 0x6F96222E); ped_models_hashes.Add("F_Y_TOURIST_01", 0x6892A334); ped_models_hashes.Add("F_Y_VILLBO_01", 0x2D6795BA); ped_models_hashes.Add("M_M_BUSINESS_02", 0xDA0E92D1); ped_models_hashes.Add("M_M_BUSINESS_03", 0x976C0D95); ped_models_hashes.Add("M_M_EE_HEAVY_01", 0xA59C6FD2); ped_models_hashes.Add("M_M_EE_HEAVY_02", 0x9371CB7D); ped_models_hashes.Add("M_M_FATMOB_01", 0x74636532); ped_models_hashes.Add("M_M_GAYMID", 0x894A8CB2); ped_models_hashes.Add("M_M_GENBUM_01", 0xBF963CE7); ped_models_hashes.Add("M_M_LOONYWHITE", 0x1D88B92A); ped_models_hashes.Add("M_M_MIDTOWN_01", 0x89BC811F); ped_models_hashes.Add("M_M_PBUSINESS_01", 0x3F688D84); ped_models_hashes.Add("M_M_PEASTEURO_01", 0x0C717BCE); ped_models_hashes.Add("M_M_PHARBRON_01", 0xC3306A8C); ped_models_hashes.Add("M_M_PINDUS_02", 0x6A3B66CC); ped_models_hashes.Add("M_M_PITALIAN_01", 0xAC686EC9); ped_models_hashes.Add("M_M_PITALIAN_02", 0x9EF053D9); ped_models_hashes.Add("M_M_PLATIN_01", 0x450E5DBF); ped_models_hashes.Add("M_M_PLATIN_02", 0x75633E74); ped_models_hashes.Add("M_M_PLATIN_03", 0x60AD1508); ped_models_hashes.Add("M_M_PMANHAT_01", 0xD8CF835D); ped_models_hashes.Add("M_M_PMANHAT_02", 0xB217B5E2); ped_models_hashes.Add("M_M_PORIENT_01", 0x2BC50FD3); ped_models_hashes.Add("M_M_PRICH_01", 0x6F2AE4DB); ped_models_hashes.Add("M_O_EASTEURO_01", 0xE6372469); ped_models_hashes.Add("M_O_HASID_01", 0x9E495AD7); ped_models_hashes.Add("M_O_MOBSTER", 0x62B5E24B); ped_models_hashes.Add("M_O_PEASTEURO_02", 0x793F36B1); ped_models_hashes.Add("M_O_PHARBRON_01", 0x4E76BDF6); ped_models_hashes.Add("M_O_PJERSEY_01", 0x3A78BA45); ped_models_hashes.Add("M_O_STREET_01", 0xB29788AB); ped_models_hashes.Add("M_O_SUITED", 0x0E86251C); ped_models_hashes.Add("M_Y_BOHO_01", 0x7C54115F); ped_models_hashes.Add("M_Y_BOHOGUY_01", 0x0D2FF2BF); ped_models_hashes.Add("M_Y_BRONX_01", 0x031EE9E3); ped_models_hashes.Add("M_Y_BUSINESS_01", 0x5B404032); ped_models_hashes.Add("M_Y_BUSINESS_02", 0x2924DBD8); ped_models_hashes.Add("M_Y_CHINATOWN_03", 0xBB784DE6); ped_models_hashes.Add("M_Y_CHOPSHOP_01", 0xED4319C3); ped_models_hashes.Add("M_Y_CHOPSHOP_02", 0xDF0C7D56); ped_models_hashes.Add("M_Y_DODGY_01", 0xBE9A3CD6); ped_models_hashes.Add("M_Y_DORK_02", 0x962996E4); ped_models_hashes.Add("M_Y_DOWNTOWN_01", 0x47F77FC9); ped_models_hashes.Add("M_Y_DOWNTOWN_02", 0x5971A2B9); ped_models_hashes.Add("M_Y_DOWNTOWN_03", 0x236BB6B2); ped_models_hashes.Add("M_Y_GAYYOUNG", 0xD36D1B5D); ped_models_hashes.Add("M_Y_GENSTREET_11", 0xD7A357ED); ped_models_hashes.Add("M_Y_GENSTREET_16", 0x9BF260A8); ped_models_hashes.Add("M_Y_GENSTREET_20", 0x3AF39D6C); ped_models_hashes.Add("M_Y_GENSTREET_34", 0x4658B34E); ped_models_hashes.Add("M_Y_HARDMAN_01", 0xAB537AD4); ped_models_hashes.Add("M_Y_HARLEM_01", 0xB71B0F29); ped_models_hashes.Add("M_Y_HARLEM_02", 0x97EBD0CB); ped_models_hashes.Add("M_Y_HARLEM_04", 0x7D701BD4); ped_models_hashes.Add("M_Y_HASID_01", 0x90442A67); ped_models_hashes.Add("M_Y_LEASTSIDE_01", 0xC1181556); ped_models_hashes.Add("M_Y_PBRONX_01", 0x22522444); ped_models_hashes.Add("M_Y_PCOOL_01", 0xFBB5AA01); ped_models_hashes.Add("M_Y_PCOOL_02", 0xF45E1B4E); ped_models_hashes.Add("M_Y_PEASTEURO_01", 0x298F268A); ped_models_hashes.Add("M_Y_PHARBRON_01", 0x27F5967B); ped_models_hashes.Add("M_Y_PHARLEM_01", 0x01961E02); ped_models_hashes.Add("M_Y_PJERSEY_01", 0x5BF734C6); ped_models_hashes.Add("M_Y_PLATIN_01", 0x944D1A30); ped_models_hashes.Add("M_Y_PLATIN_02", 0xC30777A4); ped_models_hashes.Add("M_Y_PLATIN_03", 0xB0F0D377); ped_models_hashes.Add("M_Y_PMANHAT_01", 0x243BD606); ped_models_hashes.Add("M_Y_PMANHAT_02", 0x7554785A); ped_models_hashes.Add("M_Y_PORIENT_01", 0xEB7CE59F); ped_models_hashes.Add("M_Y_PQUEENS_01", 0x21673B90); ped_models_hashes.Add("M_Y_PRICH_01", 0x509627D1); ped_models_hashes.Add("M_Y_PVILLBO_01", 0x0D55CAAC); ped_models_hashes.Add("M_Y_PVILLBO_02", 0xB5559AAD); ped_models_hashes.Add("M_Y_PVILLBO_03", 0xA2E575D9); ped_models_hashes.Add("M_Y_QUEENSBRIDGE", 0x48E8EE31); ped_models_hashes.Add("M_Y_SHADY_02", 0xB73D062F); ped_models_hashes.Add("M_Y_SKATEBIKE_01", 0x68A019EE); ped_models_hashes.Add("M_Y_SOHO_01", 0x170C6DAE); ped_models_hashes.Add("M_Y_STREET_01", 0x03B99DE1); ped_models_hashes.Add("M_Y_STREET_03", 0x1F3854DE); ped_models_hashes.Add("M_Y_STREET_04", 0x3082F773); ped_models_hashes.Add("M_Y_STREETBLK_02", 0xA37B1794); ped_models_hashes.Add("M_Y_STREETBLK_03", 0xD939030F); ped_models_hashes.Add("M_Y_STREETPUNK_02", 0xD3E34ABA); ped_models_hashes.Add("M_Y_STREETPUNK_04", 0x8D1CBD36); ped_models_hashes.Add("M_Y_STREETPUNK_05", 0x51E946D0); ped_models_hashes.Add("M_Y_TOUGH_05", 0xBC0DDE62); ped_models_hashes.Add("M_Y_TOURIST_02", 0x303963D0); ped_models_hashes.Add("F_Y_BIKESTRIPPER_01", 2260698422); ped_models_hashes.Add("F_Y_BUSIASIAN", 3838500417); ped_models_hashes.Add("F_Y_EMIDTOWN_01", 501384733); ped_models_hashes.Add("F_Y_GANGELS_01", 4144320784); ped_models_hashes.Add("F_Y_GANGELS_02", 690697563); ped_models_hashes.Add("F_Y_GANGELS_03", 3790939888); ped_models_hashes.Add("F_Y_GLOST_01", 188410296); ped_models_hashes.Add("F_Y_GLOST_02", 1414790133); ped_models_hashes.Add("F_Y_GLOST_03", 630267504); ped_models_hashes.Add("F_Y_GLOST_04", 1719115836); ped_models_hashes.Add("F_Y_GRYDERS_01", 3017999869); ped_models_hashes.Add("F_Y_UPTOWN_01", 82171231); ped_models_hashes.Add("F_Y_UPTOWN_CS", 2396119352); ped_models_hashes.Add("IG_ASHLEYA", 3567004438); ped_models_hashes.Add("IG_BILLY", 3843248439); ped_models_hashes.Add("IG_BILLYPRISON", 3435224654); ped_models_hashes.Add("IG_BRIANJ", 349841464); ped_models_hashes.Add("IG_CLAY", 1825562762); ped_models_hashes.Add("IG_DAVE_GROSSMAN", 3056906300); ped_models_hashes.Add("IG_DESEAN", 4221176784); ped_models_hashes.Add("IG_EVAN", 3497746837); ped_models_hashes.Add("IG_JASON_M", 3346030785); ped_models_hashes.Add("IG_JIM_FITZ", 870892404); ped_models_hashes.Add("IG_LOSTGIRL", 3482212408); ped_models_hashes.Add("IG_MALC", 4055673113); ped_models_hashes.Add("IG_MARTA", 2687923072); ped_models_hashes.Add("IG_MATTHEWS", 4127866099); ped_models_hashes.Add("IG_MCCORNISH", 369735431); ped_models_hashes.Add("IG_NIKO", 1613899343); ped_models_hashes.Add("IG_PGIRL_01", 2759424181); ped_models_hashes.Add("IG_PGIRL_02", 1271449429); ped_models_hashes.Add("IG_ROMAN_E1", 3541379571); ped_models_hashes.Add("IG_STROOPER", 2513523815); ped_models_hashes.Add("IG_TERRY", 1728056212); ped_models_hashes.Add("LOSTBUDDY_01", 1914397972); ped_models_hashes.Add("LOSTBUDDY_02", 2156528113); ped_models_hashes.Add("LOSTBUDDY_03", 1215631816); ped_models_hashes.Add("LOSTBUDDY_04", 1706970202); ped_models_hashes.Add("LOSTBUDDY_05", 717510247); ped_models_hashes.Add("LOSTBUDDY_06", 965080042); ped_models_hashes.Add("LOSTBUDDY_07", 693982133); ped_models_hashes.Add("LOSTBUDDY_08", 454735664); ped_models_hashes.Add("LOSTBUDDY_09", 1409362172); ped_models_hashes.Add("LOSTBUDDY_10", 767450539); ped_models_hashes.Add("LOSTBUDDY_11", 1686719296); ped_models_hashes.Add("LOSTBUDDY_12", 1917871822); ped_models_hashes.Add("LOSTBUDDY_13", 422524045); ped_models_hashes.Add("M_M_SMARTBLACK", 2517083842); ped_models_hashes.Add("M_M_SPRETZER", 2180283747); ped_models_hashes.Add("M_M_UPEAST_01", 27417470); ped_models_hashes.Add("M_M_UPTOWN_01", 953174653); ped_models_hashes.Add("M_O_HISPANIC_01", 3262122625); ped_models_hashes.Add("M_Y_BIKEMECH", 4216342535); ped_models_hashes.Add("M_Y_BUSIASIAN", 4062186619); ped_models_hashes.Add("M_Y_BUSIMIDEAST", 2205011894); ped_models_hashes.Add("M_Y_CIADLC_01", 3895167824); ped_models_hashes.Add("M_Y_CIADLC_02", 4202901503); ped_models_hashes.Add("M_Y_DOORMAN_01", 4210560758); ped_models_hashes.Add("M_Y_GANGELS_02", 3135810833); ped_models_hashes.Add("M_Y_GANGELS_03", 479817841); ped_models_hashes.Add("M_Y_GANGELS_04", 226415164); ped_models_hashes.Add("M_Y_GANGELS_05", 15972646); ped_models_hashes.Add("M_Y_GANGELS_06", 2187410431); ped_models_hashes.Add("M_Y_GAYGANG_01", 1668078208); ped_models_hashes.Add("M_Y_GLOST_01", 1439613707); ped_models_hashes.Add("M_Y_GLOST_02", 1737188996); ped_models_hashes.Add("M_Y_GLOST_03", 3883329117); ped_models_hashes.Add("M_Y_GLOST_04", 2164529525); ped_models_hashes.Add("M_Y_GLOST_05", 2462432504); ped_models_hashes.Add("M_Y_GLOST_06", 2624639054); ped_models_hashes.Add("M_Y_GRYDERS_01", 236691815); ped_models_hashes.Add("M_Y_GRYDERS_02", 1590280898); ped_models_hashes.Add("M_Y_GTRI_02", 2666541716); ped_models_hashes.Add("M_Y_GTRIAD_HI_01", 1259063802); ped_models_hashes.Add("M_Y_HIP_02", 3851036332); ped_models_hashes.Add("M_Y_HIPMALE_01", 3517356013); ped_models_hashes.Add("M_Y_HISPANIC_01", 1520019648); ped_models_hashes.Add("M_Y_PRISONBLACK", 2843661179); ped_models_hashes.Add("M_Y_PRISONDLC_01", 3470550570); ped_models_hashes.Add("M_Y_PRISONGUARD", 2378673688); ped_models_hashes.Add("F_Y_ASIANCLUB_01", 1724390423); ped_models_hashes.Add("F_Y_ASIANCLUB_02", 1964095658); ped_models_hashes.Add("F_Y_CLOEPARKER", 2802928488); ped_models_hashes.Add("F_Y_CLUBEURO_01", 930552533); ped_models_hashes.Add("F_Y_DANCER_01", 3486101654); ped_models_hashes.Add("F_Y_DOMGIRL_01", 1376565880); ped_models_hashes.Add("F_Y_EMIDTOWN_02", 3230321503); ped_models_hashes.Add("F_Y_HOSTESS", 2048838359); ped_models_hashes.Add("F_Y_HOTCHICK_01", 3997382082); ped_models_hashes.Add("F_Y_HOTCHICK_02", 2480144589); ped_models_hashes.Add("F_Y_HOTCHICK_03", 314506937); ped_models_hashes.Add("F_Y_JONI", 3412908435); ped_models_hashes.Add("F_Y_PGIRL_01", 3450748540); ped_models_hashes.Add("F_Y_PGIRL_02", 2610911831); ped_models_hashes.Add("F_Y_SMID_01", 2686009836); ped_models_hashes.Add("F_Y_TRENDY_01", 763838720); ped_models_hashes.Add("IG_AHMAD", 3807793447); ped_models_hashes.Add("IG_ARMANDO", 1370299619); ped_models_hashes.Add("IG_ARMSDEALER", 1195842459); ped_models_hashes.Add("IG_ARNAUD", 714517099); ped_models_hashes.Add("IG_BANKER", 465237040); ped_models_hashes.Add("IG_BLUEBROS", 2837294033); ped_models_hashes.Add("IG_BRUCIE2", 3893268832); ped_models_hashes.Add("IG_BULGARIN2", 243666427); ped_models_hashes.Add("IG_DAISY", 653404222); ped_models_hashes.Add("IG_DEEJAY", 2840262812); ped_models_hashes.Add("IG_DESSIE", 2848083183); ped_models_hashes.Add("IG_GRACIE2", 2014087898); ped_models_hashes.Add("IG_HENRIQUE", 1905515841); ped_models_hashes.Add("IG_ISSAC2", 2805295892); ped_models_hashes.Add("IG_JACKSON", 3241646740); ped_models_hashes.Add("IG_JOHNNY2", 8206123); ped_models_hashes.Add("IG_LUIS2", 1976355936); ped_models_hashes.Add("IG_MARGOT", 1798610950); ped_models_hashes.Add("IG_MORI_K", 1662225612); ped_models_hashes.Add("IG_MR_SANTOS", 643311700); ped_models_hashes.Add("IG_NAPOLI", 3458234342); ped_models_hashes.Add("IG_OYVEY", 2089415431); ped_models_hashes.Add("IG_ROCCO", 3381042378); ped_models_hashes.Add("IG_ROYAL", 3690408662); ped_models_hashes.Add("IG_SPADE", 1730047377); ped_models_hashes.Add("IG_TAHIR", 3887900262); ped_models_hashes.Add("IG_TIMUR", 2345614827); ped_models_hashes.Add("IG_TONY", 4020398429); ped_models_hashes.Add("IG_TRAMP2", 3321165989); ped_models_hashes.Add("IG_TRIAD", 2397320); ped_models_hashes.Add("IG_TROY", 1662473323); ped_models_hashes.Add("IG_VIC", 4138181684); ped_models_hashes.Add("IG_VICGIRL", 3837819283); ped_models_hashes.Add("IG_VINCE", 1384494459); ped_models_hashes.Add("IG_YUSEF", 3846796161); ped_models_hashes.Add("M_M_E2MAF_01", 3623617227); ped_models_hashes.Add("M_M_E2MAF_02", 821179586); ped_models_hashes.Add("M_M_MAFUNION", 657888018); ped_models_hashes.Add("M_Y_AMIRGUARD_01", 658237358); ped_models_hashes.Add("M_Y_BARMAISON", 2598437087); ped_models_hashes.Add("M_Y_BATHROOM", 1429700748); ped_models_hashes.Add("M_Y_CELEBBLOG", 2496379640); ped_models_hashes.Add("M_Y_CLUBBLACK_01", 3547608240); ped_models_hashes.Add("M_Y_CLUBEURO_01", 284474691); ped_models_hashes.Add("M_Y_CLUBEURO_02", 4283570686); ped_models_hashes.Add("M_Y_CLUBEURO_03", 627205662); ped_models_hashes.Add("M_Y_CLUBWHITE_01", 698554670); ped_models_hashes.Add("M_Y_DOMDRUG_01", 247648794); ped_models_hashes.Add("M_Y_DOMGUY_01", 738125806); ped_models_hashes.Add("M_Y_DOMGUY_02", 1639961459); ped_models_hashes.Add("M_Y_DOORMAN_02", 1756785265); ped_models_hashes.Add("M_Y_E2RUSSIAN_01", 2972144845); ped_models_hashes.Add("M_Y_E2RUSSIAN_02", 3738841110); ped_models_hashes.Add("M_Y_E2RUSSIAN_03", 3575913642); ped_models_hashes.Add("M_Y_EXSPORTS", 504377658); ped_models_hashes.Add("M_Y_FIGHTCLUB_01", 188553127); ped_models_hashes.Add("M_Y_FIGHTCLUB_02", 2817839380); ped_models_hashes.Add("M_Y_FIGHTCLUB_03", 3125245369); ped_models_hashes.Add("M_Y_FIGHTCLUB_04", 3466894963); ped_models_hashes.Add("M_Y_FIGHTCLUB_05", 3730980334); ped_models_hashes.Add("M_Y_FIGHTCLUB_06", 1394419558); ped_models_hashes.Add("M_Y_FIGHTCLUB_07", 1691568850); ped_models_hashes.Add("M_Y_FIGHTCLUB_08", 1971776569); ped_models_hashes.Add("M_Y_GAYBLACK_01", 563038535); ped_models_hashes.Add("M_Y_GAYDANCER", 2856837426); ped_models_hashes.Add("M_Y_GAYGENERAL_01", 3769281318); ped_models_hashes.Add("M_Y_GAYWHITE_01", 3595638835); ped_models_hashes.Add("M_Y_GUIDO_01", 982077731); ped_models_hashes.Add("M_Y_GUIDO_02", 1758965191); ped_models_hashes.Add("M_Y_MIDEAST_01", 761611541); ped_models_hashes.Add("M_Y_MOBPARTY", 1127066537); ped_models_hashes.Add("M_Y_PAPARAZZI_01", 2881739989); ped_models_hashes.Add("M_Y_UPTOWN_01", 3448520480); vehicle_hashes = new Dictionary<string, uint>(); vehicle_hashes.Add("ADMIRAL", 0x4B5C5320); vehicle_hashes.Add("AIRTUG", 0x5D0AAC8F); vehicle_hashes.Add("AMBULANCE", 0x45D56ADA); vehicle_hashes.Add("BANSHEE", 0xC1E908D2); vehicle_hashes.Add("BENSON", 0x7A61B330); vehicle_hashes.Add("BIFF", 0x32B91AE8); vehicle_hashes.Add("BLISTA", 0xEB70965F); vehicle_hashes.Add("BOBCAT", 0x4020325C); vehicle_hashes.Add("BOXVILLE", 0x898ECCEA); vehicle_hashes.Add("BUCCANEER", 0xD756460C); vehicle_hashes.Add("BURRITO", 0xAFBB2CA4); vehicle_hashes.Add("BURRITO2", 0xC9E8FF76); vehicle_hashes.Add("BUS", 0xD577C962); vehicle_hashes.Add("CABBY", 0x705A3E41); vehicle_hashes.Add("CAVALCADE", 0x779F23AA); vehicle_hashes.Add("CHAVOS", 0xFBFD5B62); vehicle_hashes.Add("COGNOSCENTI", 0x86FE0B60); vehicle_hashes.Add("COMET", 0x3F637729); vehicle_hashes.Add("COQUETTE", 0x067BC037); vehicle_hashes.Add("DF8", 0x09B56631); vehicle_hashes.Add("DILETTANTE", 0xBC993509); vehicle_hashes.Add("DUKES", 0x2B26F456); vehicle_hashes.Add("E109", 0x8A765902); vehicle_hashes.Add("EMPEROR", 0xD7278283); vehicle_hashes.Add("EMPEROR2", 0x8FC3AADC); vehicle_hashes.Add("ESPERANTO", 0xEF7ED55D); vehicle_hashes.Add("FACTION", 0x81A9CDDF); vehicle_hashes.Add("FBI", 0x432EA949); vehicle_hashes.Add("FELTZER", 0xBE9075F1); vehicle_hashes.Add("FEROCI", 0x3A196CEA); vehicle_hashes.Add("FEROCI2", 0x3D285C4A); vehicle_hashes.Add("FIRETRUK", 0x73920F8E); vehicle_hashes.Add("FLATBED", 0x50B0215A); vehicle_hashes.Add("FORTUNE", 0x255FC509); vehicle_hashes.Add("FORKLIFT", 0x58E49664); vehicle_hashes.Add("FUTO", 0x7836CE2F); vehicle_hashes.Add("FXT", 0x28420460); vehicle_hashes.Add("HABANERO", 0x34B7390F); vehicle_hashes.Add("HAKUMAI", 0xEB9F21D3); vehicle_hashes.Add("HUNTLEY", 0x1D06D681); vehicle_hashes.Add("INFERNUS", 0x18F25AC7); vehicle_hashes.Add("INGOT", 0xB3206692); vehicle_hashes.Add("INTRUDER", 0x34DD8AA1); vehicle_hashes.Add("LANDSTALKER", 0x4BA4E8DC); vehicle_hashes.Add("LOKUS", 0xFDCAF758); vehicle_hashes.Add("MANANA", 0x81634188); vehicle_hashes.Add("MARBELLA", 0x4DC293EA); vehicle_hashes.Add("MERIT", 0xB4D8797E); vehicle_hashes.Add("MINIVAN", 0xED7EADA4); vehicle_hashes.Add("MOONBEAM", 0x1F52A43F); vehicle_hashes.Add("MRTASTY", 0x22C16A2F); vehicle_hashes.Add("MULE", 0x35ED670B); vehicle_hashes.Add("NOOSE", 0x08DE2A8B); vehicle_hashes.Add("NSTOCKADE", 0x71EF6313); vehicle_hashes.Add("ORACLE", 0x506434F6); vehicle_hashes.Add("PACKER", 0x21EEE87D); vehicle_hashes.Add("PATRIOT", 0xCFCFEB3B); vehicle_hashes.Add("PERENNIAL", 0x84282613); vehicle_hashes.Add("PERENNIAL2", 0xA1363020); vehicle_hashes.Add("PEYOTE", 0x6D19CCBC); vehicle_hashes.Add("PHANTOM", 0x809AA4CB); vehicle_hashes.Add("PINNACLE", 0x07D10BDC); vehicle_hashes.Add("PMP600", 0x5208A519); vehicle_hashes.Add("POLICE", 0x79FBB0C5); vehicle_hashes.Add("POLICE2", 0x9F05F101); vehicle_hashes.Add("POLPATRIOT", 0xEB221FC2); vehicle_hashes.Add("PONY", 0xF8DE29A8); vehicle_hashes.Add("PREMIER", 0x8FB66F9B); vehicle_hashes.Add("PRES", 0x8B0D2BA6); vehicle_hashes.Add("PRIMO", 0xBB6B404F); vehicle_hashes.Add("PSTOCKADE", 0x8EB78F5A); vehicle_hashes.Add("RANCHER", 0x52DB01E0); vehicle_hashes.Add("REBLA", 0x04F48FC4); vehicle_hashes.Add("RIPLEY", 0xCD935EF9); vehicle_hashes.Add("ROMERO", 0x2560B2FC); vehicle_hashes.Add("ROM", 0x8CD0264C); vehicle_hashes.Add("RUINER", 0xF26CEFF9); vehicle_hashes.Add("SABRE", 0xE53C7459); vehicle_hashes.Add("SABRE2", 0x4B5D021E); vehicle_hashes.Add("SABREGT", 0x9B909C94); vehicle_hashes.Add("SCHAFTER", 0xECC96C3F); vehicle_hashes.Add("SENTINEL", 0x50732C82); vehicle_hashes.Add("SOLAIR", 0x50249008); vehicle_hashes.Add("SPEEDO", 0xCFB3870C); vehicle_hashes.Add("STALION", 0x72A4C31E); vehicle_hashes.Add("STEED", 0x63FFE6EC); vehicle_hashes.Add("STOCKADE", 0x6827CF72); vehicle_hashes.Add("STRATUM", 0x66B4FC45); vehicle_hashes.Add("STRETCH", 0x8B13F083); vehicle_hashes.Add("SULTAN", 0x39DA2754); vehicle_hashes.Add("SULTANRS", 0xEE6024BC); vehicle_hashes.Add("SUPERGT", 0x6C9962A9); vehicle_hashes.Add("TAXI", 0xC703DB5F); vehicle_hashes.Add("TAXI2", 0x480DAF95); vehicle_hashes.Add("TRASH", 0x72435A19); vehicle_hashes.Add("TURISMO", 0x8EF34547); vehicle_hashes.Add("URANUS", 0x5B73F5B7); vehicle_hashes.Add("VIGERO", 0xCEC6B9B7); vehicle_hashes.Add("VIGERO2", 0x973141FC); vehicle_hashes.Add("VINCENT", 0xDD3BD501); vehicle_hashes.Add("VIRGO", 0xE2504942); vehicle_hashes.Add("VOODOO", 0x779B4F2D); vehicle_hashes.Add("WASHINGTON", 0x69F06B57); vehicle_hashes.Add("WILLARD", 0x737DAEC2); vehicle_hashes.Add("YANKEE", 0xBE6FF06A); vehicle_hashes.Add("BOBBER", 0x92E56A2C); vehicle_hashes.Add("FAGGIO", 0x9229E4EB); vehicle_hashes.Add("HELLFURY", 0x22DC8E7F); vehicle_hashes.Add("NRG900", 0x47B9138A); vehicle_hashes.Add("PCJ", 0xC9CEAF06); vehicle_hashes.Add("SANCHEZ", 0x2EF89E46); vehicle_hashes.Add("ZOMBIEB", 0xDE05FB87); vehicle_hashes.Add("ANNIHILATOR", 0x31F0B376); vehicle_hashes.Add("MAVERICK", 0x9D0450CA); vehicle_hashes.Add("POLMAV", 0x1517D4D9); vehicle_hashes.Add("TOURMAV", 0x78D70477); vehicle_hashes.Add("DINGHY", 0x3D961290); vehicle_hashes.Add("JETMAX", 0x33581161); vehicle_hashes.Add("MARQUIS", 0xC1CE1183); vehicle_hashes.Add("PREDATOR", 0xE2E7D4AB); vehicle_hashes.Add("REEFER", 0x68E27CB6); vehicle_hashes.Add("SQUALO", 0x17DF5EC2); vehicle_hashes.Add("TUGA", 0x3F724E66); vehicle_hashes.Add("TROPIC", 0x1149422F); vehicle_hashes.Add("CABLECAR", 0xC6C3242D); vehicle_hashes.Add("SUBWAY_LO", 0x2FBC4D30); vehicle_hashes.Add("SUBWAY_HI", 0x8B887FDB); vehicle_hashes.Add("HEXER", 0x11F76C14); vehicle_hashes.Add("LYCAN", 0x2FCECEB7); vehicle_hashes.Add("NIGHTBLADE", 0xA0438767); vehicle_hashes.Add("REVENANT", 0xEA9789D1); vehicle_hashes.Add("DIABOLUS", 0xE7AD9DF9); vehicle_hashes.Add("WOLFSBANE", 0xDB20A373); vehicle_hashes.Add("DEAMON", 0x8509261B); vehicle_hashes.Add("ANGEL", 0xDDF716D8); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.DataContracts.ManagedReference { using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using Microsoft.DocAsCode.Common; using Microsoft.DocAsCode.Common.EntityMergers; using Microsoft.DocAsCode.DataContracts.Common; using Microsoft.DocAsCode.YamlSerialization; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using YamlDotNet.Serialization; [Serializable] public class ItemViewModel : IOverwriteDocumentViewModel { [YamlMember(Alias = Constants.PropertyName.Uid)] [JsonProperty(Constants.PropertyName.Uid)] [MergeOption(MergeOption.MergeKey)] public string Uid { get; set; } [YamlMember(Alias = Constants.PropertyName.CommentId)] [JsonProperty(Constants.PropertyName.CommentId)] public string CommentId { get; set; } [YamlMember(Alias = Constants.PropertyName.Id)] [JsonProperty(Constants.PropertyName.Id)] public string Id { get; set; } [YamlMember(Alias = "isEii")] [JsonProperty("isEii")] public bool IsExplicitInterfaceImplementation { get; set; } [YamlMember(Alias = "isExtensionMethod")] [JsonProperty("isExtensionMethod")] public bool IsExtensionMethod { get; set; } [YamlMember(Alias = Constants.PropertyName.Parent)] [JsonProperty(Constants.PropertyName.Parent)] [UniqueIdentityReference] public string Parent { get; set; } [YamlMember(Alias = Constants.PropertyName.Children)] [MergeOption(MergeOption.Ignore)] // todo : merge more children [JsonProperty(Constants.PropertyName.Children)] [UniqueIdentityReference] public List<string> Children { get; set; } [YamlMember(Alias = Constants.PropertyName.Href)] [JsonProperty(Constants.PropertyName.Href)] public string Href { get; set; } [YamlMember(Alias = "langs")] [JsonProperty("langs")] public string[] SupportedLanguages { get; set; } = new string[] { "csharp", "vb" }; [YamlMember(Alias = Constants.PropertyName.Name)] [JsonProperty(Constants.PropertyName.Name)] public string Name { get; set; } [ExtensibleMember(Constants.ExtensionMemberPrefix.Name)] [JsonIgnore] public SortedList<string, string> Names { get; set; } = new SortedList<string, string>(); [YamlIgnore] [JsonIgnore] public string NameForCSharp { get { Names.TryGetValue("csharp", out string result); return result; } set { if (value == null) { Names.Remove("csharp"); } else { Names["csharp"] = value; } } } [YamlIgnore] [JsonIgnore] public string NameForVB { get { Names.TryGetValue("vb", out string result); return result; } set { if (value == null) { Names.Remove("vb"); } else { Names["vb"] = value; } } } [YamlMember(Alias = Constants.PropertyName.NameWithType)] [JsonProperty(Constants.PropertyName.NameWithType)] public string NameWithType { get; set; } [ExtensibleMember(Constants.ExtensionMemberPrefix.NameWithType)] [JsonIgnore] public SortedList<string, string> NamesWithType { get; set; } = new SortedList<string, string>(); [YamlIgnore] [JsonIgnore] public string NameWithTypeForCSharp { get { Names.TryGetValue("csharp", out string result); return result; } set { if (value == null) { NamesWithType.Remove("csharp"); } else { NamesWithType["csharp"] = value; } } } [YamlIgnore] [JsonIgnore] public string NameWithTypeForVB { get { Names.TryGetValue("vb", out string result); return result; } set { if (value == null) { NamesWithType.Remove("vb"); } else { NamesWithType["vb"] = value; } } } [YamlMember(Alias = Constants.PropertyName.FullName)] [JsonProperty(Constants.PropertyName.FullName)] public string FullName { get; set; } [ExtensibleMember(Constants.ExtensionMemberPrefix.FullName)] [JsonIgnore] public SortedList<string, string> FullNames { get; set; } = new SortedList<string, string>(); [YamlIgnore] [JsonIgnore] public string FullNameForCSharp { get { FullNames.TryGetValue("csharp", out string result); return result; } set { if (value == null) { FullNames.Remove("csharp"); } else { FullNames["csharp"] = value; } } } [YamlIgnore] [JsonIgnore] public string FullNameForVB { get { FullNames.TryGetValue("vb", out string result); return result; } set { if (value == null) { FullNames.Remove("vb"); } else { FullNames["vb"] = value; } } } [YamlMember(Alias = Constants.PropertyName.Type)] [JsonProperty(Constants.PropertyName.Type)] public MemberType? Type { get; set; } [YamlMember(Alias = Constants.PropertyName.Source)] [JsonProperty(Constants.PropertyName.Source)] public SourceDetail Source { get; set; } [YamlMember(Alias = Constants.PropertyName.Documentation)] [JsonProperty(Constants.PropertyName.Documentation)] public SourceDetail Documentation { get; set; } [YamlMember(Alias = Constants.PropertyName.Assemblies)] [MergeOption(MergeOption.Ignore)] // todo : merge more children [JsonProperty(Constants.PropertyName.Assemblies)] public List<string> AssemblyNameList { get; set; } [YamlMember(Alias = Constants.PropertyName.Namespace)] [JsonProperty(Constants.PropertyName.Namespace)] [UniqueIdentityReference] public string NamespaceName { get; set; } [YamlMember(Alias = "summary")] [JsonProperty("summary")] [MarkdownContent] public string Summary { get; set; } [YamlMember(Alias = "remarks")] [JsonProperty("remarks")] [MarkdownContent] public string Remarks { get; set; } [YamlMember(Alias = "example")] [JsonProperty("example")] [MergeOption(MergeOption.Replace)] [MarkdownContent] public List<string> Examples { get; set; } [YamlMember(Alias = "syntax")] [JsonProperty("syntax")] public SyntaxDetailViewModel Syntax { get; set; } [YamlMember(Alias = Constants.PropertyName.Overridden)] [JsonProperty(Constants.PropertyName.Overridden)] [UniqueIdentityReference] public string Overridden { get; set; } [YamlMember(Alias = Constants.PropertyName.Overload)] [JsonProperty(Constants.PropertyName.Overload)] [UniqueIdentityReference] public string Overload { get; set; } [YamlMember(Alias = Constants.PropertyName.Exceptions)] [JsonProperty(Constants.PropertyName.Exceptions)] public List<ExceptionInfo> Exceptions { get; set; } [YamlMember(Alias = "seealso")] [JsonProperty("seealso")] public List<LinkInfo> SeeAlsos { get; set; } [YamlMember(Alias = "see")] [JsonProperty("see")] public List<LinkInfo> Sees { get; set; } [JsonIgnore] [YamlIgnore] [UniqueIdentityReference] public List<string> SeeAlsosUidReference => SeeAlsos?.Where(s => s.LinkType == LinkType.CRef)?.Select(s => s.LinkId).ToList(); [JsonIgnore] [YamlIgnore] [UniqueIdentityReference] public List<string> SeesUidReference => Sees?.Where(s => s.LinkType == LinkType.CRef)?.Select(s => s.LinkId).ToList(); [YamlMember(Alias = Constants.PropertyName.Inheritance)] [MergeOption(MergeOption.Ignore)] [JsonProperty(Constants.PropertyName.Inheritance)] [UniqueIdentityReference] public List<string> Inheritance { get; set; } [YamlMember(Alias = Constants.PropertyName.DerivedClasses)] [MergeOption(MergeOption.Ignore)] [JsonProperty(Constants.PropertyName.DerivedClasses)] [UniqueIdentityReference] public List<string> DerivedClasses { get; set; } [YamlMember(Alias = Constants.PropertyName.Implements)] [MergeOption(MergeOption.Ignore)] // todo : merge more children [JsonProperty(Constants.PropertyName.Implements)] [UniqueIdentityReference] public List<string> Implements { get; set; } [YamlMember(Alias = Constants.PropertyName.InheritedMembers)] [MergeOption(MergeOption.Ignore)] // todo : merge more children [JsonProperty(Constants.PropertyName.InheritedMembers)] [UniqueIdentityReference] public List<string> InheritedMembers { get; set; } [YamlMember(Alias = Constants.PropertyName.ExtensionMethods)] [MergeOption(MergeOption.Ignore)] // todo : merge more children [JsonProperty(Constants.PropertyName.ExtensionMethods)] [UniqueIdentityReference] public List<string> ExtensionMethods { get; set; } [ExtensibleMember(Constants.ExtensionMemberPrefix.Modifiers)] [MergeOption(MergeOption.Ignore)] // todo : merge more children [JsonIgnore] public SortedList<string, List<string>> Modifiers { get; set; } = new SortedList<string, List<string>>(); [YamlMember(Alias = Constants.PropertyName.Conceptual)] [JsonProperty(Constants.PropertyName.Conceptual)] [MarkdownContent] public string Conceptual { get; set; } [YamlMember(Alias = Constants.PropertyName.Platform)] [JsonProperty(Constants.PropertyName.Platform)] [MergeOption(MergeOption.Replace)] public List<string> Platform { get; set; } [YamlMember(Alias = "attributes")] [JsonProperty("attributes")] [MergeOption(MergeOption.Ignore)] public List<AttributeInfo> Attributes { get; set; } [ExtensibleMember] [JsonIgnore] public Dictionary<string, object> Metadata { get; set; } = new Dictionary<string, object>(); [EditorBrowsable(EditorBrowsableState.Never)] [YamlIgnore] [JsonExtensionData] [UniqueIdentityReferenceIgnore] [MarkdownContentIgnore] public CompositeDictionary ExtensionData => CompositeDictionary .CreateBuilder() .Add(Constants.ExtensionMemberPrefix.Name, Names, JTokenConverter.Convert<string>) .Add(Constants.ExtensionMemberPrefix.NameWithType, NamesWithType, JTokenConverter.Convert<string>) .Add(Constants.ExtensionMemberPrefix.FullName, FullNames, JTokenConverter.Convert<string>) .Add(Constants.ExtensionMemberPrefix.Modifiers, Modifiers, JTokenConverter.Convert<List<string>>) .Add(string.Empty, Metadata) .Create(); } }
// 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.Linq; using Xunit; namespace System.MemoryTests { public static partial class MemoryTests { [Fact] public static void EqualityTrue() { int[] a = { 91, 92, 93, 94, 95 }; var left = new Memory<int>(a, 2, 3); var right = new Memory<int>(a, 2, 3); Assert.True(left.Equals(right)); Assert.True(right.Equals(left)); } [Fact] public static void EqualityReflexivity() { int[] a = { 91, 92, 93, 94, 95 }; var left = new Memory<int>(a, 2, 3); Assert.True(left.Equals(left)); } [Fact] public static void EqualityIncludesLength() { int[] a = { 91, 92, 93, 94, 95 }; var left = new Memory<int>(a, 2, 1); var right = new Memory<int>(a, 2, 3); Assert.False(left.Equals(right)); Assert.False(right.Equals(left)); } [Fact] public static void EqualityIncludesBase() { int[] a = { 91, 92, 93, 94, 95 }; var left = new Memory<int>(a, 1, 3); var right = new Memory<int>(a, 2, 3); Assert.False(left.Equals(right)); Assert.False(right.Equals(left)); } [Fact] public static void EqualityComparesRangeNotContent() { var left = new Memory<int>(new int[] { 0, 1, 2 }, 1, 1); var right = new Memory<int>(new int[] { 0, 1, 2 }, 1, 1); Assert.False(left.Equals(right)); Assert.False(right.Equals(left)); } [Fact] public static void EmptyMemoryNotUnified() { var left = new Memory<int>(new int[0]); var right = new Memory<int>(new int[0]); Memory<int> memoryFromNonEmptyArrayButWithZeroLength = new Memory<int>(new int[1] { 123 }).Slice(0, 0); Assert.False(left.Equals(right)); Assert.False(right.Equals(left)); Assert.False(memoryFromNonEmptyArrayButWithZeroLength.Equals(left)); Assert.False(left.Equals(memoryFromNonEmptyArrayButWithZeroLength)); // Empty property is equal left = Memory<int>.Empty; right = Memory<int>.Empty; Assert.True(left.Equals(right)); Assert.True(right.Equals(left)); } [Fact] public static void MemoryCanBeBoxed() { Memory<byte> memory = Memory<byte>.Empty; object memoryAsObject = memory; Assert.True(memory.Equals(memoryAsObject)); ReadOnlyMemory<byte> readOnlyMemory = ReadOnlyMemory<byte>.Empty; object readOnlyMemoryAsObject = readOnlyMemory; Assert.True(readOnlyMemory.Equals(readOnlyMemoryAsObject)); Assert.False(memory.Equals(new object())); Assert.False(readOnlyMemory.Equals(new object())); Assert.False(memory.Equals((object)(new Memory<byte>(new byte[] { 1, 2 })))); Assert.False(readOnlyMemory.Equals((object)(new ReadOnlyMemory<byte>(new byte[] { 1, 2 })))); Assert.True(memory.Equals(readOnlyMemoryAsObject)); Assert.True(readOnlyMemory.Equals(memoryAsObject)); } [Fact] public static void DefaultMemoryCanBeBoxed() { Memory<byte> memory = default; object memoryAsObject = memory; Assert.True(memory.Equals(memoryAsObject)); ReadOnlyMemory<byte> readOnlyMemory = default; object readOnlyMemoryAsObject = readOnlyMemory; Assert.True(readOnlyMemory.Equals(readOnlyMemoryAsObject)); Assert.True(memory.Equals(readOnlyMemoryAsObject)); Assert.True(readOnlyMemory.Equals(memoryAsObject)); } [Theory] [MemberData(nameof(ValidArraySegments))] public static void MemoryReferencingSameMemoryAreEqualInEveryAspect(byte[] bytes, int start, int length) { var memory = new Memory<byte>(bytes, start, length); var pointingToSameMemory = new Memory<byte>(bytes, start, length); Memory<byte> structCopy = memory; Assert.True(memory.Equals(pointingToSameMemory)); Assert.True(pointingToSameMemory.Equals(memory)); Assert.True(memory.Equals(structCopy)); Assert.True(structCopy.Equals(memory)); } [Theory] [MemberData(nameof(FullArraySegments))] public static void MemoryArrayEquivalenceAndImplicitCastsAreEqual(byte[] bytes) { var memory = new Memory<byte>(bytes); var readOnlyMemory = new ReadOnlyMemory<byte>(bytes); ReadOnlyMemory<byte> implicitReadOnlyMemory = memory; Memory<byte> implicitMemoryArray = bytes; ReadOnlyMemory<byte> implicitReadOnlyMemoryArray = bytes; Assert.True(memory.Equals(bytes)); Assert.True(readOnlyMemory.Equals(bytes)); Assert.True(implicitReadOnlyMemory.Equals(bytes)); Assert.True(implicitMemoryArray.Equals(bytes)); Assert.True(implicitReadOnlyMemoryArray.Equals(bytes)); Assert.True(readOnlyMemory.Equals(memory)); Assert.True(implicitReadOnlyMemory.Equals(memory)); Assert.True(implicitMemoryArray.Equals(memory)); Assert.True(implicitReadOnlyMemoryArray.Equals(memory)); Assert.True(memory.Equals(readOnlyMemory)); Assert.True(implicitReadOnlyMemory.Equals(readOnlyMemory)); Assert.True(implicitMemoryArray.Equals(readOnlyMemory)); Assert.True(implicitReadOnlyMemoryArray.Equals(readOnlyMemory)); Assert.True(memory.Equals(implicitMemoryArray)); Assert.True(readOnlyMemory.Equals(implicitMemoryArray)); Assert.True(implicitReadOnlyMemory.Equals(implicitMemoryArray)); Assert.True(implicitReadOnlyMemoryArray.Equals(implicitMemoryArray)); Assert.True(memory.Equals(implicitReadOnlyMemory)); Assert.True(readOnlyMemory.Equals(implicitReadOnlyMemory)); Assert.True(implicitMemoryArray.Equals(implicitReadOnlyMemory)); Assert.True(implicitReadOnlyMemoryArray.Equals(implicitReadOnlyMemory)); Assert.True(memory.Equals(implicitReadOnlyMemoryArray)); Assert.True(readOnlyMemory.Equals(implicitReadOnlyMemoryArray)); Assert.True(implicitReadOnlyMemory.Equals(implicitReadOnlyMemoryArray)); Assert.True(implicitMemoryArray.Equals(implicitReadOnlyMemoryArray)); } [Theory] [MemberData(nameof(ValidArraySegments))] public static void RangedMemoryEquivalenceAndImplicitCastsAreEqual(byte[] bytes, int start, int length) { var memory = new Memory<byte>(bytes, start, length); var readOnlyMemory = new ReadOnlyMemory<byte>(bytes, start, length); ReadOnlyMemory<byte> implicitReadOnlyMemory = memory; Assert.True(readOnlyMemory.Equals(memory)); Assert.True(implicitReadOnlyMemory.Equals(memory)); Assert.True(memory.Equals(readOnlyMemory)); Assert.True(implicitReadOnlyMemory.Equals(readOnlyMemory)); Assert.True(memory.Equals(implicitReadOnlyMemory)); Assert.True(readOnlyMemory.Equals(implicitReadOnlyMemory)); } [Theory] [MemberData(nameof(ValidArraySegments))] public static void MemoryOfEqualValuesAreNotEqual(byte[] bytes, int start, int length) { byte[] bytesCopy = bytes.ToArray(); var memory = new Memory<byte>(bytes, start, length); var ofSameValues = new Memory<byte>(bytesCopy, start, length); Assert.False(memory.Equals(ofSameValues)); Assert.False(ofSameValues.Equals(memory)); } [Theory] [MemberData(nameof(ValidArraySegments))] public static void MemoryOfDifferentValuesAreNotEqual(byte[] bytes, int start, int length) { byte[] differentBytes = bytes.Select(value => ++value).ToArray(); var memory = new Memory<byte>(bytes, start, length); var ofDifferentValues = new Memory<byte>(differentBytes, start, length); Assert.False(memory.Equals(ofDifferentValues)); Assert.False(ofDifferentValues.Equals(memory)); } public static IEnumerable<object[]> ValidArraySegments { get { return new List<object[]> { new object[] { new byte[1] { 0 }, 0, 1}, new object[] { new byte[2] { 0, 0 }, 0, 2}, new object[] { new byte[2] { 0, 0 }, 0, 1}, new object[] { new byte[2] { 0, 0 }, 1, 1}, new object[] { new byte[3] { 0, 0, 0 }, 0, 3}, new object[] { new byte[3] { 0, 0, 0 }, 0, 2}, new object[] { new byte[3] { 0, 0, 0 }, 1, 2}, new object[] { new byte[3] { 0, 0, 0 }, 1, 1}, new object[] { Enumerable.Range(0, 100000).Select(i => (byte)i).ToArray(), 0, 100000 } }; } } public static IEnumerable<object[]> FullArraySegments { get { return new List<object[]> { new object[] { new byte[1] { 0 } }, new object[] { new byte[2] { 0, 0 } }, new object[] { new byte[3] { 0, 0, 0 } }, new object[] { Enumerable.Range(0, 100000).Select(i => (byte)i).ToArray() } }; } } } }
// 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.IO; using System.Xml; using Microsoft.Test.ModuleCore; namespace CoreXml.Test.XLinq { public partial class FunctionalTests : TestModule { public partial class XNodeReaderTests : XLinqTestCase { //[TestCase(Name = "ReadToDescendant", Desc = "ReadToDescendant")] public partial class TCReadToDescendant : BridgeHelpers { #region XMLSTR private string _xmlStr = @"<?xml version='1.0'?> <root><!--Comment--> <elem><!-- Comment --> <child1 att='1'><?pi target?> <child2 xmlns='child2'> <child3/> blahblahblah<![CDATA[ blah ]]> <child4/> </child2> <?pi target1?> </child1> </elem> <elem att='1'> <child1 att='1'> <child2 xmlns='child2'> <child3/> blahblahblah <child4/> </child2> <?pi target1?> </child1> </elem> <elem xmlns='elem'> <child1 att='1'> <child2 xmlns='child2'> <child3/> blahblahblah2 <child4/> </child2> </child1> </elem> <elem xmlns='elem' att='1'> <child1 att='1'> <child2 xmlns='child2'> <child3/> blahblahblah2 <child4/> </child2> </child1> </elem> <e:elem xmlns:e='elem2'> <e:child1 att='1'> <e:child2 xmlns='child2'> <e:child3/> blahblahblah2 <e:child4/> </e:child2> </e:child1> </e:elem> <e:elem xmlns:e='elem2' att='1'> <e:child1 att='1'> <e:child2 xmlns='child2'> <e:child3/> blahblahblah2 <e:child4/> </e:child2> </e:child1> </e:elem> </root>"; #endregion //[Variation("Simple positive test", Priority = 0, Params = new object[] { "NNS" })] //[Variation("Simple positive test", Priority = 0, Params = new object[] { "DNS" })] //[Variation("Simple positive test", Priority = 0, Params = new object[] { "NS" })] public void v() { string type = Variation.Params[0].ToString(); XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "root"); switch (type) { case "NNS": DataReader.ReadToDescendant("elem"); if (DataReader.HasAttributes) { TestLog.WriteLine("Positioned on wrong element"); TestLog.WriteIgnore(DataReader.ReadInnerXml() + "\n"); throw new TestException(TestResult.Failed, ""); } while (DataReader.Read()) ; DataReader.Dispose(); return; case "DNS": DataReader.ReadToDescendant("elem", "elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns") == null) { TestLog.WriteLine("Positioned on wrong element, not on DNS"); throw new TestException(TestResult.Failed, ""); } } while (DataReader.Read()) ; DataReader.Dispose(); return; case "NS": DataReader.ReadToDescendant("e:elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns:e") == null) { TestLog.WriteLine("Positioned on wrong element, not on NS"); throw new TestException(TestResult.Failed, ""); } } while (DataReader.Read()) ; DataReader.Dispose(); return; default: throw new TestFailedException("Error in Test type"); } } //[Variation("Read on a deep tree atleast more than 4K boundary", Priority = 2)] public void v2() { ManagedNodeWriter mnw = new ManagedNodeWriter(); mnw.PutPattern("X"); int count = 0; do { mnw.PutPattern("E/"); count++; } while (mnw.GetNodes().Length < 4096); mnw.PutText("<a/>"); mnw.Finish(); XmlReader DataReader = GetReader(new StringReader(mnw.GetNodes())); PositionOnElement(DataReader, "ELEMENT_1"); DataReader.ReadToDescendant("a"); TestLog.Compare(DataReader.Depth, count, "Depth is not correct"); TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "Nodetype is not correct"); while (DataReader.Read()) ; DataReader.Dispose(); } //[Variation("Read on descendant with same names", Priority = 1, Params = new object[] { "NNS" })] //[Variation("Read on descendant with same names", Priority = 1, Params = new object[] { "DNS" })] //[Variation("Read on descendant with same names", Priority = 1, Params = new object[] { "NS" })] public void v3() { string type = Variation.Params[0].ToString(); XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "root"); // Doing a sequential read. switch (type) { case "NNS": DataReader.ReadToDescendant("elem"); int depth = DataReader.Depth; if (DataReader.HasAttributes) { TestLog.WriteLine("Positioned on wrong element"); throw new TestException(TestResult.Failed, ""); } TestLog.Compare(DataReader.ReadToDescendant("elem"), false, "There are no more descendants"); TestLog.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type"); while (DataReader.Read()) ; DataReader.Dispose(); return; case "DNS": DataReader.ReadToDescendant("elem", "elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns") == null) { TestLog.WriteLine("Positioned on wrong element, not on DNS"); throw new TestException(TestResult.Failed, ""); } } TestLog.Compare(DataReader.ReadToDescendant("elem", "elem"), false, "There are no more descendants"); TestLog.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type"); while (DataReader.Read()) ; DataReader.Dispose(); return; case "NS": DataReader.ReadToDescendant("e:elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns:e") == null) { TestLog.WriteLine("Positioned on wrong element, not on DNS"); throw new TestException(TestResult.Failed, ""); } } TestLog.Compare(DataReader.ReadToDescendant("e:elem"), false, "There are no more descendants"); TestLog.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type"); while (DataReader.Read()) ; DataReader.Dispose(); return; default: throw new TestFailedException("Error in Test type"); } } //[Variation("If name not found, stop at end element of the subtree", Priority = 1)] public void v4() { XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "elem"); TestLog.Compare(DataReader.ReadToDescendant("abc"), false, "Reader returned true for an invalid name"); TestLog.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type"); DataReader.Read(); TestLog.Compare(DataReader.ReadToDescendant("abc", "elem"), false, "reader returned true for an invalid name,ns combination"); while (DataReader.Read()) ; DataReader.Dispose(); } //[Variation("Positioning on a level and try to find the name which is on a level higher", Priority = 1)] public void v5() { XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "child3"); TestLog.Compare(DataReader.ReadToDescendant("child1"), false, "Reader returned true for an invalid name"); TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "Wrong node type"); TestLog.Compare(DataReader.LocalName, "child3", "Wrong name"); PositionOnElement(DataReader, "child3"); TestLog.Compare(DataReader.ReadToDescendant("child2", "child2"), false, "Reader returned true for an invalid name,ns"); TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "Wrong node type for name,ns"); while (DataReader.Read()) ; DataReader.Dispose(); } //[Variation("Read to Descendant on one level and again to level below it", Priority = 1)] public void v6() { XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "root"); TestLog.Compare(DataReader.ReadToDescendant("elem"), true, "Cant find elem"); TestLog.Compare(DataReader.ReadToDescendant("child1"), true, "Cant find child1"); TestLog.Compare(DataReader.ReadToDescendant("child2"), true, "Cant find child2"); TestLog.Compare(DataReader.ReadToDescendant("child3"), true, "Cant find child3"); TestLog.Compare(DataReader.ReadToDescendant("child4"), false, "shouldnt find child4"); TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "Not on EndElement"); DataReader.Read(); TestLog.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on Element"); while (DataReader.Read()) ; DataReader.Dispose(); } //[Variation("Read to Descendant on one level and again to level below it, with namespace", Priority = 1)] public void v7() { XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "root"); TestLog.Compare(DataReader.ReadToDescendant("elem", "elem"), true, "Cant find elem"); TestLog.Compare(DataReader.ReadToDescendant("child1", "elem"), true, "Cant find child1"); TestLog.Compare(DataReader.ReadToDescendant("child2", "child2"), true, "Cant find child2"); TestLog.Compare(DataReader.ReadToDescendant("child3", "child2"), true, "Cant find child3"); TestLog.Compare(DataReader.ReadToDescendant("child4", "child2"), false, "shouldnt find child4"); TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "Not on EndElement"); DataReader.Read(); TestLog.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on Element"); while (DataReader.Read()) ; DataReader.Dispose(); } //[Variation("Read to Descendant on one level and again to level below it, with prefix", Priority = 1)] public void v8() { XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "root"); TestLog.Compare(DataReader.ReadToDescendant("e:elem"), true, "Cant find elem"); TestLog.Compare(DataReader.ReadToDescendant("e:child1"), true, "Cant find child1"); TestLog.Compare(DataReader.ReadToDescendant("e:child2"), true, "Cant find child2"); TestLog.Compare(DataReader.ReadToDescendant("e:child3"), true, "Cant find child3"); TestLog.Compare(DataReader.ReadToDescendant("e:child4"), false, "shouldnt find child4"); TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "Not on EndElement"); DataReader.Read(); TestLog.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on Element"); while (DataReader.Read()) ; DataReader.Dispose(); } //[Variation("Multiple Reads to children and then next siblings, NNS", Priority = 2)] public void v9() { XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "root"); TestLog.Compare(DataReader.ReadToDescendant("elem"), true, "Read fails elem"); TestLog.Compare(DataReader.ReadToDescendant("child3"), true, "Read fails child3"); TestLog.Compare(DataReader.ReadToNextSibling("child4"), true, "Read fails child4"); while (DataReader.Read()) ; DataReader.Dispose(); } //[Variation("Multiple Reads to children and then next siblings, DNS", Priority = 2)] public void v10() { XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "root"); TestLog.Compare(DataReader.ReadToDescendant("elem", "elem"), true, "Read fails elem"); TestLog.Compare(DataReader.ReadToDescendant("child3", "child2"), true, "Read fails child3"); TestLog.Compare(DataReader.ReadToNextSibling("child4", "child2"), true, "Read fails child4"); while (DataReader.Read()) ; DataReader.Dispose(); } //[Variation("Multiple Reads to children and then next siblings, NS", Priority = 2)] public void v11() { XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "root"); TestLog.Compare(DataReader.ReadToDescendant("e:elem"), true, "Read fails elem"); TestLog.Compare(DataReader.ReadToDescendant("e:child3"), true, "Read fails child3"); TestLog.Compare(DataReader.ReadToNextSibling("e:child4"), true, "Read fails child4"); while (DataReader.Read()) ; DataReader.Dispose(); } //[Variation("Call from different nodetypes", Priority = 1)] public void v12() { XmlReader DataReader = GetReader(new StringReader(_xmlStr)); while (DataReader.Read()) { if (DataReader.NodeType != XmlNodeType.Element) { TestLog.Compare(DataReader.ReadToDescendant("child1"), false, "Fails on node"); } else { if (DataReader.HasAttributes) { while (DataReader.MoveToNextAttribute()) { TestLog.Compare(DataReader.ReadToDescendant("abc"), false, "Fails on attribute node"); } } } } DataReader.Dispose(); } //[Variation("Only child has namespaces and read to it", Priority = 2)] public void v14() { XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "root"); TestLog.Compare(DataReader.ReadToDescendant("child2", "child2"), true, "Fails on attribute node"); DataReader.Dispose(); } //[Variation("Pass null to both arguments throws ArgumentException", Priority = 2)] public void v15() { XmlReader DataReader = GetReader(new StringReader("<root><b/></root>")); DataReader.Read(); try { DataReader.ReadToDescendant(null); } catch (ArgumentNullException) { } try { DataReader.ReadToDescendant("b", null); } catch (ArgumentNullException) { } while (DataReader.Read()) ; DataReader.Dispose(); } //[Variation("Different names, same uri works correctly", Priority = 2)] public void v17() { XmlReader DataReader = GetReader(new StringReader("<root><child1 xmlns='foo'/>blah<child1 xmlns='bar'>blah</child1></root>")); DataReader.Read(); DataReader.ReadToDescendant("child1", "bar"); TestLog.Compare(DataReader.IsEmptyElement, false, "Not on the correct node"); while (DataReader.Read()) ; DataReader.Dispose(); } //[Variation("On Root Node", Priority = 0, Params = new object[] { "NNS" })] //[Variation("On Root Node", Priority = 0, Params = new object[] { "DNS" })] //[Variation("On Root Node", Priority = 0, Params = new object[] { "NS" })] public void v18() { string type = Variation.Params[0].ToString(); XmlReader DataReader = GetReader(new StringReader(_xmlStr)); switch (type) { case "NNS": DataReader.ReadToDescendant("elem"); if (DataReader.HasAttributes) { TestLog.WriteLine("Positioned on wrong element"); TestLog.WriteIgnore(DataReader.ReadInnerXml() + "\n"); throw new TestException(TestResult.Failed, ""); } while (DataReader.Read()) ; DataReader.Dispose(); return; case "DNS": DataReader.ReadToDescendant("elem", "elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns") == null) { TestLog.WriteLine("Positioned on wrong element, not on DNS"); throw new TestException(TestResult.Failed, ""); } } while (DataReader.Read()) ; DataReader.Dispose(); return; case "NS": DataReader.ReadToDescendant("e:elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns:e") == null) { TestLog.WriteLine("Positioned on wrong element, not on NS"); throw new TestException(TestResult.Failed, ""); } } while (DataReader.Read()) ; DataReader.Dispose(); return; default: throw new TestFailedException("Error in Test type"); } } //[Variation("427176 Assertion failed when call XmlReader.ReadToDescendant() for non-existing node", Priority = 1)] public void v19() { XmlReader DataReader = GetReader(new StringReader("<a>b</a>")); TestLog.Compare(DataReader.ReadToDescendant("foo"), false, "Should fail without assert"); DataReader.Dispose(); } } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; namespace QuantConnect { /// <summary> /// Markets Collection: Soon to be expanded to a collection of items specifying the market hour, timezones and country codes. /// </summary> public static class Market { // the upper bound (non-inclusive) for market identifiers private const int MaxMarketIdentifier = 1000; private static readonly object _lock = new object(); private static readonly Dictionary<string, int> Markets = new Dictionary<string, int>(); private static readonly Dictionary<int, string> ReverseMarkets = new Dictionary<int, string>(); private static readonly IEnumerable<Tuple<string, int>> HardcodedMarkets = new List<Tuple<string, int>> { Tuple.Create("empty", 0), Tuple.Create(USA, 1), Tuple.Create(FXCM, 2), Tuple.Create(Oanda, 3), Tuple.Create(Dukascopy, 4), Tuple.Create(Bitfinex, 5), Tuple.Create(Globex, 6), Tuple.Create(NYMEX, 7), Tuple.Create(CBOT, 8), Tuple.Create(ICE, 9), Tuple.Create(CBOE, 10), Tuple.Create(India, 11), Tuple.Create(GDAX, 12), Tuple.Create(Kraken, 13), Tuple.Create(Bittrex, 14), Tuple.Create(Bithumb, 15), Tuple.Create(Binance, 16), Tuple.Create(Poloniex, 17), Tuple.Create(Coinone, 18), Tuple.Create(HitBTC, 19), Tuple.Create(OkCoin, 20), Tuple.Create(Bitstamp, 21), Tuple.Create(COMEX, 22), Tuple.Create(CME, 23), Tuple.Create(SGX, 24), Tuple.Create(HKFE, 25), }; static Market() { // initialize our maps foreach (var market in HardcodedMarkets) { Markets[market.Item1] = market.Item2; ReverseMarkets[market.Item2] = market.Item1; } } /// <summary> /// USA Market /// </summary> public const string USA = "usa"; /// <summary> /// Oanda Market /// </summary> public const string Oanda = "oanda"; /// <summary> /// FXCM Market Hours /// </summary> public const string FXCM = "fxcm"; /// <summary> /// Dukascopy Market /// </summary> public const string Dukascopy = "dukascopy"; /// <summary> /// Bitfinex market /// </summary> public const string Bitfinex = "bitfinex"; // Futures exchanges /// <summary> /// CME Globex /// </summary> public const string Globex = "cmeglobex"; /// <summary> /// NYMEX /// </summary> public const string NYMEX = "nymex"; /// <summary> /// CBOT /// </summary> public const string CBOT = "cbot"; /// <summary> /// ICE /// </summary> public const string ICE = "ice"; /// <summary> /// CBOE /// </summary> public const string CBOE = "cboe"; /// <summary> /// NSE - National Stock Exchange /// </summary> public const string India = "india"; /// <summary> /// Comex /// </summary> public const string COMEX = "comex"; /// <summary> /// CME /// </summary> public const string CME = "cme"; /// <summary> /// Singapore Exchange /// </summary> public const string SGX = "sgx"; /// <summary> /// Hong Kong Exchange /// </summary> public const string HKFE = "hkfe"; /// <summary> /// GDAX /// </summary> public const string GDAX = "gdax"; /// <summary> /// Kraken /// </summary> public const string Kraken = "kraken"; /// <summary> /// Bitstamp /// </summary> public const string Bitstamp = "bitstamp"; /// <summary> /// OkCoin /// </summary> public const string OkCoin = "okcoin"; /// <summary> /// Bithumb /// </summary> public const string Bithumb = "bithumb"; /// <summary> /// Binance /// </summary> public const string Binance = "binance"; /// <summary> /// Poloniex /// </summary> public const string Poloniex = "poloniex"; /// <summary> /// Coinone /// </summary> public const string Coinone = "coinone"; /// <summary> /// HitBTC /// </summary> public const string HitBTC = "hitbtc"; /// <summary> /// Bittrex /// </summary> public const string Bittrex = "bittrex"; /// <summary> /// Adds the specified market to the map of available markets with the specified identifier. /// </summary> /// <param name="market">The market string to add</param> /// <param name="identifier">The identifier for the market, this value must be positive and less than 1000</param> public static void Add(string market, int identifier) { if (identifier >= MaxMarketIdentifier) { throw new ArgumentOutOfRangeException(nameof(identifier), $"The market identifier is limited to positive values less than {MaxMarketIdentifier.ToStringInvariant()}." ); } market = market.ToLowerInvariant(); // we lock since we don't want multiple threads getting these two dictionaries out of sync lock (_lock) { int marketIdentifier; if (Markets.TryGetValue(market, out marketIdentifier) && identifier != marketIdentifier) { throw new ArgumentException( $"Attempted to add an already added market with a different identifier. Market: {market}" ); } string existingMarket; if (ReverseMarkets.TryGetValue(identifier, out existingMarket)) { throw new ArgumentException( "Attempted to add a market identifier that is already in use. " + $"New Market: {market} Existing Market: {existingMarket}" ); } // update our maps Markets[market] = identifier; ReverseMarkets[identifier] = market; } } /// <summary> /// Gets the market code for the specified market. Returns <c>null</c> if the market is not found /// </summary> /// <param name="market">The market to check for (case sensitive)</param> /// <returns>The internal code used for the market. Corresponds to the value used when calling <see cref="Add"/></returns> public static int? Encode(string market) { lock (_lock) { int code; return !Markets.TryGetValue(market, out code) ? (int?) null : code; } } /// <summary> /// Gets the market string for the specified market code. /// </summary> /// <param name="code">The market code to be decoded</param> /// <returns>The string representation of the market, or null if not found</returns> public static string Decode(int code) { lock (_lock) { string market; return !ReverseMarkets.TryGetValue(code, out market) ? null : market; } } } }
// F#: Added cast where initializing variable with subclass // Removed test for 'sealed' classes using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Specialized; using System.IO; using System.Reflection; using Microsoft.Samples.CodeDomTestSuite; public class ClassTest : CodeDomTestTree { public override TestTypes TestType { get { return TestTypes.Everett; } } public override bool ShouldCompile { get { return true; } } public override bool ShouldVerify { get { return true; } } public override string Name { get { return "ClassTest"; } } public override string Description { get { return "Tests classes."; } } public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { CodeNamespace nspace = new CodeNamespace ("NSPC"); nspace.Imports.Add (new CodeNamespaceImport ("System")); cu.Namespaces.Add (nspace); cu.ReferencedAssemblies.Add ("System.Windows.Forms.dll"); CodeTypeDeclaration cd = new CodeTypeDeclaration ("TestingClass"); cd.IsClass = true; nspace.Types.Add (cd); CodeMemberMethod cmm; CodeMethodInvokeExpression methodinvoke; // GENERATES (C#): // public int CallingPublicNestedScenario(int i) { // PublicNestedClassA.PublicNestedClassB2.PublicNestedClassC t = // new PublicNestedClassA.PublicNestedClassB2.PublicNestedClassC(); // return t.publicNestedClassesMethod(i); // } if (Supports (provider, GeneratorSupport.NestedTypes)) { AddScenario ("CheckCallingPublicNestedScenario"); cmm = new CodeMemberMethod (); cmm.Name = "CallingPublicNestedScenario"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Statements.Add (new CodeVariableDeclarationStatement (new CodeTypeReference ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"), "t", new CodeObjectCreateExpression (new CodeTypeReference ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC")))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("t"), "publicNestedClassesMethod", new CodeArgumentReferenceExpression ("i")))); cd.Members.Add (cmm); AddScenario ("CheckCallingPrivateNestedScenario"); cmm = new CodeMemberMethod (); cmm.Name = "CallingPrivateNestedScenario"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Statements.Add (new CodeVariableDeclarationStatement (new CodeTypeReference ("PrivateNestedClassA"), "t", new CodeObjectCreateExpression (new CodeTypeReference ("PrivateNestedClassA")))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("t"), "TestPrivateNestedClass", new CodeArgumentReferenceExpression ("i")))); cd.Members.Add (cmm); } // GENERATES (C#): // public int CallingAbstractScenario(int i) { // InheritAbstractClass t = new InheritAbstractClass(); // return t.AbstractMethod(i); // } AddScenario ("CheckCallingAbstractScenario"); cmm = new CodeMemberMethod (); cmm.Name = "CallingAbstractScenario"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Statements.Add (new CodeVariableDeclarationStatement ("InheritAbstractClass", "t", new CodeObjectCreateExpression ("InheritAbstractClass"))); methodinvoke = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("t"), "AbstractMethod"); methodinvoke.Parameters.Add (new CodeArgumentReferenceExpression ("i")); cmm.Statements.Add (new CodeMethodReturnStatement (methodinvoke)); cd.Members.Add (cmm); if (Supports (provider, GeneratorSupport.DeclareInterfaces)) { // testing multiple interface implementation class // GENERATES (C#): // public int TestMultipleInterfaces(int i) { // TestMultipleInterfaceImp t = new TestMultipleInterfaceImp(); // InterfaceA interfaceAobject = ((InterfaceA)(t)); // InterfaceB interfaceBobject = ((InterfaceB)(t)); // return (interfaceAobject.InterfaceMethod(i) - interfaceBobject.InterfaceMethod(i)); // } if (Supports (provider, GeneratorSupport.MultipleInterfaceMembers)) { cmm = new CodeMemberMethod(); cmm.Name = "TestMultipleInterfaces"; cmm.ReturnType = new CodeTypeReference(typeof(int)); cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i")); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Statements.Add(new CodeVariableDeclarationStatement("TestMultipleInterfaceImp","t",new CodeObjectCreateExpression("TestMultipleInterfaceImp"))); cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceA", "interfaceAobject", new CodeCastExpression("InterfaceA" , new CodeVariableReferenceExpression("t")))); cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceB", "interfaceBobject", new CodeCastExpression("InterfaceB" , new CodeVariableReferenceExpression("t")))); methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceAobject") , "InterfaceMethod"); methodinvoke.Parameters.Add(new CodeArgumentReferenceExpression("i")); CodeMethodInvokeExpression methodinvoke2 = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceBobject") , "InterfaceMethod"); methodinvoke2.Parameters.Add(new CodeArgumentReferenceExpression("i")); cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression( methodinvoke , CodeBinaryOperatorType.Subtract, methodinvoke2))); cd.Members.Add(cmm); } // testing single interface implementation // GENERATES (C#): // public int TestSingleInterface(int i) { // TestMultipleInterfaceImp t = new TestMultipleInterfaceImp(); // return t.InterfaceMethod(i); // } AddScenario ("CheckTestSingleInterface"); cmm = new CodeMemberMethod (); cmm.Name = "TestSingleInterface"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Statements.Add (new CodeVariableDeclarationStatement ("TestSingleInterfaceImp", "t", new CodeObjectCreateExpression ("TestSingleInterfaceImp"))); methodinvoke = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("t") , "InterfaceMethod"); methodinvoke.Parameters.Add (new CodeArgumentReferenceExpression ("i")); cmm.Statements.Add (new CodeMethodReturnStatement (methodinvoke)); cd.Members.Add (cmm); } // similar to the 'new' test, write a method to complete testing of the 'override' scenario // GENERATES (C#): // public int CallingOverrideScenario(int i) { // ClassWVirtualMethod t = new ClassWOverrideMethod(); // return t.VirtualMethod(i); // } AddScenario ("CheckCallingOverrideScenario"); cmm = new CodeMemberMethod (); cmm.Name = "CallingOverrideScenario"; cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Statements.Add (new CodeVariableDeclarationStatement ("ClassWVirtualMethod", "t", new CodeCastExpression(new CodeTypeReference("ClassWVirtualMethod"), new CodeObjectCreateExpression ("ClassWOverrideMethod")))); methodinvoke = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("t"), "VirtualMethod"); methodinvoke.Parameters.Add (new CodeArgumentReferenceExpression ("i")); cmm.Statements.Add (new CodeMethodReturnStatement (methodinvoke)); cd.Members.Add (cmm); // declare a base class // GENERATES (C#): // public class ClassWVirtualMethod { // public virtual int VirtualMethod(int a) { // return a; // } // } cd = new CodeTypeDeclaration ("ClassWVirtualMethod"); cd.IsClass = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "VirtualMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); cd.Members.Add (cmm); // inherit the base class // GENERATES (C#): // public class ClassWMethod : ClassWVirtualMethod { // } cd = new CodeTypeDeclaration ("ClassWMethod"); cd.BaseTypes.Add (new CodeTypeReference ("ClassWVirtualMethod")); cd.IsClass = true; nspace.Types.Add (cd); // inheritance the base class with override method // GENERATES (C#): // public class ClassWOverrideMethod : ClassWVirtualMethod { // public override int VirtualMethod(int a) { // return (2 * a); // } // } cd = new CodeTypeDeclaration ("ClassWOverrideMethod"); cd.BaseTypes.Add (new CodeTypeReference ("ClassWVirtualMethod")); cd.IsClass = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "VirtualMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression ( new CodePrimitiveExpression (2), CodeBinaryOperatorType.Multiply , new CodeArgumentReferenceExpression ("a")))); cd.Members.Add (cmm); if (Supports (provider, GeneratorSupport.DeclareInterfaces)) { // ******** implement a single public interface *********** // declare an interface // GENERATES (C#): // public interface InterfaceA { // int InterfaceMethod(int a); // } cd = new CodeTypeDeclaration ("InterfaceA"); cd.IsInterface = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Attributes = MemberAttributes.Public; cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cd.Members.Add (cmm); // implement the interface // GENERATES (C#): // public class TestSingleInterfaceImp : InterfaceA { // public virtual int InterfaceMethod(int a) { // return a; // } // } cd = new CodeTypeDeclaration ("TestSingleInterfaceImp"); cd.BaseTypes.Add (new CodeTypeReference ("System.Object")); cd.BaseTypes.Add (new CodeTypeReference ("InterfaceA")); cd.IsClass = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.ImplementationTypes.Add (new CodeTypeReference ("InterfaceA")); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); cd.Members.Add (cmm); // ********implement two interfaces with overloading method name******* // declare the second interface // GENERATES (C#): // public interface InterfaceB { // int InterfaceMethod(int a); // } cd = new CodeTypeDeclaration ("InterfaceB"); cd.IsInterface = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "InterfaceMethod"; cmm.Attributes = MemberAttributes.Public; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cd.Members.Add (cmm); // implement both of the interfaces // GENERATES (C#): // public class TestMultipleInterfaceImp : InterfaceB, InterfaceA { // public int InterfaceMethod(int a) { // return a; // } // } if (Supports (provider, GeneratorSupport.MultipleInterfaceMembers)) { AddScenario ("CheckTestMultipleInterfaces"); cd = new CodeTypeDeclaration ("TestMultipleInterfaceImp"); cd.BaseTypes.Add (new CodeTypeReference ("System.Object")); cd.BaseTypes.Add (new CodeTypeReference ("InterfaceB")); cd.BaseTypes.Add (new CodeTypeReference ("InterfaceA")); cd.IsClass = true; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.ImplementationTypes.Add (new CodeTypeReference ("InterfaceA")); cmm.ImplementationTypes.Add (new CodeTypeReference ("InterfaceB")); cmm.Name = "InterfaceMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); cd.Members.Add (cmm); } } if (Supports (provider, GeneratorSupport.NestedTypes)) { // *********** public nested classes ************************* // GENERATES (C#): // public class PublicNestedClassA { // public class PublicNestedClassB1 { // } // public class PublicNestedClassB2 { // public class PublicNestedClassC { // public int publicNestedClassesMethod(int a) { // return a; // } // } // } // } cd = new CodeTypeDeclaration ("PublicNestedClassA"); cd.IsClass = true; nspace.Types.Add (cd); CodeTypeDeclaration nestedClass = new CodeTypeDeclaration ("PublicNestedClassB1"); nestedClass.IsClass = true; nestedClass.TypeAttributes = TypeAttributes.NestedPublic; cd.Members.Add (nestedClass); nestedClass = new CodeTypeDeclaration ("PublicNestedClassB2"); nestedClass.TypeAttributes = TypeAttributes.NestedPublic; nestedClass.IsClass = true; cd.Members.Add (nestedClass); CodeTypeDeclaration innerNestedClass = new CodeTypeDeclaration ("PublicNestedClassC"); innerNestedClass.TypeAttributes = TypeAttributes.NestedPublic; innerNestedClass.IsClass = true; nestedClass.Members.Add (innerNestedClass); cmm = new CodeMemberMethod (); cmm.Name = "publicNestedClassesMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); innerNestedClass.Members.Add (cmm); // *********** private nested classes ************************* // GENERATES (C#): // public class PrivateNestedClassA { // public int TestPrivateNestedClass(int i) { // return PrivateNestedClassB.PrivateNestedClassesMethod(i); // } // private class PrivateNestedClassB { // public int PrivateNestedClassesMethod(int a) { // return a; // } // } // } cd = new CodeTypeDeclaration ("PrivateNestedClassA"); cd.IsClass = true; nspace.Types.Add (cd); AddScenario ("CantFindPrivateNestedClass"); nestedClass = new CodeTypeDeclaration ("PrivateNestedClassB"); nestedClass.IsClass = true; nestedClass.TypeAttributes = TypeAttributes.NestedPrivate; cd.Members.Add (nestedClass); cmm = new CodeMemberMethod (); cmm.Name = "PrivateNestedClassesMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a")); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); nestedClass.Members.Add (cmm); // test private, nested classes cmm = new CodeMemberMethod (); cmm.Name = "TestPrivateNestedClass"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.Attributes = (cmm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; cmm.Statements.Add (new CodeVariableDeclarationStatement (new CodeTypeReference ("PrivateNestedClassB"), "objB")); cmm.Statements.Add (new CodeAssignStatement (new CodeVariableReferenceExpression ("objB"), new CodeObjectCreateExpression (new CodeTypeReference ("PrivateNestedClassB")))); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("objB"), "PrivateNestedClassesMethod", new CodeArgumentReferenceExpression ("i")))); cd.Members.Add (cmm); } // ************ abstract class *************** // GENERATES (C#): // public abstract class AbstractClass { // public abstract int AbstractMethod(int i); // } // public class InheritAbstractClass : AbstractClass { // // public override int AbstractMethod(int i) { // return i; // } // } AddScenario ("TestAbstractAttributes"); cd = new CodeTypeDeclaration ("AbstractClass"); cd.TypeAttributes = TypeAttributes.Abstract | TypeAttributes.Public; cd.IsClass = true; nspace.Types.Add (cd); CodeTypeDeclaration inheritAbstractClass = new CodeTypeDeclaration ("InheritAbstractClass"); inheritAbstractClass.IsClass = true; inheritAbstractClass.BaseTypes.Add (new CodeTypeReference ("AbstractClass")); nspace.Types.Add (inheritAbstractClass); cmm = new CodeMemberMethod (); cmm.Name = "AbstractMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Abstract; cd.Members.Add (cmm); cmm = new CodeMemberMethod (); cmm.Name = "AbstractMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Override; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("i"))); inheritAbstractClass.Members.Add (cmm); // ************ sealed class ***************** // GENERATES (C#): // sealed class SealedClass { // public int SealedClassMethod(int i) { // return i; // } // } AddScenario ("TestSealedAttributes"); cd = new CodeTypeDeclaration ("SealedClass"); cd.IsClass = true; cd.TypeAttributes = TypeAttributes.Sealed; nspace.Types.Add (cd); cmm = new CodeMemberMethod (); cmm.Name = "SealedClassMethod"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i")); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("i"))); cd.Members.Add (cmm); // ************* class with custom attributes ******************** // GENERATES (C#): // [System.Obsolete("Don\'t use this Class")] // [System.Windows.Forms.AxHost.ClsidAttribute("Class.ID")] // public class ClassWCustomAttributes { // } cd = new CodeTypeDeclaration ("ClassWCustomAttributes"); cd.IsClass = true; AddScenario ("FindObsoleteAttribute"); cd.CustomAttributes.Add (new CodeAttributeDeclaration ("System.Obsolete", new CodeAttributeArgument (new CodePrimitiveExpression ("Don't use this Class")))); AddScenario ("FindOtherAttribute"); cd.CustomAttributes.Add (new CodeAttributeDeclaration (typeof (System.Windows.Forms.AxHost.ClsidAttribute).FullName, new CodeAttributeArgument (new CodePrimitiveExpression ("Class.ID")))); nspace.Types.Add (cd); } public override void VerifyAssembly (CodeDomProvider provider, Assembly asm) { object genObject; Type genType; AddScenario ("InstantiateTestingClass", "Find and instantiate TestingClass."); if (!FindAndInstantiate ("NSPC.TestingClass", asm, out genObject, out genType)) return; VerifyScenario ("InstantiateTestingClass"); if (Supports (provider, GeneratorSupport.NestedTypes)) { if (VerifyMethod (genType, genObject, "CallingPrivateNestedScenario", new object[] {7}, 7)) VerifyScenario ("CheckCallingPrivateNestedScenario"); if (VerifyMethod (genType, genObject, "CallingPublicNestedScenario", new object[] {7}, 7)) VerifyScenario ("CheckCallingPublicNestedScenario"); } if (Supports (provider, GeneratorSupport.DeclareInterfaces)) { if (VerifyMethod (genType, genObject, "TestSingleInterface", new object[] {7}, 7)) VerifyScenario ("CheckTestSingleInterface"); if (Supports (provider, GeneratorSupport.MultipleInterfaceMembers) && VerifyMethod (genType, genObject, "TestMultipleInterfaces", new object[] {7}, 0)) { VerifyScenario ("CheckTestMultipleInterfaces"); } } if (VerifyMethod (genType, genObject, "CallingOverrideScenario", new object[] {7}, 14)) { VerifyScenario ("CheckCallingOverrideScenario"); } if (VerifyMethod (genType, genObject, "CallingAbstractScenario", new object[] {7}, 7)) { VerifyScenario ("CheckCallingAbstractScenario"); } // check that can't access private nested class from outside the class if (Supports (provider, GeneratorSupport.NestedTypes) && !FindType ("NSPC.PrivateNestedClassA.PrivateNestedClassB", asm, out genType)) { VerifyScenario ("CantFindPrivateNestedClass"); } // verify abstract attribute on classes if (FindType ("NSPC.AbstractClass", asm, out genType) && (genType.Attributes & TypeAttributes.Abstract) == TypeAttributes.Abstract) { VerifyScenario ("TestAbstractAttributes"); } // verify sealed attribute on classes if (FindType ("NSPC.SealedClass", asm, out genType) /*&& (genType.Attributes & TypeAttributes.Sealed) == TypeAttributes.Sealed*/) { VerifyScenario ("TestSealedAttributes"); } // verify custom attributes on classes if (FindType ("NSPC.ClassWCustomAttributes", asm, out genType)) { object[] customAttributes = genType.GetCustomAttributes (typeof (System.ObsoleteAttribute), true); if (customAttributes.GetLength (0) == 1) { VerifyScenario ("FindObsoleteAttribute"); } customAttributes = genType.GetCustomAttributes (typeof (System.Windows.Forms.AxHost.ClsidAttribute), true); if (customAttributes.GetLength (0) == 1) { VerifyScenario ("FindOtherAttribute"); } } } }
/* * Copyright 2013 Splunk, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"): you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ namespace Splunk { using System; using System.Collections.Generic; using System.IO; using System.Net.Sockets; using System.Xml; /// <summary> /// The <see cref="Service"/> class represents a Splunk service instance /// at a given address (<i>host</i>:<i>port</i>) accessed using the http or /// https protocol scheme. /// </summary> /// <remarks> /// <para> /// A <see cref="Service"/> instance also captures an optional namespace /// contact that consists of an optional owner name (or "-" wildcard) and /// optional app name (or "-" wildcard). /// </para> /// <para> /// To access the <see cref="Service"/> members, the <see cref="Service"/> /// instance must be authenticated by presenting credentials using the /// <see cref="Login"/> method, or by constructing the /// <see cref="Service"/> instance using the <see cref="Connect"/> method. /// </para> /// </remarks> public class Service : BaseService { /// <summary> /// The default host name, which is used when a host name is not /// provided. /// </summary> private static string defaultHost = "localhost"; /// <summary> /// The default port number, which is used when a port number is not /// provided. /// </summary> private static int defaultPort = 8089; /// <summary> /// Initializes a new instance of the <see cref="Service"/> class /// </summary> /// <param name="host">The hostname.</param> public Service(string host) : base(host) { this.InitProperties(); } /// <summary> /// Initializes a new instance of the <see cref="Service"/> class, /// with host and port. /// </summary> /// <param name="host">The host name.</param> /// <param name="port">The port.</param> public Service(string host, int port) : base(host, port) { this.InitProperties(); } /// <summary> /// Initializes a new instance of the <see cref="Service"/> class, /// with host, port, and scheme. /// </summary> /// <param name="host">The host name.</param> /// <param name="port">The port.</param> /// <param name="scheme">The scheme, http or https.</param> public Service(string host, int port, string scheme) : base(host, port, scheme) { this.InitProperties(); } /// <summary> /// Initializes a new instance of the <see cref="Service"/> class, /// with a <see cref="ServiceArgs"/> argument list. /// </summary> /// <param name="args">The service arguments.</param> public Service(ServiceArgs args) : base() { this.InitProperties(); this.App = args.App; this.Host = args.Host == null ? defaultHost : args.Host; this.Owner = args.Owner; this.Port = args.Port == 0 ? defaultPort : args.Port; this.Scheme = args.Scheme == null ? HttpService.DefaultScheme : args.Scheme; this.Token = args.Token; } /// <summary> /// Initializes a new instance of the <see cref="Service"/> class /// with a general argument list. /// </summary> /// <param name="args">The service arguments.</param> public Service(Dictionary<string, object> args) : base() { this.InitProperties(); this.App = Args.Get(args, "app", null); this.Host = Args.Get(args, "host", defaultHost); this.Owner = Args.Get(args, "owner", null); this.Port = args.ContainsKey("port") ? Convert.ToInt32(args["port"]) : defaultPort; this.Scheme = Args.Get(args, "scheme", HttpService.DefaultScheme); this.Token = Args.Get(args, "token", null); } /// <summary> /// Gets or sets the current app context. /// </summary> private string App { get; set; } /// <summary> /// Gets or sets the current owner context. /// </summary> /// <remarks> /// A value of "nobody" means that all users have access to the /// resource. /// </remarks> private string Owner { get; set; } /// <summary> /// Gets or sets the password, which is used to authenticate the /// Splunk instance. /// </summary> private string Password { get; set; } /// <summary> /// Gets or sets the default password endpoint, which can change over /// Splunk versions. /// </summary> internal string PasswordEndPoint { get; set; } /// <summary> /// Gets or sets the default simple receiver endpoint. /// </summary> internal string SimpleReceiverEndPoint { get; set; } /// <summary> /// Gets or sets the current session (authorization) token. /// </summary> public string Token { get; set; } /// <summary> /// Gets or sets the Splunk account username, which is used to /// authenticate the Splunk instance. /// </summary> private string Username { get; set; } /// <summary> /// Gets the version of this Splunk instance, once logged in. /// </summary> public string Version { get; private set; } /// <summary> /// Initializes all properties to their default values. /// </summary> private void InitProperties() { this.SimpleReceiverEndPoint = "receivers/simple"; this.PasswordEndPoint = "admin/passwords"; this.App = null; this.Owner = null; this.Password = null; this.Token = null; this.Username = null; this.Version = null; } /// <summary> /// Establishes a connection to a Splunk service using a map of /// arguments. /// </summary> /// <param name="args">The connection arguments.</param> /// <returns>A new <see cref="Service"/> instance.</returns> /// <remarks> /// This method creates a new <see cref="Service"/> instance and /// authenticates the session using credentials passed in from the args /// dictionary. /// </remarks> public static Service Connect(Dictionary<string, object> args) { Service service = new Service(args); if (args.ContainsKey("username")) { string username = Args.Get(args, "username", null); string password = Args.Get(args, "password", null); service.Login(username, password); } return service; } /// <summary> /// Returns the array of the system capabilities. /// </summary> /// <returns>An array of system capabilities.</returns> public string[] Capabilities() { Entity caps = new Entity(this, "authorization/capabilities"); return caps.GetStringArray("capabilities"); } /// <summary> /// Runs a search using the search/jobs/export endpoint, which streams /// results back via a <see cref="Stream"/>. /// </summary> /// <param name="search">The search query string.</param> /// <returns>A results stream.</returns> public Stream Export(string search) { return this.Export(search, null); } /// <summary> /// Runs a search using the search/jobs/export endpoint, which streams /// results back via a <see cref="Stream"/>. /// </summary> /// <param name="search">The search query string.</param> /// <param name="args">The search arguments.</param> /// <returns>A results stream.</returns> public Stream Export(string search, Args args) { args = Args.Create(args).Set("search", search); SetSegmentationDefault(ref args); ResponseMessage response = Get("search/jobs/export", args); return new ResponseStream(response, true); } /// <summary> /// Runs a search using the search/jobs/export endpoint which streams /// results back via a <see cref="Stream"/>. /// </summary> /// <param name="search">The search query string.</param> /// <param name="args">The search arguments.</param> /// <returns>The results stream.</returns> public Stream Export(string search, JobExportArgs args) { return Export(search, (Args) args); } /// <summary> /// Ensures that the given path is fully qualified, prepending a path /// prefix if necessary. /// </summary> /// <param name="path">The path.</param> /// <returns>The fully qualified URL.</returns> /// <remarks> /// The path prefix is constructed using the current owner and app /// context when available. /// </remarks> public string Fullpath(string path) { return this.Fullpath(path, null); } /// <summary> /// Ensures that the given path is fully qualified, prepending a path /// prefix if necessary. /// </summary> /// <param name="path">The path.</param> /// <param name="splunkNamespace">The Splunk namespace.</param> /// <returns>A fully qualified URL.</returns> /// <remarks> /// The path prefix is constructed using the current owner and app /// context when available. /// </remarks> public string Fullpath(string path, Args splunkNamespace) { // If already fully qualified (i.e. root begins with /), then return // the already qualified path. if (path.StartsWith("/")) { return path; } // If no namespace at all and no service instance of app and no // sharing, return base service endpoint + path. if (splunkNamespace == null && this.App == null) { return "/services/" + path; } // Base namespace values. string localApp = this.App; string localOwner = this.Owner; string localSharing = string.Empty; // Override with invocation namespace if set. if (splunkNamespace != null) { if (splunkNamespace.ContainsKey("app")) { localApp = (string)splunkNamespace["app"]; } if (splunkNamespace.ContainsKey("owner")) { localOwner = (string)splunkNamespace["owner"]; } if (splunkNamespace.ContainsKey("sharing")) { localSharing = (string)splunkNamespace["sharing"]; } } // Sharing, if set calls for special mapping, override here. // "user" --> {user}/{app} // "app" --> nobody/{app} // "global" --> nobody/{app} // "system" --> nobody/system if (localSharing.Equals("app") || localSharing.Equals("global")) { localOwner = "nobody"; } else if (localSharing.Equals("system")) { localApp = "system"; localOwner = "nobody"; } return string.Format( "/servicesNS/{0}/{1}/{2}", localOwner == null ? "-" : localOwner, localApp == null ? "-" : localApp, path); } /// <summary> /// Returns the collection of applications. /// </summary> /// <returns> /// A collection of applications. /// </returns> public EntityCollection<Application> GetApplications() { return new EntityCollection<Application>( this, "/services/apps/local", typeof(Application)); } /// <summary> /// Returns the collection of configurations. /// </summary> /// <returns>A collection of configurations.</returns> public ConfCollection GetConfs() { return new ConfCollection(this); } /// <summary> /// Returns the collection of configurations. /// </summary> /// <param name="args">The arguments.</param> /// <returns>A collection of configurations.</returns> public ConfCollection GetConfs(Args args) { return new ConfCollection(this, args); } /// <summary> /// Returns a collection of saved event types. /// </summary> /// <returns>A collection of saved event types.</returns> public EventTypeCollection GetEventTypes() { return new EventTypeCollection(this); } /// <summary> /// Returns a collection of saved event types. /// </summary> /// <param name="args">The arguments.</param> /// <returns>A collection of saved event types.</returns> public EventTypeCollection GetEventTypes(Args args) { return new EventTypeCollection(this, args); } /// <summary> /// Returns a collection of alert groups that have been /// fired by the service. /// </summary> /// <returns>A collection of fired alert groups.</returns> public FiredAlertsGroupCollection GetFiredAlertGroups() { return new FiredAlertsGroupCollection(this); } /// <summary> /// Returns a collection of alert groups that have been /// fired by the service. /// </summary> /// <param name="args">Optional arguments, such as "count" and /// "offset" for pagination.</param> /// <returns>A collection of fired alert groups.</returns> public FiredAlertsGroupCollection GetFiredAlerts(Args args) { return new FiredAlertsGroupCollection(this, args); } /// <summary> /// Returns a collection of Splunk indexes. /// </summary> /// <returns>A collection of indexes.</returns> public EntityCollection<Index> GetIndexes() { return new EntityCollection<Index>(this, "data/indexes", typeof(Index)); } /// <summary> /// Returns a collection of Splunk indexes. /// </summary> /// <param name="args">The optional arguments.</param> /// <returns>A collection of indexes.</returns> public EntityCollection<Index> GetIndexes(Args args) { return new EntityCollection<Index>( this, "data/indexes", args, typeof(Index)); } /// <summary> /// Returns information about the Splunk service. /// </summary> /// <returns>Information about the Splunk /// service.</returns> public ServiceInfo GetInfo() { return new ServiceInfo(this); } /// <summary> /// Returns a collection of configured inputs. /// </summary> /// <returns>A collection of configured inputs.</returns> public InputCollection GetInputs() { return new InputCollection(this); } /// <summary> /// Returns a collection of configured inputs. /// </summary> /// <param name="args">Optional arguments.</param> /// <returns>A collection of configured inputs.</returns> public InputCollection GetInputs(Args args) { return new InputCollection(this, args); } /// <summary> /// Returns a collection of current search jobs. /// </summary> /// <returns>A collection of jobs.</returns> public JobCollection GetJobs() { return new JobCollection(this); } /// <summary> /// Returns a collection of current search jobs. /// </summary> /// <param name="args">The variable arguments.</param> /// <returns>A collection of jobs.</returns> public JobCollection GetJobs(Args args) { return new JobCollection(this, args); } /// <summary> /// Returns a collection of service logging categories and their /// status. /// </summary> /// <returns>A collection of loggers.</returns> public EntityCollection<Logger> GetLoggers() { return new EntityCollection<Logger>( this, "server/logger", typeof(Logger)); } /// <summary> /// Returns a collection of service logging categories and their status. /// </summary> /// <param name="args">Optional arguments, such as "count" and "offset" /// for pagination.</param> /// <returns>A collection of loggers.</returns> public EntityCollection<Logger> GetLoggers(Args args) { return new EntityCollection<Logger>( this, "server/logger", args, typeof(Logger)); } /// <summary> /// Returns the collection of messages. /// </summary> /// <returns>A <see cref="MessageCollection"/>.</returns> public MessageCollection GetMessages() { return new MessageCollection(this); } /// <summary> /// Returns the collection of messages. /// </summary> /// <param name="args">The arguments.</param> /// <returns>A collection of messages.</returns> public MessageCollection GetMessages(Args args) { return new MessageCollection(this, args); } /// <summary> /// Returns a collection of credentials. /// </summary> /// <returns>A collection of credentials.</returns> /// <remarks> /// This collection is used for managing secure credentials. /// </remarks> public CredentialCollection GetCredentials() { return new CredentialCollection(this); } /// <summary> /// Returns a collection of credentials. /// </summary> /// <param name="args">Optional arguments, such as "count" and "offset" /// for pagination.</param> /// <returns>A collection of credentials.</returns> /// <remarks> /// This collection is used for managing secure credentials. /// </remarks> public CredentialCollection GetPasswords(Args args) { return new CredentialCollection(this, args); } /// <summary> /// Returns the receiver object for this Splunk service. /// </summary> /// <returns>A receiver object.</returns> public Receiver GetReceiver() { return new Receiver(this); } /// <summary> /// Returns a collection of Splunk user roles. /// </summary> /// <returns>A collection of Splunk roles.</returns> public EntityCollection<Role> GetRoles() { return new EntityCollection<Role>( this, "authorization/roles", typeof(Role)); } /// <summary> /// Returns a collection of Splunk user roles. /// </summary> /// <param name="args">Optional parameters.</param> /// <returns>A collection of Splunk roles.</returns> public EntityCollection<Role> GetRoles(Args args) { return new EntityCollection<Role>( this, "authorization/roles", args, typeof(Role)); } /// <summary> /// Returns a collection of saved searches. /// </summary> /// <returns>A collection of saved searches.</returns> public SavedSearchCollection GetSavedSearches() { return new SavedSearchCollection(this); } /// <summary> /// Returns a collection of saved searches. /// </summary> /// <param name="args">The arguments.</param> /// <returns>A collection of saved searches.</returns> public SavedSearchCollection GetSavedSearches(Args args) { return new SavedSearchCollection(this, args); } /// <summary> /// Returns service configuration information for an instance of /// Splunk. /// </summary> /// <returns>This Splunk instance's configuration information. /// </returns> public Settings GetSettings() { return new Settings(this); } /// <summary> /// Returns a collection of in-progress oneshot uploads. /// </summary> /// <returns>A collection of oneshot uploads.</returns> public EntityCollection<Upload> GetUploads() { return new EntityCollection<Upload>( this, "data/inputs/oneshot", typeof(Upload)); } /// <summary> /// Returns a collection of in-progress oneshot uploads. /// </summary> /// <param name="splunkNamespace">The specific namespace.</param> /// <returns>A collection of oneshot uploads.</returns> public EntityCollection<Upload> GetUploads(Args splunkNamespace) { return new EntityCollection<Upload>( this, "data/inputs/oneshot", splunkNamespace, typeof(Upload)); } /// <summary> /// Returns a collection of Splunk users. /// </summary> /// <returns>A collection of Splunk users.</returns> public UserCollection GetUsers() { return new UserCollection(this); } /// <summary> /// Returns a collection of Splunk users. /// </summary> /// <param name="args">The arguments.</param> /// <returns>A collection of Splunk users.</returns> public UserCollection GetUsers(Args args) { return new UserCollection(this, args); } /// <summary> /// Authenticates the <see cref="Service"/> instance with a username /// and password. /// </summary> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <returns>The service instance.</returns> public Service Login(string username, string password) { this.Username = username; this.Password = password; Args args = new Args(); args.Set("username", username); args.Set("password", password); ResponseMessage response = Post("/services/auth/login", args); StreamReader streamReader = new StreamReader(response.Content); XmlDocument doc = new XmlDocument(); doc.LoadXml(streamReader.ReadToEnd()); string sessionKey = doc .SelectSingleNode("/response/sessionKey") .InnerText; this.Token = "Splunk " + sessionKey; this.Version = this.GetInfo().Version; if (!this.Version.Contains(".")) { // internal build this.Version = "6.0"; } if (this.VersionCompare("4.3") >= 0) { this.PasswordEndPoint = "storage/passwords"; } return this; } /// <summary> /// Logs out of the service. /// </summary> /// <returns>The service instance.</returns> public Service Logout() { this.Token = null; return this; } /// <summary> /// Creates a oneshot synchronous search. /// </summary> /// <param name="query">The search string.</param> /// <returns>An I/O stream.</returns> public Stream Oneshot(string query) { return this.Oneshot(query, null); } /// <summary> /// Creates a oneshot synchronous search using search arguments. /// </summary> /// <param name="query">The search query.</param> /// <param name="inputArgs">The input arguments.</param> /// <returns>An I/O stream.</returns> public Stream Oneshot(string query, Args inputArgs) { inputArgs = (inputArgs == null) ? Args.Create() : inputArgs; inputArgs = Args.Create(inputArgs); inputArgs.Add("search", query); inputArgs.Add("exec_mode", "oneshot"); SetSegmentationDefault(ref inputArgs); ResponseMessage response = this.Post("search/jobs", inputArgs); return new ResponseStream(response); } /// <summary> /// Sets the default value for the 'segmentation' property /// in the specified Args. /// </summary> /// <param name="args">Arguments to be modified if necessary</param> internal void SetSegmentationDefault(ref Args args) { // 'segmentation=none' on Splunk 4.3.5 (or earlier) // will result in full segmentation, rather than the // REST API default, "raw". Thus, don't add if (VersionCompare("5.0") < 0) { return; } if (args == null) { args = new Args(); } // If "segmentation" is not set, set it to "none". const string SegmentationKey = "segmentation"; if (!args.ContainsKey(SegmentationKey)) { args[SegmentationKey] = "none"; } } /// <summary> /// Opens a socket to the host and specified port. /// </summary> /// <param name="port">The port on the server to which to /// connect.</param> /// <returns>A connected socket.</returns> public Socket Open(int port) { Socket socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(this.Host, port); return socket; } /// <summary> /// Parses a search query and returns a semantic map for the search in /// JSON format. /// </summary> /// <param name="query">The search query.</param> /// <returns>A parse response message.</returns> public ResponseMessage Parse(string query) { return this.Parse(query, null); } /// <summary> /// Parses a search query with additional arguments and returns a /// semantic map for the search in JSON format. /// </summary> /// <param name="query">The search query.</param> /// <param name="args">The arguments.</param> /// <returns>A parse response message.</returns> public ResponseMessage Parse(string query, Args args) { args = Args.Create(args); args.Add("q", query); return this.Get("search/parser", args); } /// <summary> /// Issues a restart request to the service. /// </summary> /// <returns>A response message.</returns> public ResponseMessage Restart() { return this.Post("server/control/restart"); } /// <summary> /// Creates a simplified synchronous search using search arguments. /// </summary> /// <param name="query">The search string.</param> /// <returns>The stream handle of the search.</returns> /// <remarks> /// Use this method for simple searches. For output control arguments, /// use the <see cref="Search(string,Args,Args)"/> method. /// </remarks> public Stream Search(string query) { return this.Search(query, null, null); } /// <summary> /// Creates a simplified synchronous search using search arguments. /// </summary> /// <param name="query">The search string.</param> /// <param name="inputArgs">The variable arguments.</param> /// <returns>The stream handle of the search.</returns> /// <remarks> /// Use this method for simple searches. For output control arguments, /// use the <see cref="Search(string,Args,Args)"/> method. /// </remarks> public Stream Search(string query, Args inputArgs) { return this.Search(query, inputArgs, null); } /// <summary> /// Creates a simplified synchronous search using search arguments. /// </summary> /// <param name="query">The search string.</param> /// <param name="inputArgs">The variable arguments.</param> /// <param name="outputArgs">The output arguments.</param> /// <returns>The stream handle of the search.</returns> /// <remarks> /// Use this method for simple searches. /// </remarks> public Stream Search(string query, Args inputArgs, Args outputArgs) { inputArgs = Args.Create(inputArgs); inputArgs.Set("search", query); // always block until results are ready. inputArgs.Set("exec_mode", "blocking"); Job job = this.GetJobs().Create(query, inputArgs); return job.Results(outputArgs); } /// <summary> /// Overloaded. Issues an HTTP request against the service using a /// request path and message. /// </summary> /// <param name="path">The path.</param> /// <param name="request">The request message.</param> /// <returns>A response message.</returns> /// <remarks> /// This method overrides the base /// <see cref="HttpService"/>.<see cref="HttpService.Send"/> /// method and applies the Splunk authorization header, which is /// required for authenticated interactions with the Splunk service. /// </remarks> public override ResponseMessage Send(string path, RequestMessage request) { if (this.Token != null) { request.Header.Add("Authorization", this.Token); } return base.Send(this.Fullpath(path), request); } /// <summary> /// Compares the current version versus a desired version. /// </summary> /// <param name="right">The desired version.</param> /// <returns><para>One of the following values: /// <list type="bullet"> /// <item>"-1" indicates the current version is less than the desired /// version.</item> /// <item>"0" indicates the versions are equal.</item> /// <item>"1" indicates the current version is greater than the /// desired version.</item> /// </list></para></returns> public int VersionCompare(string right) { // Short cut for equality. if (this.Version.Equals(right)) { return 0; } // If not the same, break down into individual digits for // comparison. string[] leftDigits = this.Version.Split('.'); string[] rightDigits = right.Split('.'); for (int i = 0; i < leftDigits.Length; i++) { // No more right side, left side is bigger. if (i == rightDigits.Length) { return 1; } // Left side smaller? if (Convert.ToInt32(leftDigits[i]) < Convert.ToInt32(rightDigits[i])) { return -1; } // Left side bigger? if (Convert.ToInt32(leftDigits[i]) > Convert.ToInt32(rightDigits[i])) { return 1; } } // We got to the end of the left side, and not equal, right side // must be larger by having more digits. return -1; } } }
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, [email protected] * * * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.Collections.Generic; using System.Text; using MLifter.DAL.Interfaces; using MLifter.DAL.Tools; using System.Drawing; namespace MLifter.DAL.Preview { /// <summary> /// Used for preview and in the CardEdit for new media objects. /// </summary> /// <remarks>Documented by Dev03, 2008-08-25</remarks> internal class PreviewMedia : Interfaces.IMedia { public PreviewMedia(EMedia type, string path, bool isActive, bool isDefault, bool isExample, ParentClass parent) { this.parent = parent; this.mediatype = type; this.filename = path; this.active = isActive; this._default = isDefault; this.example = isExample; } #region IMedia Members public int Id { get { return -1; } } private string filename; public string Filename { get { return filename; } set { filename = value; } } public System.IO.Stream Stream { get { if (System.IO.File.Exists(Filename)) return System.IO.File.OpenRead(Filename); else return null; } } private EMedia mediatype; public MLifter.DAL.Interfaces.EMedia MediaType { get { return mediatype; } } private bool? active; public bool? Active { get { return active; } } private bool? example; public bool? Example { get { return example; } } private bool? _default; public bool? Default { get { return _default; } } public string MimeType { get { return Helper.GetMimeType(Filename); } } public string Extension { get { return System.IO.Path.GetExtension(Filename); } } /// <summary> /// Gets or sets the size of the media. /// </summary> /// <value>The size of the media.</value> /// <remarks>Documented by Dev08, 2008-10-02</remarks> public int MediaSize { get { try { return (int)Stream.Length; } catch { return 0; } } } #endregion #region IParent Members private ParentClass parent; public ParentClass Parent { get { return parent; } } #endregion #region ISecurity Members /// <summary> /// Determines whether the object has the specified permission. /// </summary> /// <param name="permissionName">Name of the permission.</param> /// <returns> /// <c>true</c> if the object name has the specified permission; otherwise, <c>false</c>. /// </returns> /// <remarks>Documented by Dev03, 2009-01-15</remarks> /// <remarks>Documented by Dev03, 2009-01-15</remarks> public bool HasPermission(string permissionName) { throw new NotImplementedException(); } /// <summary> /// Gets the permissions for the object. /// </summary> /// <returns>A list of permissions for the object.</returns> /// <remarks>Documented by Dev03, 2009-01-15</remarks> /// <remarks>Documented by Dev03, 2009-01-15</remarks> public List<SecurityFramework.PermissionInfo> GetPermissions() { throw new NotImplementedException(); } #endregion } /// <summary> /// Used for preview and in the CardEdit for new media objects. /// </summary> /// <remarks>Documented by Dev03, 2008-08-25</remarks> internal class PreviewAudio : PreviewMedia, IAudio { public PreviewAudio(string path, bool isActive, bool isDefault, bool isExample, ParentClass parent) : base(EMedia.Audio, path, isActive, isDefault, isExample, parent) { } } /// <summary> /// Used for preview and in the CardEdit for new media objects. /// </summary> /// <remarks>Documented by Dev03, 2008-08-25</remarks> internal class PreviewImage : PreviewMedia, IImage { public PreviewImage(string path, bool isActive, bool isDefault, bool isExample, ParentClass parent) : base(EMedia.Image, path, isActive, isDefault, isExample, parent) { try { if (Stream != null) { using (Image image = Image.FromStream(Stream)) { Height = image.Size.Height; Width = image.Size.Width; } } } catch { } } #region IImage Members int width = 0; public int Width { get { return width; } set { width = value; } } int height = 0; public int Height { get { return height; } set { height = value; } } #endregion } /// <summary> /// Used for preview and in the CardEdit for new media objects. /// </summary> /// <remarks>Documented by Dev03, 2008-08-25</remarks> internal class PreviewVideo : PreviewMedia, IVideo { public PreviewVideo(string path, bool isActive, bool isDefault, bool isExample, ParentClass parent) : base(EMedia.Video, path, isActive, isDefault, isExample, parent) { } } }
// Copyright (c) morrisjdev. All rights reserved. // Original copyright (c) .NET Foundation. All rights reserved. // Modified version by morrisjdev // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using FileContextCore.FileManager; using FileContextCore.Infrastructure.Internal; using FileContextCore.Internal; using FileContextCore.Serializer; using FileContextCore.StoreManager; using FileContextCore.Utilities; using FileContextCore.ValueGeneration.Internal; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Microsoft.EntityFrameworkCore.Update; using Microsoft.EntityFrameworkCore.Utilities; namespace FileContextCore.Storage.Internal { public class FileContextTable<TKey> : IFileContextTable { // WARNING: The in-memory provider is using EF internal code here. This should not be copied by other providers. See #15096 private readonly Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IPrincipalKeyValueFactory<TKey> _keyValueFactory; private readonly bool _sensitiveLoggingEnabled; private readonly IEntityType _entityType; private readonly IFileContextScopedOptions _options; private readonly IServiceProvider _serviceProvider; private readonly Dictionary<TKey, object[]> _rows; private IStoreManager _storeManager; private Dictionary<int, IFileContextIntegerValueGenerator> _integerGenerators; public FileContextTable( // WARNING: The in-memory provider is using EF internal code here. This should not be copied by other providers. See #15096 [NotNull] Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IPrincipalKeyValueFactory<TKey> keyValueFactory, bool sensitiveLoggingEnabled, IEntityType entityType, IFileContextScopedOptions options, IServiceProvider serviceProvider) { _keyValueFactory = keyValueFactory; _sensitiveLoggingEnabled = sensitiveLoggingEnabled; _entityType = entityType; _options = options; _serviceProvider = serviceProvider; _rows = Init(); } public virtual FileContextIntegerValueGenerator<TProperty> GetIntegerValueGenerator<TProperty>(IProperty property) { if (_integerGenerators == null) { _integerGenerators = new Dictionary<int, IFileContextIntegerValueGenerator>(); } // WARNING: The in-memory provider is using EF internal code here. This should not be copied by other providers. See #15096 var propertyIndex = Microsoft.EntityFrameworkCore.Metadata.Internal.PropertyBaseExtensions.GetIndex(property); if (!_integerGenerators.TryGetValue(propertyIndex, out var generator)) { generator = new FileContextIntegerValueGenerator<TProperty>(propertyIndex); _integerGenerators[propertyIndex] = generator; foreach (var row in _rows.Values) { generator.Bump(row); } } return (FileContextIntegerValueGenerator<TProperty>)generator; } public virtual IReadOnlyList<object[]> SnapshotRows() => _rows.Values.ToList(); private static List<ValueComparer> GetStructuralComparers(IEnumerable<IProperty> properties) => properties.Select(GetStructuralComparer).ToList(); private static ValueComparer GetStructuralComparer(IProperty p) => p.GetStructuralValueComparer() ?? p.FindTypeMapping()?.StructuralComparer; public virtual void Create(IUpdateEntry entry) { var row = entry.EntityType.GetProperties() .Select(p => SnapshotValue(p, GetStructuralComparer(p), entry)) .ToArray(); _rows.Add(CreateKey(entry), row); BumpValueGenerators(row); } public virtual void Delete(IUpdateEntry entry) { var key = CreateKey(entry); if (_rows.ContainsKey(key)) { var properties = entry.EntityType.GetProperties().ToList(); var concurrencyConflicts = new Dictionary<IProperty, object>(); for (var index = 0; index < properties.Count; index++) { IsConcurrencyConflict(entry, properties[index], _rows[key][index], concurrencyConflicts); } if (concurrencyConflicts.Count > 0) { ThrowUpdateConcurrencyException(entry, concurrencyConflicts); } _rows.Remove(key); } else { throw new DbUpdateConcurrencyException(FileContextStrings.UpdateConcurrencyException, new[] { entry }); } } private static bool IsConcurrencyConflict( IUpdateEntry entry, IProperty property, object rowValue, Dictionary<IProperty, object> concurrencyConflicts) { if (property.IsConcurrencyToken && !StructuralComparisons.StructuralEqualityComparer.Equals( rowValue, entry.GetOriginalValue(property))) { concurrencyConflicts.Add(property, rowValue); return true; } return false; } public virtual void Update(IUpdateEntry entry) { var key = CreateKey(entry); if (_rows.ContainsKey(key)) { var properties = entry.EntityType.GetProperties().ToList(); var comparers = GetStructuralComparers(properties); var valueBuffer = new object[properties.Count]; var concurrencyConflicts = new Dictionary<IProperty, object>(); for (var index = 0; index < valueBuffer.Length; index++) { if (IsConcurrencyConflict(entry, properties[index], _rows[key][index], concurrencyConflicts)) { continue; } valueBuffer[index] = entry.IsModified(properties[index]) ? SnapshotValue(properties[index], comparers[index], entry) : _rows[key][index]; } if (concurrencyConflicts.Count > 0) { ThrowUpdateConcurrencyException(entry, concurrencyConflicts); } _rows[key] = valueBuffer; BumpValueGenerators(valueBuffer); } else { throw new DbUpdateConcurrencyException(FileContextStrings.UpdateConcurrencyException, new[] { entry }); } } private void BumpValueGenerators(object[] row) { if (_integerGenerators != null) { foreach (var generator in _integerGenerators.Values) { generator.Bump(row); } } } // WARNING: The in-memory provider is using EF internal code here. This should not be copied by other providers. See #15096 private TKey CreateKey(IUpdateEntry entry) => _keyValueFactory.CreateFromCurrentValues((Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry)entry); private static object SnapshotValue(IProperty property, ValueComparer comparer, IUpdateEntry entry) => SnapshotValue(comparer, entry.GetCurrentValue(property)); private static object SnapshotValue(ValueComparer comparer, object value) => comparer == null ? value : comparer.Snapshot(value); public void Save() { _storeManager.Serialize(ConvertToProvider(_rows)); } /// <summary> /// Throws an exception indicating that concurrency conflicts were detected. /// </summary> /// <param name="entry"> The update entry which resulted in the conflict(s). </param> /// <param name="concurrencyConflicts"> The conflicting properties with their associated database values. </param> protected virtual void ThrowUpdateConcurrencyException([NotNull] IUpdateEntry entry, [NotNull] Dictionary<IProperty, object> concurrencyConflicts) { Check.NotNull(entry, nameof(entry)); Check.NotNull(concurrencyConflicts, nameof(concurrencyConflicts)); if (_sensitiveLoggingEnabled) { throw new DbUpdateConcurrencyException( FileContextStrings.UpdateConcurrencyTokenExceptionSensitive( entry.EntityType.DisplayName(), entry.BuildCurrentValuesString(entry.EntityType.FindPrimaryKey().Properties), entry.BuildOriginalValuesString(concurrencyConflicts.Keys), "{" + string.Join(", ", concurrencyConflicts.Select(c => c.Key.Name + ": " + Convert.ToString(c.Value, CultureInfo.InvariantCulture))) + "}"), new[] { entry }); } throw new DbUpdateConcurrencyException( FileContextStrings.UpdateConcurrencyTokenException( entry.EntityType.DisplayName(), concurrencyConflicts.Keys.Format()), new[] { entry }); } private Dictionary<TKey, object[]> Init() { _storeManager = (IStoreManager)_serviceProvider.GetService(_options.StoreManagerType); _storeManager.Initialize(_options, _entityType, _keyValueFactory); Dictionary<TKey, object[]> newList = new Dictionary<TKey, object[]>(_keyValueFactory.EqualityComparer); return ConvertFromProvider(_storeManager.Deserialize(newList)); } private Dictionary<TKey, object[]> ApplyValueConverter(Dictionary<TKey, object[]> list, Func<ValueConverter, Func<object, object>> conversionFunc) { var result = new Dictionary<TKey, object[]>(_keyValueFactory.EqualityComparer); var converters = _entityType.GetProperties().Select(p => p.GetValueConverter()).ToArray(); foreach (var keyValuePair in list) { result[keyValuePair.Key] = keyValuePair.Value.Select((value, index) => { var converter = converters[index]; return converter == null ? value : conversionFunc(converter)(value); }).ToArray(); } return result; } private Dictionary<TKey, object[]> ConvertToProvider(Dictionary<TKey, object[]> list) { return ApplyValueConverter(list, converter => converter.ConvertToProvider); } private Dictionary<TKey, object[]> ConvertFromProvider(Dictionary<TKey, object[]> list) { return ApplyValueConverter(list, converter => converter.ConvertFromProvider); } } }
// // This file is part of the game Voxalia, created by FreneticXYZ. // This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license. // See README.md or LICENSE.txt for contents of the MIT license. // If these are not available, see https://opensource.org/licenses/MIT // using System; using System.Runtime.InteropServices; namespace Voxalia.Shared { /// <summary> /// Internal representation of a single block's data. /// Structure: /// 14 bits: Material /// 2 bits: block damage /// 8 bits: shape ('data') /// 6 bits: paint /// 1 bit: blockShareTexture /// 1 bit: --UNUSED-- /// 8 bits: local data /// </summary> [StructLayout(LayoutKind.Sequential, Pack=1)] public struct BlockInternal { /// <summary> /// A sample block, a plain unmodified air block. /// </summary> public static BlockInternal AIR = new BlockInternal(0, 0, 0, 0); /// <summary> /// Converts an "item datum" method of storing a block internal data to an actual block internal data. /// </summary> /// <param name="dat">The item datum.</param> /// <returns>The actual block internal data.</returns> public static BlockInternal FromItemDatum(int dat) { return FromItemDatumU(BitConverter.ToUInt32(BitConverter.GetBytes(dat), 0)); // TODO: Less stupid conversion } /// <summary> /// Converts an unsigned "item datum" method of storing a block internal data to an actual block internal data. /// </summary> /// <param name="dat">The unsigned item datum.</param> /// <returns>The actual block internal data.</returns> public static BlockInternal FromItemDatumU(uint dat) { return new BlockInternal((ushort)(dat & (255u | (255u * 256u))), (byte)((dat & (255u * 256u * 256u)) / (256u * 256u)), (byte)((dat & (255u * 256u * 256u * 256u)) / (256u * 256u * 256)), 0); } /// <summary> /// The internal material and damage data of this block. /// </summary> public ushort _BlockMaterialInternal; /// <summary> /// The material represented by this block. /// This is a custom getter, that returns a small portion of the potential space. /// </summary> public ushort BlockMaterial { get { return (ushort)(_BlockMaterialInternal & (16384 - 1)); } set { _BlockMaterialInternal = (ushort)(value | (DamageData * 16384)); } } /// <summary> /// The material represented by this block. /// This is a custom getter, that returns a small portion of the potential space. /// </summary> public Material Material { get { return (Material)BlockMaterial; } set { BlockMaterial = (ushort)value; } } /// <summary> /// The damage data (0/1/2/3) of this block. /// </summary> public byte DamageData { get { return (byte)((_BlockMaterialInternal & (16384 | (16384 * 2))) / (16384)); } set { _BlockMaterialInternal = (ushort)(BlockMaterial | (value * 16384)); } } /// <summary> /// The damage data (NONE/SOME/MUCH/FULL) of this block. /// </summary> public BlockDamage Damage { get { return (BlockDamage)DamageData; } set { DamageData = (byte)value; } } /// <summary> /// The data represented by this block. /// Currently a directly read field, may be replaced by a getter that expands the bit count by stealing from other fields. /// </summary> public byte BlockData; public byte _BlockPaintInternal; /// <summary> /// The paint details represented by this block. /// This is a custom getter, that returns a small portion of the potential space. /// </summary> public byte BlockPaint { get { return (byte)(_BlockPaintInternal & 63); } set { _BlockPaintInternal = (byte)(value | (BlockShareTex ? 64 : 0)); } } /// <summary> /// Whether this block should grab surrounding texture data to color itself. /// This is a custom getter, that returns a small portion of the potential space. /// </summary> public bool BlockShareTex { get { return (_BlockPaintInternal & 64) == 64; } set { _BlockPaintInternal = (byte)(BlockPaint | (value ? 64 : 0)); } } /// <summary> /// The local details represented by this block. /// Only a direct field. Exact bit count may change. /// Generally for use with things such as light levels (Client), or block informational flags (Server). /// </summary> public byte BlockLocalData; /// <summary> /// Quickly constructs a basic BlockInternal from exact internal data input. /// </summary> /// <param name="mat">The material + damage data.</param> /// <param name="dat">The block data.</param> /// <param name="paint">The block paint.</param> /// <param name="loc">The block local data.</param> public BlockInternal(ushort mat, byte dat, byte paint, byte loc) { _BlockMaterialInternal = mat; BlockData = dat; _BlockPaintInternal = paint; BlockLocalData = loc; } /// <summary> /// Returns whether this block is opaque, checks both material and paint. /// </summary> /// <returns>Whether the block is opaque.</returns> public bool IsOpaque() { return ((Material)BlockMaterial).IsOpaque() && (BlockPaint < Colors.TRANS1 || BlockPaint > Colors.TRANS2); } /// <summary> /// Converts this block internal datum to an "item datum" integer. /// </summary> public int GetItemDatum() { return BitConverter.ToInt32(BitConverter.GetBytes(GetItemDatumU()), 0); // TODO: Less stupid conversion } /// <summary> /// Converts this block internal datum to an "item datum" unsigned integer. /// </summary> public uint GetItemDatumU() { return (uint)_BlockMaterialInternal | ((uint)BlockData * 256u * 256u) | ((uint)_BlockPaintInternal * 256u * 256u * 256u); } /// <summary> /// Displays this block's data as a quick string. Rarely if ever useful. /// </summary> public override string ToString() { return ((Material)_BlockMaterialInternal) + ":" + BlockData + ":" + _BlockPaintInternal + ":" + BlockLocalData; } } }
// // Copyright (c) 2004-2018 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using NLog.LayoutRenderers; namespace NLog.Config { using System; using System.Collections.Generic; using Common; using Internal; /// <summary> /// Factory for class-based items. /// </summary> /// <typeparam name="TBaseType">The base type of each item.</typeparam> /// <typeparam name="TAttributeType">The type of the attribute used to annotate items.</typeparam> internal class Factory<TBaseType, TAttributeType> : INamedItemFactory<TBaseType, Type>, IFactory where TBaseType : class where TAttributeType : NameBaseAttribute { private readonly Dictionary<string, GetTypeDelegate> _items = new Dictionary<string, GetTypeDelegate>(StringComparer.OrdinalIgnoreCase); private readonly ConfigurationItemFactory _parentFactory; internal Factory(ConfigurationItemFactory parentFactory) { _parentFactory = parentFactory; } private delegate Type GetTypeDelegate(); /// <summary> /// Scans the assembly. /// </summary> /// <param name="types">The types to scan.</param> /// <param name="prefix">The prefix.</param> public void ScanTypes(Type[] types, string prefix) { foreach (Type t in types) { try { RegisterType(t, prefix); } catch (Exception exception) { InternalLogger.Error(exception, "Failed to add type '{0}'.", t.FullName); if (exception.MustBeRethrown()) { throw; } } } } /// <summary> /// Registers the type. /// </summary> /// <param name="type">The type to register.</param> /// <param name="itemNamePrefix">The item name prefix.</param> public void RegisterType(Type type, string itemNamePrefix) { IEnumerable<TAttributeType> attributes = type.GetCustomAttributes<TAttributeType>(false); if (attributes != null) { foreach (TAttributeType attr in attributes) { RegisterDefinition(itemNamePrefix + attr.Name, type); } } } /// <summary> /// Registers the item based on a type name. /// </summary> /// <param name="itemName">Name of the item.</param> /// <param name="typeName">Name of the type.</param> public void RegisterNamedType(string itemName, string typeName) { _items[itemName] = () => Type.GetType(typeName, false); } /// <summary> /// Clears the contents of the factory. /// </summary> public void Clear() { _items.Clear(); } /// <summary> /// Registers a single type definition. /// </summary> /// <param name="itemName">The item name.</param> /// <param name="itemDefinition">The type of the item.</param> public void RegisterDefinition(string itemName, Type itemDefinition) { _items[itemName] = () => itemDefinition; } /// <summary> /// Tries to get registered item definition. /// </summary> /// <param name="itemName">Name of the item.</param> /// <param name="result">Reference to a variable which will store the item definition.</param> /// <returns>Item definition.</returns> public bool TryGetDefinition(string itemName, out Type result) { GetTypeDelegate getTypeDelegate; if (!_items.TryGetValue(itemName, out getTypeDelegate)) { result = null; return false; } try { result = getTypeDelegate(); return result != null; } catch (Exception ex) { if (ex.MustBeRethrown()) { throw; } // delegate invocation failed - type is not available result = null; return false; } } /// <summary> /// Tries to create an item instance. /// </summary> /// <param name="itemName">Name of the item.</param> /// <param name="result">The result.</param> /// <returns>True if instance was created successfully, false otherwise.</returns> public virtual bool TryCreateInstance(string itemName, out TBaseType result) { Type type; if (!TryGetDefinition(itemName, out type)) { result = null; return false; } result = (TBaseType)_parentFactory.CreateInstance(type); return true; } /// <summary> /// Creates an item instance. /// </summary> /// <param name="name">The name of the item.</param> /// <returns>Created item.</returns> public virtual TBaseType CreateInstance(string name) { TBaseType result; if (TryCreateInstance(name, out result)) { return result; } var message = typeof(TBaseType).Name + " cannot be found: '" + name + "'"; if (name != null && (name.StartsWith("aspnet", StringComparison.OrdinalIgnoreCase) || name.StartsWith("iis", StringComparison.OrdinalIgnoreCase))) { //common mistake and probably missing NLog.Web message += ". Is NLog.Web not included?"; } throw new ArgumentException(message); } } /// <summary> /// Factory specialized for <see cref="LayoutRenderer"/>s. /// </summary> class LayoutRendererFactory : Factory<LayoutRenderer, LayoutRendererAttribute> { public LayoutRendererFactory(ConfigurationItemFactory parentFactory) : base(parentFactory) { } private Dictionary<string, FuncLayoutRenderer> _funcRenderers; /// <summary> /// Clear all func layouts /// </summary> public void ClearFuncLayouts() { _funcRenderers = null; } /// <summary> /// Register a layout renderer with a callback function. /// </summary> /// <param name="name">Name of the layoutrenderer, without ${}.</param> /// <param name="renderer">the renderer that renders the value.</param> public void RegisterFuncLayout(string name, FuncLayoutRenderer renderer) { _funcRenderers = _funcRenderers ?? new Dictionary<string, FuncLayoutRenderer>(StringComparer.OrdinalIgnoreCase); //overwrite current if there is one _funcRenderers[name] = renderer; } /// <summary> /// Tries to create an item instance. /// </summary> /// <param name="itemName">Name of the item.</param> /// <param name="result">The result.</param> /// <returns>True if instance was created successfully, false otherwise.</returns> public override bool TryCreateInstance(string itemName, out LayoutRenderer result) { //first try func renderers, as they should have the possiblity to overwrite a current one. if (_funcRenderers != null) { FuncLayoutRenderer funcResult; var succesAsFunc = _funcRenderers.TryGetValue(itemName, out funcResult); if (succesAsFunc) { result = funcResult; return true; } } var success = base.TryCreateInstance(itemName, out result); return success; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsAzureBodyDurationAllSync { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// DurationOperations operations. /// </summary> internal partial class DurationOperations : IServiceOperations<AutoRestDurationTestService>, IDurationOperations { /// <summary> /// Initializes a new instance of the DurationOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DurationOperations(AutoRestDurationTestService client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AutoRestDurationTestService /// </summary> public AutoRestDurationTestService Client { get; private set; } /// <summary> /// Get null duration value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<System.TimeSpan?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/null").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<System.TimeSpan?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.TimeSpan?>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put a positive duration value /// </summary> /// <param name='durationBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PutPositiveDurationWithHttpMessagesAsync(System.TimeSpan durationBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("durationBody", durationBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutPositiveDuration", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(durationBody, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a positive duration value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<System.TimeSpan?>> GetPositiveDurationWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetPositiveDuration", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<System.TimeSpan?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.TimeSpan?>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get an invalid duration value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<System.TimeSpan?>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/invalid").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<System.TimeSpan?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.TimeSpan?>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using OLEDB.Test.ModuleCore; using System; using System.IO; using System.Xml; using XmlCoreTest.Common; using XmlReaderTest.Common; namespace XmlReaderTest { [TestModule(Name = "XmlSubtreeReader Test", Desc = "XmlSubtreeReader Test")] public partial class SubtreeReaderTest : CGenericTestModule { public override int Init(object objParam) { int ret = base.Init(objParam); string strFile = String.Empty; TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.GENERIC); TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.XSLT_COPY); TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.XMLSCHEMA); TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.INVALID_DTD); TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.INVALID_NAMESPACE); TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.INVALID_SCHEMA); TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.INVWELLFORMED_DTD); TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.NONWELLFORMED_DTD); TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.VALID_DTD); TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.WELLFORMED_DTD); TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.WHITESPACE_TEST); ReaderFactory = new XmlSubtreeReaderFactory(); return ret; } public override int Terminate(object objParam) { return base.Terminate(objParam); } } //////////////////////////////////////////////////////////////// // SubtreeReader factory // //////////////////////////////////////////////////////////////// internal class XmlSubtreeReaderFactory : ReaderFactory { public override XmlReader Create(MyDict<string, object> options) { string tcDesc = (string)options[ReaderFactory.HT_CURDESC]; string tcVar = (string)options[ReaderFactory.HT_CURVAR]; CError.Compare(tcDesc == "subtreereader", "Invalid testcase"); XmlReaderSettings rs = (XmlReaderSettings)options[ReaderFactory.HT_READERSETTINGS]; Stream stream = (Stream)options[ReaderFactory.HT_STREAM]; string filename = (string)options[ReaderFactory.HT_FILENAME]; object readerType = options[ReaderFactory.HT_READERTYPE]; object vt = options[ReaderFactory.HT_VALIDATIONTYPE]; string fragment = (string)options[ReaderFactory.HT_FRAGMENT]; StringReader sr = (StringReader)options[ReaderFactory.HT_STRINGREADER]; if (rs == null) rs = new XmlReaderSettings(); rs.DtdProcessing = DtdProcessing.Ignore; if (sr != null) { CError.WriteLine("SubtreeReader String"); XmlReader r = ReaderHelper.Create(sr, rs, string.Empty); while (r.Read()) { if (r.NodeType == XmlNodeType.Element) break; } XmlReader wr = r.ReadSubtree(); return wr; } if (stream != null) { CError.WriteLine("SubtreeReader Stream"); XmlReader r = ReaderHelper.Create(stream, rs, filename); while (r.Read()) { if (r.NodeType == XmlNodeType.Element) break; } XmlReader wr = r.ReadSubtree(); return wr; } if (fragment != null) { CError.WriteLine("SubtreeReader Fragment"); rs.ConformanceLevel = ConformanceLevel.Fragment; StringReader tr = new StringReader(fragment); XmlReader r = ReaderHelper.Create(tr, rs, (string)null); while (r.Read()) { if (r.NodeType == XmlNodeType.Element) break; } XmlReader wr = r.ReadSubtree(); return wr; } if (filename != null) { CError.WriteLine("SubtreeReader Filename"); Stream fs = FilePathUtil.getStream(filename); XmlReader r = ReaderHelper.Create(fs, rs, filename); while (r.Read()) { if (r.NodeType == XmlNodeType.Element) break; } XmlReader wr = r.ReadSubtree(); return wr; } throw new CTestFailedException("SubtreeReader not created"); } } [TestCase(Name = "InvalidXML", Desc = "SubtreeReader")] public class TCInvalidXMLReader : TCInvalidXML { } [TestCase(Name = "ErrorCondition", Desc = "SubtreeReader")] public class TCErrorConditionReader : TCErrorCondition { } [TestCase(Name = "Depth", Desc = "SubtreeReader")] public class TCDepthReader : TCDepth { } [TestCase(Name = "Namespace", Desc = "SubtreeReader")] public class TCNamespaceReader : TCNamespace { } [TestCase(Name = "LookupNamespace", Desc = "SubtreeReader")] public class TCLookupNamespaceReader : TCLookupNamespace { } [TestCase(Name = "IsEmptyElement", Desc = "SubtreeReader")] public class TCIsEmptyElementReader : TCIsEmptyElement { } [TestCase(Name = "XmlSpace", Desc = "SubtreeReader")] public class TCXmlSpaceReader : TCXmlSpace { } [TestCase(Name = "XmlLang", Desc = "SubtreeReader")] public class TCXmlLangReader : TCXmlLang { } [TestCase(Name = "Skip", Desc = "SubtreeReader")] public class TCSkipReader : TCSkip { } [TestCase(Name = "ReadOuterXml", Desc = "SubtreeReader")] public class TCReadOuterXmlReader : TCReadOuterXml { } [TestCase(Name = "AttributeAccess", Desc = "SubtreeReader")] public class TCAttributeAccessReader : TCAttributeAccess { } [TestCase(Name = "This(Name) and This(Name, Namespace)", Desc = "SubtreeReader")] public class TCThisNameReader : TCThisName { } [TestCase(Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "SubtreeReader")] public class TCMoveToAttributeReader : TCMoveToAttribute { } [TestCase(Name = "GetAttribute (Ordinal)", Desc = "SubtreeReader")] public class TCGetAttributeOrdinalReader : TCGetAttributeOrdinal { } [TestCase(Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "SubtreeReader")] public class TCGetAttributeNameReader : TCGetAttributeName { } [TestCase(Name = "This [Ordinal]", Desc = "SubtreeReader")] public class TCThisOrdinalReader : TCThisOrdinal { } [TestCase(Name = "MoveToAttribute(Ordinal)", Desc = "SubtreeReader")] public class TCMoveToAttributeOrdinalReader : TCMoveToAttributeOrdinal { } [TestCase(Name = "MoveToFirstAttribute()", Desc = "SubtreeReader")] public class TCMoveToFirstAttributeReader : TCMoveToFirstAttribute { } [TestCase(Name = "MoveToNextAttribute()", Desc = "SubtreeReader")] public class TCMoveToNextAttributeReader : TCMoveToNextAttribute { } [TestCase(Name = "Attribute Test when NodeType != Attributes", Desc = "SubtreeReader")] public class TCAttributeTestReader : TCAttributeTest { } [TestCase(Name = "xmlns as local name DCR50345", Desc = "SubtreeReader")] public class TCXmlnsReader : TCXmlns { } [TestCase(Name = "bounded namespace to xmlns prefix DCR50881", Desc = "SubtreeReader")] public class TCXmlnsPrefixReader : TCXmlnsPrefix { } [TestCase(Name = "ReadInnerXml", Desc = "SubtreeReader")] public class TCReadInnerXmlReader : TCReadInnerXml { } [TestCase(Name = "MoveToContent", Desc = "SubtreeReader")] public class TCMoveToContentReader : TCMoveToContent { } [TestCase(Name = "IsStartElement", Desc = "SubtreeReader")] public class TCIsStartElementReader : TCIsStartElement { } [TestCase(Name = "ReadStartElement", Desc = "SubtreeReader")] public class TCReadStartElementReader : TCReadStartElement { } [TestCase(Name = "ReadEndElement", Desc = "SubtreeReader")] public class TCReadEndElementReader : TCReadEndElement { } [TestCase(Name = "ResolveEntity and ReadAttributeValue", Desc = "SubtreeReader")] public class TCResolveEntityReader : TCResolveEntity { } [TestCase(Name = "HasValue", Desc = "SubtreeReader")] public class TCHasValueReader : TCHasValue { } [TestCase(Name = "ReadAttributeValue", Desc = "SubtreeReader")] public class TCReadAttributeValueReader : TCReadAttributeValue { } [TestCase(Name = "Read", Desc = "SubtreeReader")] public class TCReadReader : TCRead2 { } [TestCase(Name = "MoveToElement", Desc = "SubtreeReader")] public class TCMoveToElementReader : TCMoveToElement { } [TestCase(Name = "Dispose", Desc = "SubtreeReader")] public class TCDisposeReader : TCDispose { } [TestCase(Name = "Buffer Boundaries", Desc = "SubtreeReader")] public class TCBufferBoundariesReader : TCBufferBoundaries { } //[TestCase(Name = "BeforeRead", Desc = "BeforeRead")] //[TestCase(Name = "AfterReadIsFalse", Desc = "AfterReadIsFalse")] //[TestCase(Name = "AfterCloseInTheMiddle", Desc = "AfterCloseInTheMiddle")] //[TestCase(Name = "AfterClose", Desc = "AfterClose")] public class TCXmlNodeIntegrityTestFile : TCXMLIntegrityBase { } [TestCase(Name = "Read Subtree", Desc = "SubtreeReader")] public class TCReadSubtreeReader : TCReadSubtree { } [TestCase(Name = "ReadToDescendant", Desc = "SubtreeReader")] public class TCReadToDescendantReader : TCReadToDescendant { } [TestCase(Name = "ReadToNextSibling", Desc = "SubtreeReader")] public class TCReadToNextSiblingReader : TCReadToNextSibling { } [TestCase(Name = "ReadValue", Desc = "SubtreeReader")] public class TCReadValueReader : TCReadValue { } [TestCase(Name = "ReadContentAsBase64", Desc = "SubtreeReader")] public class TCReadContentAsBase64Reader : TCReadContentAsBase64 { } [TestCase(Name = "ReadElementContentAsBase64", Desc = "SubtreeReader")] public class TCReadElementContentAsBase64Reader : TCReadElementContentAsBase64 { } [TestCase(Name = "ReadContentAsBinHex", Desc = "SubtreeReader")] public class TCReadContentAsBinHexReader : TCReadContentAsBinHex { } [TestCase(Name = "ReadElementContentAsBinHex", Desc = "SubtreeReader")] public class TCReadElementContentAsBinHexReader : TCReadElementContentAsBinHex { } [TestCase(Name = "ReadToFollowing", Desc = "SubtreeReader")] public class TCReadToFollowingReader : TCReadToFollowing { } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace CuSer.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using System.Collections.Generic; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.TypeInfos.NativeFormat; using System.Reflection.Runtime.Assemblies; using System.Reflection.Runtime.MethodInfos; using System.Reflection.Runtime.MethodInfos.NativeFormat; #if ECMA_METADATA_SUPPORT using System.Reflection.Runtime.TypeInfos.EcmaFormat; using System.Reflection.Runtime.MethodInfos.EcmaFormat; #endif using System.Reflection.Runtime.TypeParsing; using System.Reflection.Runtime.CustomAttributes; using Internal.Metadata.NativeFormat; using Internal.Runtime.Augments; namespace Internal.Reflection.Core.Execution { // // This singleton class acts as an entrypoint from System.Private.Reflection.Execution to System.Private.Reflection.Core. // public sealed class ExecutionDomain { internal ExecutionDomain(ReflectionDomainSetup executionDomainSetup, ExecutionEnvironment executionEnvironment) { ExecutionEnvironment = executionEnvironment; ReflectionDomainSetup = executionDomainSetup; } // // Retrieves a type by name. Helper to implement Type.GetType(); // public Type GetType(String typeName, Func<AssemblyName, Assembly> assemblyResolver, Func<Assembly, string, bool, Type> typeResolver, bool throwOnError, bool ignoreCase, IList<string> defaultAssemblyNames) { if (typeName == null) throw new ArgumentNullException(); if (typeName.Length == 0) { if (throwOnError) throw new TypeLoadException(SR.Arg_TypeLoadNullStr); else return null; } TypeName parsedName = TypeParser.ParseAssemblyQualifiedTypeName(typeName, throwOnError: throwOnError); if (parsedName == null) return null; CoreAssemblyResolver coreAssemblyResolver = CreateCoreAssemblyResolver(assemblyResolver); CoreTypeResolver coreTypeResolver = CreateCoreTypeResolver(typeResolver, defaultAssemblyNames, throwOnError: throwOnError, ignoreCase: ignoreCase); GetTypeOptions getTypeOptions = new GetTypeOptions(coreAssemblyResolver, coreTypeResolver, throwOnError: throwOnError, ignoreCase: ignoreCase); return parsedName.ResolveType(null, getTypeOptions); } private static CoreAssemblyResolver CreateCoreAssemblyResolver(Func<AssemblyName, Assembly> assemblyResolver) { if (assemblyResolver == null) { return RuntimeAssembly.GetRuntimeAssemblyIfExists; } else { return delegate (RuntimeAssemblyName runtimeAssemblyName) { AssemblyName assemblyName = runtimeAssemblyName.ToAssemblyName(); Assembly assembly = assemblyResolver(assemblyName); return assembly; }; } } private static CoreTypeResolver CreateCoreTypeResolver(Func<Assembly, string, bool, Type> typeResolver, IList<string> defaultAssemblyNames, bool throwOnError, bool ignoreCase) { if (typeResolver == null) { return delegate (Assembly containingAssemblyIfAny, string coreTypeName) { if (containingAssemblyIfAny != null) { return containingAssemblyIfAny.GetTypeCore(coreTypeName, ignoreCase: ignoreCase); } else { foreach (string defaultAssemblyName in defaultAssemblyNames) { RuntimeAssemblyName runtimeAssemblyName = AssemblyNameParser.Parse(defaultAssemblyName); RuntimeAssembly defaultAssembly = RuntimeAssembly.GetRuntimeAssembly(runtimeAssemblyName); Type resolvedType = defaultAssembly.GetTypeCore(coreTypeName, ignoreCase: ignoreCase); if (resolvedType != null) return resolvedType; } if (throwOnError && defaultAssemblyNames.Count > 0) { // Though we don't have to throw a TypeLoadException exception (that's our caller's job), we can throw a more specific exception than he would so just do it. throw Helpers.CreateTypeLoadException(coreTypeName, defaultAssemblyNames[0]); } return null; } }; } else { return delegate (Assembly containingAssemblyIfAny, string coreTypeName) { string escapedName = coreTypeName.EscapeTypeNameIdentifier(); Type type = typeResolver(containingAssemblyIfAny, escapedName, ignoreCase); return type; }; } } // // Retrieves the MethodBase for a given method handle. Helper to implement Delegate.GetMethodInfo() // public MethodBase GetMethod(RuntimeTypeHandle declaringTypeHandle, QMethodDefinition methodHandle, RuntimeTypeHandle[] genericMethodTypeArgumentHandles) { RuntimeTypeInfo contextTypeInfo = declaringTypeHandle.GetTypeForRuntimeTypeHandle(); RuntimeNamedMethodInfo runtimeNamedMethodInfo = null; if (methodHandle.IsNativeFormatMetadataBased) { MethodHandle nativeFormatMethodHandle = methodHandle.NativeFormatHandle; NativeFormatRuntimeNamedTypeInfo definingTypeInfo = contextTypeInfo.AnchoringTypeDefinitionForDeclaredMembers.CastToNativeFormatRuntimeNamedTypeInfo(); MetadataReader reader = definingTypeInfo.Reader; if (nativeFormatMethodHandle.IsConstructor(reader)) { return RuntimePlainConstructorInfo<NativeFormatMethodCommon>.GetRuntimePlainConstructorInfo(new NativeFormatMethodCommon(nativeFormatMethodHandle, definingTypeInfo, contextTypeInfo)); } else { // RuntimeMethodHandles always yield methods whose ReflectedType is the DeclaringType. RuntimeTypeInfo reflectedType = contextTypeInfo; runtimeNamedMethodInfo = RuntimeNamedMethodInfo<NativeFormatMethodCommon>.GetRuntimeNamedMethodInfo(new NativeFormatMethodCommon(nativeFormatMethodHandle, definingTypeInfo, contextTypeInfo), reflectedType); } } #if ECMA_METADATA_SUPPORT else { System.Reflection.Metadata.MethodDefinitionHandle ecmaFormatMethodHandle = methodHandle.EcmaFormatHandle; EcmaFormatRuntimeNamedTypeInfo definingEcmaTypeInfo = contextTypeInfo.AnchoringTypeDefinitionForDeclaredMembers.CastToEcmaFormatRuntimeNamedTypeInfo(); System.Reflection.Metadata.MetadataReader reader = definingEcmaTypeInfo.Reader; if (ecmaFormatMethodHandle.IsConstructor(reader)) { return RuntimePlainConstructorInfo<EcmaFormatMethodCommon>.GetRuntimePlainConstructorInfo(new EcmaFormatMethodCommon(ecmaFormatMethodHandle, definingEcmaTypeInfo, contextTypeInfo)); } else { // RuntimeMethodHandles always yield methods whose ReflectedType is the DeclaringType. RuntimeTypeInfo reflectedType = contextTypeInfo; runtimeNamedMethodInfo = RuntimeNamedMethodInfo<EcmaFormatMethodCommon>.GetRuntimeNamedMethodInfo(new EcmaFormatMethodCommon(ecmaFormatMethodHandle, definingEcmaTypeInfo, contextTypeInfo), reflectedType); } } #endif if (!runtimeNamedMethodInfo.IsGenericMethod) { return runtimeNamedMethodInfo; } else { RuntimeTypeInfo[] genericTypeArguments = new RuntimeTypeInfo[genericMethodTypeArgumentHandles.Length]; for (int i = 0; i < genericMethodTypeArgumentHandles.Length; i++) { genericTypeArguments[i] = genericMethodTypeArgumentHandles[i].GetTypeForRuntimeTypeHandle(); } return RuntimeConstructedGenericMethodInfo.GetRuntimeConstructedGenericMethodInfo(runtimeNamedMethodInfo, genericTypeArguments); } } // // Get or create a CustomAttributeData object for a specific type and arguments. // public CustomAttributeData GetCustomAttributeData(Type attributeType, IList<CustomAttributeTypedArgument> constructorArguments, IList<CustomAttributeNamedArgument> namedArguments) { if (!attributeType.IsRuntimeImplemented()) throw new InvalidOperationException(); RuntimeTypeInfo runtimeAttributeType = attributeType.CastToRuntimeTypeInfo(); return new RuntimePseudoCustomAttributeData(runtimeAttributeType, constructorArguments, namedArguments); } //======================================================================================= // This group of methods jointly service the Type.GetTypeFromHandle() path. The caller // is responsible for analyzing the RuntimeTypeHandle to figure out which flavor to call. //======================================================================================= public Type GetNamedTypeForHandle(RuntimeTypeHandle typeHandle, bool isGenericTypeDefinition) { QTypeDefinition qTypeDefinition; if (ExecutionEnvironment.TryGetMetadataForNamedType(typeHandle, out qTypeDefinition)) { #if ECMA_METADATA_SUPPORT if (qTypeDefinition.IsNativeFormatMetadataBased) #endif { return qTypeDefinition.NativeFormatHandle.GetNamedType(qTypeDefinition.NativeFormatReader, typeHandle); } #if ECMA_METADATA_SUPPORT else { return System.Reflection.Runtime.TypeInfos.EcmaFormat.EcmaFormatRuntimeNamedTypeInfo.GetRuntimeNamedTypeInfo(qTypeDefinition.EcmaFormatReader, qTypeDefinition.EcmaFormatHandle, typeHandle); } #endif } else { if (ExecutionEnvironment.IsReflectionBlocked(typeHandle)) { return RuntimeBlockedTypeInfo.GetRuntimeBlockedTypeInfo(typeHandle, isGenericTypeDefinition); } else { return RuntimeNoMetadataNamedTypeInfo.GetRuntimeNoMetadataNamedTypeInfo(typeHandle, isGenericTypeDefinition); } } } public Type GetArrayTypeForHandle(RuntimeTypeHandle typeHandle) { RuntimeTypeHandle elementTypeHandle; if (!ExecutionEnvironment.TryGetArrayTypeElementType(typeHandle, out elementTypeHandle)) throw CreateMissingMetadataException((Type)null); return elementTypeHandle.GetTypeForRuntimeTypeHandle().GetArrayType(typeHandle); } public Type GetMdArrayTypeForHandle(RuntimeTypeHandle typeHandle, int rank) { RuntimeTypeHandle elementTypeHandle; if (!ExecutionEnvironment.TryGetArrayTypeElementType(typeHandle, out elementTypeHandle)) throw CreateMissingMetadataException((Type)null); return elementTypeHandle.GetTypeForRuntimeTypeHandle().GetMultiDimArrayType(rank, typeHandle); } public Type GetPointerTypeForHandle(RuntimeTypeHandle typeHandle) { RuntimeTypeHandle targetTypeHandle; if (!ExecutionEnvironment.TryGetPointerTypeTargetType(typeHandle, out targetTypeHandle)) throw CreateMissingMetadataException((Type)null); return targetTypeHandle.GetTypeForRuntimeTypeHandle().GetPointerType(typeHandle); } public Type GetByRefTypeForHandle(RuntimeTypeHandle typeHandle) { RuntimeTypeHandle targetTypeHandle; if (!ExecutionEnvironment.TryGetByRefTypeTargetType(typeHandle, out targetTypeHandle)) throw CreateMissingMetadataException((Type)null); return targetTypeHandle.GetTypeForRuntimeTypeHandle().GetByRefType(typeHandle); } public Type GetConstructedGenericTypeForHandle(RuntimeTypeHandle typeHandle) { RuntimeTypeHandle genericTypeDefinitionHandle; RuntimeTypeHandle[] genericTypeArgumentHandles; genericTypeDefinitionHandle = RuntimeAugments.GetGenericInstantiation(typeHandle, out genericTypeArgumentHandles); // Reflection blocked constructed generic types simply pretend to not be generic // This is reasonable, as the behavior of reflection blocked types is supposed // to be that they expose the minimal information about a type that is necessary // for users of Object.GetType to move from that type to a type that isn't // reflection blocked. By not revealing that reflection blocked types are generic // we are making it appear as if implementation detail types exposed to user code // are all non-generic, which is theoretically possible, and by doing so // we avoid (in all known circumstances) the very complicated case of representing // the interfaces, base types, and generic parameter types of reflection blocked // generic type definitions. if (ExecutionEnvironment.IsReflectionBlocked(genericTypeDefinitionHandle)) { return RuntimeBlockedTypeInfo.GetRuntimeBlockedTypeInfo(typeHandle, isGenericTypeDefinition: false); } RuntimeTypeInfo genericTypeDefinition = genericTypeDefinitionHandle.GetTypeForRuntimeTypeHandle(); int count = genericTypeArgumentHandles.Length; RuntimeTypeInfo[] genericTypeArguments = new RuntimeTypeInfo[count]; for (int i = 0; i < count; i++) { genericTypeArguments[i] = genericTypeArgumentHandles[i].GetTypeForRuntimeTypeHandle(); } return genericTypeDefinition.GetConstructedGenericType(genericTypeArguments, typeHandle); } //======================================================================================= // MissingMetadataExceptions. //======================================================================================= public Exception CreateMissingMetadataException(Type pertainant) { return this.ReflectionDomainSetup.CreateMissingMetadataException(pertainant); } public Exception CreateMissingMetadataException(TypeInfo pertainant) { return this.ReflectionDomainSetup.CreateMissingMetadataException(pertainant); } public Exception CreateMissingMetadataException(TypeInfo pertainant, string nestedTypeName) { return this.ReflectionDomainSetup.CreateMissingMetadataException(pertainant, nestedTypeName); } public Exception CreateNonInvokabilityException(MemberInfo pertainant) { return this.ReflectionDomainSetup.CreateNonInvokabilityException(pertainant); } public Exception CreateMissingArrayTypeException(Type elementType, bool isMultiDim, int rank) { return ReflectionDomainSetup.CreateMissingArrayTypeException(elementType, isMultiDim, rank); } public Exception CreateMissingConstructedGenericTypeException(Type genericTypeDefinition, Type[] genericTypeArguments) { return ReflectionDomainSetup.CreateMissingConstructedGenericTypeException(genericTypeDefinition, genericTypeArguments); } //======================================================================================= // Miscellaneous. //======================================================================================= public RuntimeTypeHandle GetTypeHandleIfAvailable(Type type) { if (!type.IsRuntimeImplemented()) return default(RuntimeTypeHandle); RuntimeTypeInfo runtimeType = type.CastToRuntimeTypeInfo(); if (runtimeType == null) return default(RuntimeTypeHandle); return runtimeType.InternalTypeHandleIfAvailable; } public bool SupportsReflection(Type type) { if (!type.IsRuntimeImplemented()) return false; RuntimeTypeInfo runtimeType = type.CastToRuntimeTypeInfo(); if (null == runtimeType.InternalNameIfAvailable) return false; if (ExecutionEnvironment.IsReflectionBlocked(type.TypeHandle)) { // The type is an internal framework type and is blocked from reflection return false; } if (runtimeType.InternalFullNameOfAssembly == Internal.Runtime.Augments.RuntimeAugments.HiddenScopeAssemblyName) { // The type is an internal framework type but is reflectable for internal class library use // where we make the type appear in a hidden assembly return false; } return true; } internal ExecutionEnvironment ExecutionEnvironment { get; } internal ReflectionDomainSetup ReflectionDomainSetup { get; } internal IEnumerable<Type> PrimitiveTypes => s_primitiveTypes; private static readonly Type[] s_primitiveTypes = { CommonRuntimeTypes.Boolean, CommonRuntimeTypes.Char, CommonRuntimeTypes.SByte, CommonRuntimeTypes.Byte, CommonRuntimeTypes.Int16, CommonRuntimeTypes.UInt16, CommonRuntimeTypes.Int32, CommonRuntimeTypes.UInt32, CommonRuntimeTypes.Int64, CommonRuntimeTypes.UInt64, CommonRuntimeTypes.Single, CommonRuntimeTypes.Double, CommonRuntimeTypes.IntPtr, CommonRuntimeTypes.UIntPtr, }; } }
using JetBrains.Annotations; using Nuke.Common; using Nuke.Common.IO; using Nuke.Common.Tooling; using Nuke.Common.Tools.Git; using Nuke.Common.Tools.GitVersion; using System; public class GitFlow { readonly Build build; public GitFlow([NotNull] Build build) { this.build = build ?? throw new ArgumentNullException(nameof(build)); } public event EventHandler<BuildType> UpdateVersionNumbers; public bool EnsureNoUncommittedChanges() { if (!GitTasks.GitHasCleanWorkingCopy()) throw new Exception( "There are uncommitted changes in the working tree. Please commit or remove these before proceeding."); return true; } public void PrepareStagingBranch(BuildState state) { if (state == null) throw new ArgumentNullException(nameof(state)); var versionInfo = FetchVersion(); if (versionInfo.BranchName == state.ReleaseTargetBranch) throw new Exception( $@"Cannot initiate a release from the release-target branch. Switch to a develop or release-xxx branch before continuing. Based on the current version information I expect to be on branch '{state.DevelopmentBranch}', but detected branch '{versionInfo.BranchName}' instead"); // if on development branch, create a release branch. // if you work in a support-xx branch, treat it as your develop-branch. var stageBranchName = state.ReleaseStagingBranch; if (versionInfo.BranchName == state.DevelopmentBranch) { if (GitTools.CheckBranchExists(stageBranchName)) { Logger.Info($"Switching to existing staging branch from {versionInfo.BranchName} as branch {stageBranchName}"); GitTools.Checkout(stageBranchName); } else { Logger.Info($"Creating new staging branch from current branch {versionInfo.BranchName} as branch {stageBranchName}"); GitTools.Branch(stageBranchName); UpdateVersionNumbers?.Invoke(this, BuildType.Staging); } } else { if (versionInfo.BranchName != stageBranchName) throw new Exception( $@"This command must be exist run from the development branch or an active release branch. Based on the current version information I expect to be on branch '{state.ReleaseStagingBranch}', but detected branch '{versionInfo.BranchName}' instead"); } } public void AttemptStagingBuild(BuildState state, Action<BuildType, string> action) { // We are now supposed to be on the release branch. EnsureOnReleaseStagingBranch(state); Logger.Info("Building current release as release candidate."); ValidateBuild(action, BuildType.Staging, null); } void ValidateBuild(Action<BuildType, string> runBuildTarget, BuildType t, string path) { if (runBuildTarget == null) throw new ArgumentException("RunBuildTarget action is not configured."); EnsureNoUncommittedChanges(); Logger.Info("Running target build script."); runBuildTarget(t, path); Logger.Info("Restoring original assembly version files."); GitTools.Reset(GitTools.ResetType.Hard); EnsureNoUncommittedChanges(); } public void PushStagingBranch() { var versionInfo = FetchVersion(); var stageBranchName = string.Format(build.ReleaseStagingBranchPattern, versionInfo.MajorMinorPatch, versionInfo.Major, versionInfo.Minor, versionInfo.Patch); if (!string.IsNullOrEmpty(build.PushTarget)) { Logger.Info("Publishing staging branch to public source repository."); GitTools.Push(build.PushTarget, stageBranchName); } } public bool EnsureOnReleaseStagingBranch(BuildState state) { if (state == null) throw new ArgumentNullException(nameof(state)); Logger.Trace("Validating that the build is on the release branch."); var versionInfo = FetchVersion(); if (versionInfo.BranchName != state.ReleaseStagingBranch) throw new Exception( "Not on the release branch. Based on the current version information I expect to be on branch '" + state.ReleaseStagingBranch + "', but detected branch '" + versionInfo.BranchName + "' instead"); return true; } public void PerformRelease(BuildState state, AbsolutePath changeLogFile, Action<BuildType, string> buildAction) { var releaseId = Guid.NewGuid(); var releaseBranchTag = "_release-state-" + releaseId; var stagingBranchTag = "_staging-state-" + releaseId; EnsureOnReleaseStagingBranch(state); GitTools.Tag(stagingBranchTag, state.ReleaseStagingBranch); try { if (ChangeLogGenerator.TryPrepareChangeLogForRelease(state, changeLogFile, out var sectionFile)) { GitTools.Commit($"Updated change log for release {state.Version.MajorMinorPatch}"); } // record the current master branch state. // We will use that later to potentially undo any changes we made during that build. GitTools.Tag(releaseBranchTag, state.ReleaseTargetBranch); try { // this takes the current staging branch state and merges it into // the release branch (usually master). This changes the active // branch of the working copy. GitTools.MergeRelease(state.ReleaseTargetBranch, state.ReleaseStagingBranch); // attempt to build the release again. ValidateBuild(buildAction, BuildType.Release, sectionFile); } catch { Logger.Error("Error: Unable to build the release on the release branch. Attempting to roll back changes on release branch."); GitTools.Reset(GitTools.ResetType.Hard, releaseBranchTag); throw; } finally { GitTools.DeleteTag(releaseBranchTag); } } catch { // In case of errors, roll back all commits and restore the current state // to be back on the release-staging branch. GitTools.Checkout(stagingBranchTag); GitTools.ResetBranch(state.ReleaseStagingBranch, stagingBranchTag); throw; } finally { GitTools.DeleteTag(stagingBranchTag); } } public void ContinueOnDevelopmentBranch(BuildState state) { EnsureNoUncommittedChanges(); GitTools.Checkout(state.DevelopmentBranch); GitTools.Merge(state.ReleaseStagingBranch); UpdateVersionNumbers?.Invoke(this, BuildType.Development); } public BuildState RecordBuildState() { EnsureNoUncommittedChanges(); return new BuildState(build.VersionTagPattern, build.DevelopBranch, build.ReleaseStagingBranchPattern, build.ReleaseTargetBranch); } const string GitVersionFramework = "net5.0"; public static GitVersion FetchVersion() { return GitVersionTasks.GitVersion(s => s.SetFramework(GitVersionFramework) .EnableNoFetch() .DisableProcessLogOutput() .DisableUpdateAssemblyInfo()) .Result; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.DirectoryServices; using System.Text; using System.Runtime.InteropServices; namespace System.DirectoryServices.AccountManagement { internal class SAMMembersSet : BookmarkableResultSet { internal SAMMembersSet(string groupPath, UnsafeNativeMethods.IADsGroup group, bool recursive, SAMStoreCtx storeCtx, DirectoryEntry ctxBase) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "SAMMembersSet: groupPath={0}, recursive={1}, base={2}", groupPath, recursive, ctxBase.Path); _storeCtx = storeCtx; _ctxBase = ctxBase; _group = group; _originalGroup = group; _recursive = recursive; _groupsVisited.Add(groupPath); // so we don't revisit it UnsafeNativeMethods.IADsMembers iADsMembers = group.Members(); _membersEnumerator = ((IEnumerable)iADsMembers).GetEnumerator(); } // Return the principal we're positioned at as a Principal object. // Need to use our StoreCtx's GetAsPrincipal to convert the native object to a Principal override internal object CurrentAsPrincipal { get { if (_current != null) { // Local principal --- handle it ourself GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "CurrentAsPrincipal: returning current"); return SAMUtils.DirectoryEntryAsPrincipal(_current, _storeCtx); } else if (_currentFakePrincipal != null) { // Local fake principal --- handle it ourself GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "CurrentAsPrincipal: returning currentFakePrincipal"); return _currentFakePrincipal; } else if (_currentForeign != null) { // Foreign, non-recursive principal. Just return the principal. GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "CurrentAsPrincipal: returning currentForeign"); return _currentForeign; } else { // Foreign recursive expansion. Proxy the call to the foreign ResultSet. Debug.Assert(_foreignResultSet != null); GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "CurrentAsPrincipal: returning foreignResultSet"); return _foreignResultSet.CurrentAsPrincipal; } } } // Advance the enumerator to the next principal in the result set, pulling in additional pages // of results (or ranges of attribute values) as needed. // Returns true if successful, false if no more results to return. override internal bool MoveNext() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "Entering MoveNext"); _atBeginning = false; bool f = MoveNextLocal(); if (!f) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNext: trying foreign"); f = MoveNextForeign(); } return f; } private bool MoveNextLocal() { bool needToRetry; do { needToRetry = false; object[] nativeMembers = new object[1]; bool f = _membersEnumerator.MoveNext(); if (f) // got a value { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextLocal: got a value from the enumerator"); UnsafeNativeMethods.IADs nativeMember = (UnsafeNativeMethods.IADs)_membersEnumerator.Current; // If we encountered a group member corresponding to a fake principal such as // NT AUTHORITY/NETWORK SERVICE, construct and prepare to return the fake principal. byte[] sid = (byte[])nativeMember.Get("objectSid"); SidType sidType = Utils.ClassifySID(sid); if (sidType == SidType.FakeObject) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextLocal: fake principal, sid={0}", Utils.ByteArrayToString(sid)); _currentFakePrincipal = _storeCtx.ConstructFakePrincipalFromSID(sid); _current = null; _currentForeign = null; if (_foreignResultSet != null) _foreignResultSet.Dispose(); _foreignResultSet = null; return true; } // We do this, rather than using the DirectoryEntry constructor that takes a native IADs object, // is so the credentials get transferred to the new DirectoryEntry. If we just use the native // object constructor, the native object will have the right credentials, but the DirectoryEntry // will have default (null) credentials, which it'll use anytime it needs to use credentials. DirectoryEntry de = SDSUtils.BuildDirectoryEntry( _storeCtx.Credentials, _storeCtx.AuthTypes); if (sidType == SidType.RealObjectFakeDomain) { // Transform the "WinNT://BUILTIN/foo" path to "WinNT://machineName/foo" string builtinADsPath = nativeMember.ADsPath; UnsafeNativeMethods.Pathname pathCracker = new UnsafeNativeMethods.Pathname(); UnsafeNativeMethods.IADsPathname pathName = (UnsafeNativeMethods.IADsPathname)pathCracker; pathName.Set(builtinADsPath, 1 /* ADS_SETTYPE_FULL */); // Build the "WinNT://" portion of the new path StringBuilder adsPath = new StringBuilder(); adsPath.Append("WinNT://"); //adsPath.Append(pathName.Retrieve(9 /*ADS_FORMAT_SERVER */)); // Build the "WinNT://machineName/" portion of the new path adsPath.Append(_storeCtx.MachineUserSuppliedName); adsPath.Append("/"); // Build the "WinNT://machineName/foo" portion of the new path int cElements = pathName.GetNumElements(); Debug.Assert(cElements >= 2); // "WinNT://BUILTIN/foo" == 2 elements // Note that the ADSI WinNT provider indexes them backwards, e.g., in // "WinNT://BUILTIN/A/B", BUILTIN == 2, A == 1, B == 0. for (int i = cElements - 2; i >= 0; i--) { adsPath.Append(pathName.GetElement(i)); adsPath.Append("/"); } adsPath.Remove(adsPath.Length - 1, 1); // remove the trailing "/" de.Path = adsPath.ToString(); GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextLocal: fake domain: {0} --> {1}", builtinADsPath, adsPath); } else { Debug.Assert(sidType == SidType.RealObject); de.Path = nativeMember.ADsPath; GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextLocal: real domain {0}", de.Path); } // Debug.Assert(Utils.AreBytesEqual(sid, (byte[]) de.Properties["objectSid"].Value)); if (IsLocalMember(sid)) { // If we're processing recursively, and the member is a group, // we don't return it but instead treat it as something to recursively // visit (expand) later. if (!_recursive || !SAMUtils.IsOfObjectClass(de, "Group")) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextLocal: setting current to {0}", de.Path); // Not recursive, or not a group. Return the principal. _current = de; _currentFakePrincipal = null; _currentForeign = null; if (_foreignResultSet != null) _foreignResultSet.Dispose(); _foreignResultSet = null; return true; } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextLocal: adding {0} to groupsToVisit", de.Path); // Save off for later, if we haven't done so already. if (!_groupsVisited.Contains(de.Path) && !_groupsToVisit.Contains(de.Path)) _groupsToVisit.Add(de.Path); needToRetry = true; continue; } } else { // It's a foreign principal (e..g, an AD user or group). // Save it off for later. GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextLocal: adding {0} to foreignMembers", de.Path); _foreignMembers.Add(de); needToRetry = true; continue; } } else { // We reached the end of this group's membership. // If we're supposed to be recursively expanding, we need to expand // any remaining non-foreign groups we earlier visited. if (_recursive) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextLocal: recursive processing, groupsToVisit={0}", _groupsToVisit.Count); if (_groupsToVisit.Count > 0) { // Pull off the next group to visit string groupPath = _groupsToVisit[0]; GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextLocal: recursively processing {0}", groupPath); _groupsToVisit.RemoveAt(0); _groupsVisited.Add(groupPath); // Set up for the next round of enumeration DirectoryEntry de = SDSUtils.BuildDirectoryEntry( groupPath, _storeCtx.Credentials, _storeCtx.AuthTypes); _group = (UnsafeNativeMethods.IADsGroup)de.NativeObject; UnsafeNativeMethods.IADsMembers iADsMembers = _group.Members(); _membersEnumerator = ((IEnumerable)iADsMembers).GetEnumerator(); // and go on to the first member of this new group needToRetry = true; continue; } } } } while (needToRetry); return false; } private bool MoveNextForeign() { bool needToRetry; do { needToRetry = false; GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextForeign: foreignMembers count={0}", _foreignMembers.Count); if (_foreignMembers.Count > 0) { // foreignDE is a DirectoryEntry in _this_ store representing a principal in another store DirectoryEntry foreignDE = _foreignMembers[0]; _foreignMembers.RemoveAt(0); GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextForeign: foreignDE={0}", foreignDE.Path); // foreignPrincipal is a principal from _another_ store (e.g., it's backed by an ADStoreCtx) Principal foreignPrincipal = _storeCtx.ResolveCrossStoreRefToPrincipal(foreignDE); // If we're not enumerating recursively, return the principal. // If we are enumerating recursively, and it's a group, save it off for later. if (!_recursive || !(foreignPrincipal is GroupPrincipal)) { // Return the principal. GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextForeign: setting currentForeign to {0}", foreignDE.Path); _current = null; _currentFakePrincipal = null; _currentForeign = foreignPrincipal; if (_foreignResultSet != null) _foreignResultSet.Dispose(); _foreignResultSet = null; return true; } else { // Save off the group for recursive expansion, and go on to the next principal. GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextForeign: adding {0} to foreignGroups", foreignDE.Path); _foreignGroups.Add((GroupPrincipal)foreignPrincipal); needToRetry = true; continue; } } if (_foreignResultSet == null && _foreignGroups.Count > 0) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextForeign: getting foreignResultSet (foreignGroups count={0})", _foreignGroups.Count); // We're expanding recursively, and either (1) we're immediately before // the recursive expansion of the first foreign group, or (2) we just completed // the recursive expansion of a foreign group, and now are moving on to the next. Debug.Assert(_recursive == true); // Pull off a foreign group to expand. GroupPrincipal foreignGroup = _foreignGroups[0]; _foreignGroups.RemoveAt(0); // Since it's a foreign group, we don't know how to enumerate its members. So we'll // ask the group, through its StoreCtx, to do it for us. Effectively, we'll end up acting // as a proxy to the foreign group's ResultSet. _foreignResultSet = foreignGroup.GetStoreCtxToUse().GetGroupMembership(foreignGroup, true); } // We're either just beginning the recursive expansion of a foreign group, or we're continuing the expansion // that we started on a previous call to MoveNext(). if (_foreignResultSet != null) { Debug.Assert(_recursive == true); bool f = _foreignResultSet.MoveNext(); if (f) { // By setting current, currentFakePrincipal, and currentForeign to null, // CurrentAsPrincipal/CurrentAsIdentityReference will know to proxy out to foreignResultSet. GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextForeign: using foreignResultSet"); _current = null; _currentFakePrincipal = null; _currentForeign = null; return true; } // Ran out of members in the foreign group, is there another foreign group remaining that we need // to expand? if (_foreignGroups.Count > 0) { // Yes, there is. Null out the foreignResultSet so we'll pull out the next foreign group // the next time around the loop. GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextForeign: ran out of members, using next foreignResultSet"); _foreignResultSet.Dispose(); _foreignResultSet = null; Debug.Assert(_foreignMembers.Count == 0); needToRetry = true; } else { // No, there isn't. Nothing left to do. We set foreignResultSet to null here just // to leave things in a clean state --- it shouldn't really be necessary. GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextForeign: ran out of members, nothing more to do"); _foreignResultSet.Dispose(); _foreignResultSet = null; } } } while (needToRetry); return false; } private bool IsLocalMember(byte[] sid) { // BUILTIN SIDs are local, but we can't determine that by looking at domainName SidType sidType = Utils.ClassifySID(sid); Debug.Assert(sidType != SidType.FakeObject); if (sidType == SidType.RealObjectFakeDomain) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "IsLocalMember: fake domain, SID={0}", Utils.ByteArrayToString(sid)); return true; } bool isLocal = false; // Ask the OS to resolve the SID to its target. int accountUsage = 0; string name; string domainName; int err = Utils.LookupSid( _storeCtx.MachineUserSuppliedName, _storeCtx.Credentials, sid, out name, out domainName, out accountUsage); if (err != 0) { GlobalDebug.WriteLineIf(GlobalDebug.Error, "SAMMembersSet", "IsLocalMember: LookupSid failed, sid={0}, server={1}, err={2}", Utils.ByteArrayToString(sid), _storeCtx.MachineUserSuppliedName, err); throw new PrincipalOperationException( string.Format(CultureInfo.CurrentCulture, SR.SAMStoreCtxErrorEnumeratingGroup, err)); } if (string.Equals(_storeCtx.MachineFlatName, domainName, StringComparison.OrdinalIgnoreCase)) isLocal = true; GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "IsLocalMember: sid={0}, isLocal={1}, domainName={2}", Utils.ByteArrayToString(sid), isLocal, domainName); return isLocal; } // Resets the enumerator to before the first result in the set. This potentially can be an expensive // operation, e.g., if doing a paged search, may need to re-retrieve the first page of results. // As a special case, if the ResultSet is already at the very beginning, this is guaranteed to be // a no-op. override internal void Reset() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "Reset"); if (!_atBeginning) { _groupsToVisit.Clear(); string originalGroupPath = _groupsVisited[0]; _groupsVisited.Clear(); _groupsVisited.Add(originalGroupPath); _group = _originalGroup; UnsafeNativeMethods.IADsMembers iADsMembers = _group.Members(); _membersEnumerator = ((IEnumerable)iADsMembers).GetEnumerator(); _current = null; _currentFakePrincipal = null; _currentForeign = null; _foreignMembers.Clear(); _foreignGroups.Clear(); if (_foreignResultSet != null) { _foreignResultSet.Dispose(); _foreignResultSet = null; } _atBeginning = true; } } override internal ResultSetBookmark BookmarkAndReset() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "Bookmarking"); SAMMembersSetBookmark bookmark = new SAMMembersSetBookmark(); bookmark.groupsToVisit = _groupsToVisit; _groupsToVisit = new List<string>(); string originalGroupPath = _groupsVisited[0]; bookmark.groupsVisited = _groupsVisited; _groupsVisited = new List<string>(); _groupsVisited.Add(originalGroupPath); bookmark.group = _group; bookmark.membersEnumerator = _membersEnumerator; _group = _originalGroup; UnsafeNativeMethods.IADsMembers iADsMembers = _group.Members(); _membersEnumerator = ((IEnumerable)iADsMembers).GetEnumerator(); bookmark.current = _current; bookmark.currentFakePrincipal = _currentFakePrincipal; bookmark.currentForeign = _currentForeign; _current = null; _currentFakePrincipal = null; _currentForeign = null; bookmark.foreignMembers = _foreignMembers; bookmark.foreignGroups = _foreignGroups; bookmark.foreignResultSet = _foreignResultSet; _foreignMembers = new List<DirectoryEntry>(); _foreignGroups = new List<GroupPrincipal>(); _foreignResultSet = null; bookmark.atBeginning = _atBeginning; _atBeginning = true; return bookmark; } override internal void RestoreBookmark(ResultSetBookmark bookmark) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "Restoring from bookmark"); Debug.Assert(bookmark is SAMMembersSetBookmark); SAMMembersSetBookmark samBookmark = (SAMMembersSetBookmark)bookmark; _groupsToVisit = samBookmark.groupsToVisit; _groupsVisited = samBookmark.groupsVisited; _group = samBookmark.group; _membersEnumerator = samBookmark.membersEnumerator; _current = samBookmark.current; _currentFakePrincipal = samBookmark.currentFakePrincipal; _currentForeign = samBookmark.currentForeign; _foreignMembers = samBookmark.foreignMembers; _foreignGroups = samBookmark.foreignGroups; if (_foreignResultSet != null) _foreignResultSet.Dispose(); _foreignResultSet = samBookmark.foreignResultSet; _atBeginning = samBookmark.atBeginning; } override public void Dispose() { try { if (!_disposed) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "Dispose: disposing"); if (_foreignResultSet != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "Dispose: disposing foreignResultSet"); _foreignResultSet.Dispose(); } _disposed = true; } } finally { base.Dispose(); } } // // Private fields // private bool _recursive; private bool _disposed = false; private SAMStoreCtx _storeCtx; private DirectoryEntry _ctxBase; private bool _atBeginning = true; // local // The 0th entry in this list is always the ADsPath of the original group whose membership we're querying private List<string> _groupsVisited = new List<string>(); private List<string> _groupsToVisit = new List<string>(); private DirectoryEntry _current = null; // current member of the group (if enumerating local group and found a real principal) private Principal _currentFakePrincipal = null; // current member of the group (if enumerating local group and found a fake pricipal) private UnsafeNativeMethods.IADsGroup _group; // the group whose membership we're currently enumerating over private UnsafeNativeMethods.IADsGroup _originalGroup; // the group whose membership we started off with (before recursing) private IEnumerator _membersEnumerator; // the current group's membership enumerator // foreign private List<DirectoryEntry> _foreignMembers = new List<DirectoryEntry>(); private Principal _currentForeign = null; // current member of the group (if enumerating foreign principal) private List<GroupPrincipal> _foreignGroups = new List<GroupPrincipal>(); private ResultSet _foreignResultSet = null; // current foreign group's ResultSet (if enumerating via proxy to foreign group) } internal class SAMMembersSetBookmark : ResultSetBookmark { public List<string> groupsToVisit; public List<string> groupsVisited; public UnsafeNativeMethods.IADsGroup group; public IEnumerator membersEnumerator; public DirectoryEntry current; public Principal currentFakePrincipal; public Principal currentForeign; public List<DirectoryEntry> foreignMembers; public List<GroupPrincipal> foreignGroups; public ResultSet foreignResultSet; public bool atBeginning; } } // #endif
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/spanner/v1/mutation.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Cloud.Spanner.V1 { /// <summary>Holder for reflection information generated from google/spanner/v1/mutation.proto</summary> public static partial class MutationReflection { #region Descriptor /// <summary>File descriptor for google/spanner/v1/mutation.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static MutationReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiBnb29nbGUvc3Bhbm5lci92MS9tdXRhdGlvbi5wcm90bxIRZ29vZ2xlLnNw", "YW5uZXIudjEaHGdvb2dsZS9hcGkvYW5ub3RhdGlvbnMucHJvdG8aHGdvb2ds", "ZS9wcm90b2J1Zi9zdHJ1Y3QucHJvdG8aHGdvb2dsZS9zcGFubmVyL3YxL2tl", "eXMucHJvdG8ixgMKCE11dGF0aW9uEjMKBmluc2VydBgBIAEoCzIhLmdvb2ds", "ZS5zcGFubmVyLnYxLk11dGF0aW9uLldyaXRlSAASMwoGdXBkYXRlGAIgASgL", "MiEuZ29vZ2xlLnNwYW5uZXIudjEuTXV0YXRpb24uV3JpdGVIABI9ChBpbnNl", "cnRfb3JfdXBkYXRlGAMgASgLMiEuZ29vZ2xlLnNwYW5uZXIudjEuTXV0YXRp", "b24uV3JpdGVIABI0CgdyZXBsYWNlGAQgASgLMiEuZ29vZ2xlLnNwYW5uZXIu", "djEuTXV0YXRpb24uV3JpdGVIABI0CgZkZWxldGUYBSABKAsyIi5nb29nbGUu", "c3Bhbm5lci52MS5NdXRhdGlvbi5EZWxldGVIABpTCgVXcml0ZRINCgV0YWJs", "ZRgBIAEoCRIPCgdjb2x1bW5zGAIgAygJEioKBnZhbHVlcxgDIAMoCzIaLmdv", "b2dsZS5wcm90b2J1Zi5MaXN0VmFsdWUaQwoGRGVsZXRlEg0KBXRhYmxlGAEg", "ASgJEioKB2tleV9zZXQYAiABKAsyGS5nb29nbGUuc3Bhbm5lci52MS5LZXlT", "ZXRCCwoJb3BlcmF0aW9uQpYBChVjb20uZ29vZ2xlLnNwYW5uZXIudjFCDU11", "dGF0aW9uUHJvdG9QAVo4Z29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29v", "Z2xlYXBpcy9zcGFubmVyL3YxO3NwYW5uZXKqAhdHb29nbGUuQ2xvdWQuU3Bh", "bm5lci5WMcoCF0dvb2dsZVxDbG91ZFxTcGFubmVyXFYxYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.StructReflection.Descriptor, global::Google.Cloud.Spanner.V1.KeysReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Spanner.V1.Mutation), global::Google.Cloud.Spanner.V1.Mutation.Parser, new[]{ "Insert", "Update", "InsertOrUpdate", "Replace", "Delete" }, new[]{ "Operation" }, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Spanner.V1.Mutation.Types.Write), global::Google.Cloud.Spanner.V1.Mutation.Types.Write.Parser, new[]{ "Table", "Columns", "Values" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Spanner.V1.Mutation.Types.Delete), global::Google.Cloud.Spanner.V1.Mutation.Types.Delete.Parser, new[]{ "Table", "KeySet" }, null, null, null)}) })); } #endregion } #region Messages /// <summary> /// A modification to one or more Cloud Spanner rows. Mutations can be /// applied to a Cloud Spanner database by sending them in a /// [Commit][google.spanner.v1.Spanner.Commit] call. /// </summary> public sealed partial class Mutation : pb::IMessage<Mutation> { private static readonly pb::MessageParser<Mutation> _parser = new pb::MessageParser<Mutation>(() => new Mutation()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Mutation> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Spanner.V1.MutationReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Mutation() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Mutation(Mutation other) : this() { switch (other.OperationCase) { case OperationOneofCase.Insert: Insert = other.Insert.Clone(); break; case OperationOneofCase.Update: Update = other.Update.Clone(); break; case OperationOneofCase.InsertOrUpdate: InsertOrUpdate = other.InsertOrUpdate.Clone(); break; case OperationOneofCase.Replace: Replace = other.Replace.Clone(); break; case OperationOneofCase.Delete: Delete = other.Delete.Clone(); break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Mutation Clone() { return new Mutation(this); } /// <summary>Field number for the "insert" field.</summary> public const int InsertFieldNumber = 1; /// <summary> /// Insert new rows in a table. If any of the rows already exist, /// the write or transaction fails with error `ALREADY_EXISTS`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Spanner.V1.Mutation.Types.Write Insert { get { return operationCase_ == OperationOneofCase.Insert ? (global::Google.Cloud.Spanner.V1.Mutation.Types.Write) operation_ : null; } set { operation_ = value; operationCase_ = value == null ? OperationOneofCase.None : OperationOneofCase.Insert; } } /// <summary>Field number for the "update" field.</summary> public const int UpdateFieldNumber = 2; /// <summary> /// Update existing rows in a table. If any of the rows does not /// already exist, the transaction fails with error `NOT_FOUND`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Spanner.V1.Mutation.Types.Write Update { get { return operationCase_ == OperationOneofCase.Update ? (global::Google.Cloud.Spanner.V1.Mutation.Types.Write) operation_ : null; } set { operation_ = value; operationCase_ = value == null ? OperationOneofCase.None : OperationOneofCase.Update; } } /// <summary>Field number for the "insert_or_update" field.</summary> public const int InsertOrUpdateFieldNumber = 3; /// <summary> /// Like [insert][google.spanner.v1.Mutation.insert], except that if the row already exists, then /// its column values are overwritten with the ones provided. Any /// column values not explicitly written are preserved. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Spanner.V1.Mutation.Types.Write InsertOrUpdate { get { return operationCase_ == OperationOneofCase.InsertOrUpdate ? (global::Google.Cloud.Spanner.V1.Mutation.Types.Write) operation_ : null; } set { operation_ = value; operationCase_ = value == null ? OperationOneofCase.None : OperationOneofCase.InsertOrUpdate; } } /// <summary>Field number for the "replace" field.</summary> public const int ReplaceFieldNumber = 4; /// <summary> /// Like [insert][google.spanner.v1.Mutation.insert], except that if the row already exists, it is /// deleted, and the column values provided are inserted /// instead. Unlike [insert_or_update][google.spanner.v1.Mutation.insert_or_update], this means any values not /// explicitly written become `NULL`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Spanner.V1.Mutation.Types.Write Replace { get { return operationCase_ == OperationOneofCase.Replace ? (global::Google.Cloud.Spanner.V1.Mutation.Types.Write) operation_ : null; } set { operation_ = value; operationCase_ = value == null ? OperationOneofCase.None : OperationOneofCase.Replace; } } /// <summary>Field number for the "delete" field.</summary> public const int DeleteFieldNumber = 5; /// <summary> /// Delete rows from a table. Succeeds whether or not the named /// rows were present. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Spanner.V1.Mutation.Types.Delete Delete { get { return operationCase_ == OperationOneofCase.Delete ? (global::Google.Cloud.Spanner.V1.Mutation.Types.Delete) operation_ : null; } set { operation_ = value; operationCase_ = value == null ? OperationOneofCase.None : OperationOneofCase.Delete; } } private object operation_; /// <summary>Enum of possible cases for the "operation" oneof.</summary> public enum OperationOneofCase { None = 0, Insert = 1, Update = 2, InsertOrUpdate = 3, Replace = 4, Delete = 5, } private OperationOneofCase operationCase_ = OperationOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OperationOneofCase OperationCase { get { return operationCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void ClearOperation() { operationCase_ = OperationOneofCase.None; operation_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Mutation); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Mutation other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Insert, other.Insert)) return false; if (!object.Equals(Update, other.Update)) return false; if (!object.Equals(InsertOrUpdate, other.InsertOrUpdate)) return false; if (!object.Equals(Replace, other.Replace)) return false; if (!object.Equals(Delete, other.Delete)) return false; if (OperationCase != other.OperationCase) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (operationCase_ == OperationOneofCase.Insert) hash ^= Insert.GetHashCode(); if (operationCase_ == OperationOneofCase.Update) hash ^= Update.GetHashCode(); if (operationCase_ == OperationOneofCase.InsertOrUpdate) hash ^= InsertOrUpdate.GetHashCode(); if (operationCase_ == OperationOneofCase.Replace) hash ^= Replace.GetHashCode(); if (operationCase_ == OperationOneofCase.Delete) hash ^= Delete.GetHashCode(); hash ^= (int) operationCase_; return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (operationCase_ == OperationOneofCase.Insert) { output.WriteRawTag(10); output.WriteMessage(Insert); } if (operationCase_ == OperationOneofCase.Update) { output.WriteRawTag(18); output.WriteMessage(Update); } if (operationCase_ == OperationOneofCase.InsertOrUpdate) { output.WriteRawTag(26); output.WriteMessage(InsertOrUpdate); } if (operationCase_ == OperationOneofCase.Replace) { output.WriteRawTag(34); output.WriteMessage(Replace); } if (operationCase_ == OperationOneofCase.Delete) { output.WriteRawTag(42); output.WriteMessage(Delete); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (operationCase_ == OperationOneofCase.Insert) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Insert); } if (operationCase_ == OperationOneofCase.Update) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Update); } if (operationCase_ == OperationOneofCase.InsertOrUpdate) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(InsertOrUpdate); } if (operationCase_ == OperationOneofCase.Replace) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Replace); } if (operationCase_ == OperationOneofCase.Delete) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Delete); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Mutation other) { if (other == null) { return; } switch (other.OperationCase) { case OperationOneofCase.Insert: Insert = other.Insert; break; case OperationOneofCase.Update: Update = other.Update; break; case OperationOneofCase.InsertOrUpdate: InsertOrUpdate = other.InsertOrUpdate; break; case OperationOneofCase.Replace: Replace = other.Replace; break; case OperationOneofCase.Delete: Delete = other.Delete; break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { global::Google.Cloud.Spanner.V1.Mutation.Types.Write subBuilder = new global::Google.Cloud.Spanner.V1.Mutation.Types.Write(); if (operationCase_ == OperationOneofCase.Insert) { subBuilder.MergeFrom(Insert); } input.ReadMessage(subBuilder); Insert = subBuilder; break; } case 18: { global::Google.Cloud.Spanner.V1.Mutation.Types.Write subBuilder = new global::Google.Cloud.Spanner.V1.Mutation.Types.Write(); if (operationCase_ == OperationOneofCase.Update) { subBuilder.MergeFrom(Update); } input.ReadMessage(subBuilder); Update = subBuilder; break; } case 26: { global::Google.Cloud.Spanner.V1.Mutation.Types.Write subBuilder = new global::Google.Cloud.Spanner.V1.Mutation.Types.Write(); if (operationCase_ == OperationOneofCase.InsertOrUpdate) { subBuilder.MergeFrom(InsertOrUpdate); } input.ReadMessage(subBuilder); InsertOrUpdate = subBuilder; break; } case 34: { global::Google.Cloud.Spanner.V1.Mutation.Types.Write subBuilder = new global::Google.Cloud.Spanner.V1.Mutation.Types.Write(); if (operationCase_ == OperationOneofCase.Replace) { subBuilder.MergeFrom(Replace); } input.ReadMessage(subBuilder); Replace = subBuilder; break; } case 42: { global::Google.Cloud.Spanner.V1.Mutation.Types.Delete subBuilder = new global::Google.Cloud.Spanner.V1.Mutation.Types.Delete(); if (operationCase_ == OperationOneofCase.Delete) { subBuilder.MergeFrom(Delete); } input.ReadMessage(subBuilder); Delete = subBuilder; break; } } } } #region Nested types /// <summary>Container for nested types declared in the Mutation message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// Arguments to [insert][google.spanner.v1.Mutation.insert], [update][google.spanner.v1.Mutation.update], [insert_or_update][google.spanner.v1.Mutation.insert_or_update], and /// [replace][google.spanner.v1.Mutation.replace] operations. /// </summary> public sealed partial class Write : pb::IMessage<Write> { private static readonly pb::MessageParser<Write> _parser = new pb::MessageParser<Write>(() => new Write()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Write> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Spanner.V1.Mutation.Descriptor.NestedTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Write() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Write(Write other) : this() { table_ = other.table_; columns_ = other.columns_.Clone(); values_ = other.values_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Write Clone() { return new Write(this); } /// <summary>Field number for the "table" field.</summary> public const int TableFieldNumber = 1; private string table_ = ""; /// <summary> /// Required. The table whose rows will be written. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Table { get { return table_; } set { table_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "columns" field.</summary> public const int ColumnsFieldNumber = 2; private static readonly pb::FieldCodec<string> _repeated_columns_codec = pb::FieldCodec.ForString(18); private readonly pbc::RepeatedField<string> columns_ = new pbc::RepeatedField<string>(); /// <summary> /// The names of the columns in [table][google.spanner.v1.Mutation.Write.table] to be written. /// /// The list of columns must contain enough columns to allow /// Cloud Spanner to derive values for all primary key columns in the /// row(s) to be modified. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> Columns { get { return columns_; } } /// <summary>Field number for the "values" field.</summary> public const int ValuesFieldNumber = 3; private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.ListValue> _repeated_values_codec = pb::FieldCodec.ForMessage(26, global::Google.Protobuf.WellKnownTypes.ListValue.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.ListValue> values_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.ListValue>(); /// <summary> /// The values to be written. `values` can contain more than one /// list of values. If it does, then multiple rows are written, one /// for each entry in `values`. Each list in `values` must have /// exactly as many entries as there are entries in [columns][google.spanner.v1.Mutation.Write.columns] /// above. Sending multiple lists is equivalent to sending multiple /// `Mutation`s, each containing one `values` entry and repeating /// [table][google.spanner.v1.Mutation.Write.table] and [columns][google.spanner.v1.Mutation.Write.columns]. Individual values in each list are /// encoded as described [here][google.spanner.v1.TypeCode]. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.ListValue> Values { get { return values_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Write); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Write other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Table != other.Table) return false; if(!columns_.Equals(other.columns_)) return false; if(!values_.Equals(other.values_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Table.Length != 0) hash ^= Table.GetHashCode(); hash ^= columns_.GetHashCode(); hash ^= values_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Table.Length != 0) { output.WriteRawTag(10); output.WriteString(Table); } columns_.WriteTo(output, _repeated_columns_codec); values_.WriteTo(output, _repeated_values_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Table.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Table); } size += columns_.CalculateSize(_repeated_columns_codec); size += values_.CalculateSize(_repeated_values_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Write other) { if (other == null) { return; } if (other.Table.Length != 0) { Table = other.Table; } columns_.Add(other.columns_); values_.Add(other.values_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Table = input.ReadString(); break; } case 18: { columns_.AddEntriesFrom(input, _repeated_columns_codec); break; } case 26: { values_.AddEntriesFrom(input, _repeated_values_codec); break; } } } } } /// <summary> /// Arguments to [delete][google.spanner.v1.Mutation.delete] operations. /// </summary> public sealed partial class Delete : pb::IMessage<Delete> { private static readonly pb::MessageParser<Delete> _parser = new pb::MessageParser<Delete>(() => new Delete()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Delete> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Spanner.V1.Mutation.Descriptor.NestedTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Delete() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Delete(Delete other) : this() { table_ = other.table_; KeySet = other.keySet_ != null ? other.KeySet.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Delete Clone() { return new Delete(this); } /// <summary>Field number for the "table" field.</summary> public const int TableFieldNumber = 1; private string table_ = ""; /// <summary> /// Required. The table whose rows will be deleted. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Table { get { return table_; } set { table_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "key_set" field.</summary> public const int KeySetFieldNumber = 2; private global::Google.Cloud.Spanner.V1.KeySet keySet_; /// <summary> /// Required. The primary keys of the rows within [table][google.spanner.v1.Mutation.Delete.table] to delete. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Spanner.V1.KeySet KeySet { get { return keySet_; } set { keySet_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Delete); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Delete other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Table != other.Table) return false; if (!object.Equals(KeySet, other.KeySet)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Table.Length != 0) hash ^= Table.GetHashCode(); if (keySet_ != null) hash ^= KeySet.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Table.Length != 0) { output.WriteRawTag(10); output.WriteString(Table); } if (keySet_ != null) { output.WriteRawTag(18); output.WriteMessage(KeySet); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Table.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Table); } if (keySet_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(KeySet); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Delete other) { if (other == null) { return; } if (other.Table.Length != 0) { Table = other.Table; } if (other.keySet_ != null) { if (keySet_ == null) { keySet_ = new global::Google.Cloud.Spanner.V1.KeySet(); } KeySet.MergeFrom(other.KeySet); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Table = input.ReadString(); break; } case 18: { if (keySet_ == null) { keySet_ = new global::Google.Cloud.Spanner.V1.KeySet(); } input.ReadMessage(keySet_); break; } } } } } } #endregion } #endregion } #endregion Designer generated code
using UnityEngine; using System.Collections; public class HeatTransfer : MonoBehaviour { private Texture2D texture = null; private bool heating = false; public int radius = 15; //circle size private float deltaX = 0.0f; private float deltaT = 0.1f; private float[] heatVals; private float[] heatPrecVals; public float maxTempatature = 250.0f; public float minTemparature = 0.0f; private float alpha = 0.8f; private ComputeShader cs_transfer; public GameObject flameParticle; private ColorMapping colorMapper; private Camera cam; // Use this for initialization void Start () { //add component's properties cs_transfer = Resources.Load("Scripts/CS_Transfer") as ComputeShader; if(flameParticle == null) flameParticle = Resources.Load("Prefabs/FlameParticles") as GameObject; texture = new Texture2D(256, 256, TextureFormat.ARGB32, false); GetComponent<Renderer>().material.mainTexture = texture; colorMapper = GetComponent<ColorMapping>(); Color32[] cols = texture.GetPixels32(); for (int i = 0; i < cols.Length; ++i) { cols[i] = GetColor(10.0f); } texture.SetPixels32(cols); texture.Apply(false); heatVals = new float[cols.Length]; heatPrecVals = new float[cols.Length]; for (int i = 0; i < cols.Length; ++i) { if (i >= 0 && i < 256) { heatVals[i] = 250.0f; heatPrecVals[i] = 250.0f; } else { heatVals[i] = 10.0f; heatPrecVals[i] = 10.0f; } } cam = Camera.main; Vector3 screenPos = new Vector3(Screen.width * 0.5f , Screen.height * 0.5f, 40.0f); Vector3 worldPos = cam.ScreenToWorldPoint(screenPos); Vector3 worldOffsetPos = cam.ScreenToWorldPoint(screenPos + new Vector3(1.0f, 0.0f, 0.0f)); deltaX = worldOffsetPos.x - worldPos.x; deltaT = deltaX / 1.5f; //deltaT = deltaX / (radius * 2); deltaT *= 0.1f; } // Update is called once per frame void Update () { if (Input.GetMouseButtonDown(0)) { heating = true; } if (heating && Input.GetMouseButton(0)) { RaycastHit ray = new RaycastHit(); if (!Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out ray)) { return; } Renderer renderer = ray.collider.GetComponent<Renderer>(); if (renderer == null || renderer.material == null || renderer.material.mainTexture == null) { return; } Vector2 pixelUV = ray.textureCoord; pixelUV.x *= texture.width; pixelUV.y *= texture.height; for (int i = -radius; i <= radius; ++i) { for (int j = -radius; j <= radius; ++j) { int x = (int)pixelUV.x + j; int y = (int)pixelUV.y + i; if (i*i + j*j <= radius * radius) { if( y * texture.width + x < heatVals.Length){ heatVals[y * texture.width + x] = maxTempatature; heatPrecVals[y * texture.width + x] = maxTempatature ; } } } } Color32[] cols = texture.GetPixels32(); for (int hi = 0; hi < heatVals.Length; ++hi) { cols[hi] = GetColor(heatVals[hi]); } texture.SetPixels32(cols); texture.Apply(false); Vector3 screenPos = Input.mousePosition + Vector3.forward * 10.0f; Vector3 targetPos = cam.ScreenToWorldPoint(screenPos); GameObject flame = (GameObject)Instantiate(flameParticle, targetPos, Quaternion.identity); flame.transform.parent = this.transform; } if (Input.GetMouseButtonUp(0)) { heating = false; } /*if (!heating)*/ { ComputeBuffer prevBuf = new ComputeBuffer(256 * 256, sizeof(float)); ComputeBuffer curBuf = new ComputeBuffer(256 * 256, sizeof(float)); prevBuf.SetData(heatPrecVals); curBuf.SetData(heatVals); HeatStep(prevBuf, curBuf, 0); HeatStep(curBuf, prevBuf, 0); prevBuf.GetData(heatPrecVals); curBuf.GetData(heatVals); prevBuf.Release(); curBuf.Release(); Color32[] cols = texture.GetPixels32(); for (int hi = 0; hi < heatVals.Length; ++hi) { cols[hi] = GetColor(heatVals[hi]); } texture.SetPixels32(cols); texture.Apply(false); } } Color32 GetColor(float t) { Color color = new Color(0,0,0); color = colorMapper.getColor(minTemparature, maxTempatature, t); byte R = (byte)(color.r * 255); byte G = (byte)(color.g * 255); byte B = (byte)(color.b * 255); return new Color32(R, G, B, 255); } Color32 GetColorRainbow(float t) { t = Mathf.Clamp(t, minTemparature, maxTempatature); float invMaxH = 1.0f / (maxTempatature - minTemparature); float zRel = (t - minTemparature) * invMaxH; float cR = 0, cG = 0, cB = 0; if (t == 200) { cB = 1.0f; } if (0 <= zRel && zRel < 0.2f) { cB = 1.0f; cG = zRel * 5.0f; } else if (0.2f <= zRel && zRel < 0.4f) { cG = 1.0f; cB = 1.0f - (zRel - 0.2f) * 5.0f; } else if (0.4f <= zRel && zRel < 0.6f) { cG = 1.0f; cR = (zRel - 0.4f) * 5.0f; } else if (0.6f <= zRel && zRel < 0.8f) { cR = 1.0f; cG = 1.0f - (zRel - 0.6f) * 5.0f; } else { cR = 1.0f; cG = (zRel - 0.8f) * 5.0f; cB = cG; } byte R = (byte)(cR * 255); byte G = (byte)(cG * 255); byte B = (byte)(cB * 255); return new Color32(R, G, B, 255); } void HeatStep(ComputeBuffer heatPrev, ComputeBuffer heatVals, int kernelNum) { if (!SystemInfo.supportsComputeShaders) return; cs_transfer.SetVector("g_params", new Vector4(deltaX, deltaT, alpha, 1.0f)); cs_transfer.SetBuffer(kernelNum, "Prev", heatPrev); cs_transfer.SetBuffer(kernelNum, "Result", heatVals); cs_transfer.Dispatch(kernelNum, 256, 256, 1); /* for (int y = 1; y < texture.height - 1; ++y) { for (int x = 1; x < texture.width - 1; ++x) { float origVal = heatPrev[y * texture.width + x]; float vVal = -2.0f * origVal; float uxx = vVal + heatPrev[y * texture.width + x - 1] + heatPrev[y * texture.width + x + 1]; float uyy = vVal + heatPrev[(y - 1) * texture.width + x] + heatPrev[(y + 1) * texture.width + x]; float temp = 1.0f / deltaX; temp *= temp; float val = origVal + deltaT * alpha * (uxx + uyy) * temp; heatVals[y * texture.width + x] = val; } } */ } /* void HeatStep(float[] heatPrev, float[] heatVals) { for (int y = 1; y < texture.height - 1; ++y) { for (int x = 1; x < texture.width - 1; ++x) { float origVal = heatPrev[y * texture.width + x]; float vVal = -2.0f * origVal; float uxx = vVal + heatPrev[y * texture.width + x - 1] + heatPrev[y * texture.width + x + 1]; float uyy = vVal + heatPrev[(y - 1) * texture.width + x] + heatPrev[(y + 1) * texture.width + x]; float temp = 1.0f / deltaX; temp *= temp; float val = origVal + deltaT * alpha * (uxx + uyy) * temp; heatVals[y * texture.width + x] = val; } } } */ }
// -------------------------------------------------------------------------------------------------------------------- // Copyright (c) Lead Pipe Software. All rights reserved. // Licensed under the MIT License. Please see the LICENSE file in the project root for full license information. // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using LeadPipe.Net.Extensions; namespace LeadPipe.Net.Authorization { /// <summary> /// A fluent authorization class. /// </summary> public class Authorizer : IAuthorizer, IAuthorizerActions, IAuthorizerWhen, IAuthorizerUser, IAuthorizerCan, IAuthorizerAssertions, IAuthorizerApplication { #region Constants and Fields /// <summary> /// The name of the calling method. /// </summary> private string callingMethodName; /// <summary> /// The name of the calling type. /// </summary> private string callingTypeName; /// <summary> /// The activity names. /// </summary> private IList<Activity> activities; /// <summary> /// The application name. /// </summary> private Application application; /// <summary> /// The exception to throw. /// </summary> private Exception exception; /// <summary> /// The next Boolean value. /// </summary> private bool not; /// <summary> /// Determines if the authorizer should throw an exception if not authorized. /// </summary> private bool shouldThrow; /// <summary> /// The user context. /// </summary> private User user; /// <summary> /// Determines if all the activities need to be authorized. /// </summary> private bool authorizeAllActivities; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="Authorizer"/> class. /// </summary> public Authorizer() { } /// <summary> /// Initializes a new instance of the <see cref="Authorizer"/> class. /// </summary> /// <param name="authorizationProvider">The authorization provider.</param> public Authorizer(IAuthorizationProvider authorizationProvider) { this.AuthorizationProvider = authorizationProvider; } #endregion #region Public Properties /// <summary> /// Gets or sets the authorization provider. /// </summary> public virtual IAuthorizationProvider AuthorizationProvider { get; set; } /// <summary> /// Gets the start of the fluent authorizer chain. /// </summary> public IAuthorizerActions Will { get { Guard.Will.ThrowExceptionOfType<LeadPipeNetSecurityException>("The Authorizer requires an Authorization Provider.").When(this.AuthorizationProvider.IsNull()); var frame = new StackFrame(1); var method = frame.GetMethod(); this.callingMethodName = method.Name; if (method.DeclaringType != null) { this.callingTypeName = method.DeclaringType.Name; } return this; } } /// <summary> /// The Assert chain method. /// </summary> /// <returns> /// The Authorizer set to assert the authorization result. /// </returns> public IAuthorizerUser Assert { get { this.shouldThrow = false; return this; } } /// <summary> /// Determines whether this instance [can]. /// </summary> /// <returns>The Authorizer.</returns> public IAuthorizerAssertions Can { get { this.not = false; return this; } } /// <summary> /// Inverts Boolean fluent members. /// </summary> /// <returns>The Authorizer.</returns> public IAuthorizerAssertions Not { get { this.not = true; return this; } } /// <summary> /// Gets the when. /// </summary> public IAuthorizerUser When { get { return this; } } #endregion #region Public Methods and Operators /// <summary> /// Sets the activity name(s). If more than one, only one needs to be authorized. /// </summary> /// <param name="activities">The activities.</param> /// <returns> /// The Authorizer with an activity name set. /// </returns> public IAuthorizerApplication ExecuteAnyOfTheseActivities(params Activity[] activities) { Guard.Will.ProtectAgainstNullArgument(() => activities); this.activities = activities; return this; } /// <summary> /// Sets the activity name(s). If more than one, all will be authorized. /// </summary> /// <param name="activities">The activity name(s).</param> /// <returns> /// The Authorizer with an activity name set. /// </returns> public IAuthorizerApplication ExecuteAllOfTheseActivities(params Activity[] activities) { Guard.Will.ProtectAgainstNullArgument(() => activities); this.activities = activities; this.authorizeAllActivities = true; return this; } /// <summary> /// Sets the user. /// </summary> /// <param name="user">The user.</param> /// <returns> /// The Authorizer with a user. /// </returns> public IAuthorizerCan User(User user) { Guard.Will.ProtectAgainstNullArgument(() => user); this.user = user; return this; } /// <summary> /// Sets the application name and performs the authorization assertion. /// </summary> /// <param name="application"> /// Name of the application. /// </param> /// <returns> /// <c>true</c> if the user can perform the specified activity; otherwise, <c>false</c>. /// </returns> public bool In(Application application) { Guard.Will.ProtectAgainstNullArgument(() => application); this.application = application; var applicationUser = new ApplicationUser { Application = this.application, User = this.user }; var authorizationRequest = new AuthorizationRequest { ApplicationUser = applicationUser, Activities = this.activities, AuthorizeAll = this.authorizeAllActivities }; return this.Authorize(authorizationRequest); } /// <summary> /// The Throw chain method. /// </summary> /// <returns> /// The Authorizer set to throw an exception if the authorization fails. /// </returns> public IAuthorizerWhen ThrowAccessDeniedException() { this.shouldThrow = true; return this; } /// <summary> /// The Throw chain method. /// </summary> /// <param name="message"> /// The exception message. /// </param> /// <returns> /// The Authorizer set to throw an exception if the authorization fails. /// </returns> public IAuthorizerWhen ThrowAccessDeniedException(string message) { // Throw an exception of the specified type... this.exception = (LeadPipeNetAccessDeniedException)Activator.CreateInstance(typeof(LeadPipeNetAccessDeniedException), message); return this; } #endregion #region Methods /// <summary> /// Authorizes this instance. /// </summary> /// <param name="authorizationRequest"> /// The authorization request. /// </param> /// <returns> /// True if authorized. False otherwise. /// </returns> private bool Authorize(AuthorizationRequest authorizationRequest) { var authorizationResult = this.AuthorizationProvider.Authorize(authorizationRequest); if (this.shouldThrow) { // If we don't already have an exception built up then build the default exception... if (this.exception == null) { var exceptionMessage = new StringBuilder(); exceptionMessage.Append(this.user.Login.FormattedWith("{0} is not authorized to perform ")); if (authorizationRequest.Activities != null) { if (authorizationRequest.Activities.Count() > 1) { var activityNames = authorizationRequest.Activities.Select(activity => activity.Name).ToList(); if (activityNames.Count() > 2) { activityNames[activityNames.Count() - 1] = "or " + activityNames[activityNames.Count() - 1]; exceptionMessage.Append(activityNames.WrapEachWith(string.Empty, string.Empty, ", ")); } else { exceptionMessage.Append(activityNames.WrapEachWith(string.Empty, string.Empty, " or ")); } } else if (authorizationRequest.Activities.Count() == 1) { var firstOrDefault = authorizationRequest.Activities.FirstOrDefault(); exceptionMessage.Append(firstOrDefault != null ? firstOrDefault.Name.ToFriendlyName().FormattedWith("the \"{0}\" activity") : "Unknown".FormattedWith("the \"{0}\" activity")); } } exceptionMessage.Append(authorizationRequest.ApplicationUser.Application.Name.FormattedWith(" in {0}.")); this.exception = new LeadPipeNetAccessDeniedException(exceptionMessage.ToString()); } // If CAN... if (!this.not) { if (authorizationResult) { return true; } throw this.exception; } // If CAN NOT... if (this.not) { // Throw if they can... if (authorizationResult) { return true; } throw this.exception; } } // If CAN NOT return the inverse... if (this.not) { return !authorizationResult; } return authorizationResult; } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace TodoListService.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// 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; namespace System.Buffers.Text { public static partial class Utf8Parser { private enum ComponentParseResult : byte { // Do not change or add values in this enum unless you review every use of the TimeSpanSplitter.Separators field. That field is an "array of four // ComponentParseResults" encoded as a 32-bit integer with each of its four bytes containing one of 0 (NoMoreData), 1 (Colon) or 2 (Period). // (So a value of 0x01010200 means the string parsed as "nn:nn:nn.nnnnnnn") NoMoreData = 0, Colon = 1, Period = 2, ParseFailure = 3, } private struct TimeSpanSplitter { public uint V1; public uint V2; public uint V3; public uint V4; public uint V5; public bool IsNegative; // Encodes an "array of four ComponentParseResults" as a 32-bit integer with each of its four bytes containing one of 0 (NoMoreData), 1 (Colon) or 2 (Period). // (So a value of 0x01010200 means the string parsed as "nn:nn:nn.nnnnnnn") public uint Separators; public bool TrySplitTimeSpan(ReadOnlySpan<byte> source, bool periodUsedToSeparateDay, out int bytesConsumed) { int srcIndex = 0; byte c = default; // Unlike many other data types, TimeSpan allow leading whitespace. while (srcIndex != source.Length) { c = source[srcIndex]; if (!(c == ' ' || c == '\t')) break; srcIndex++; } if (srcIndex == source.Length) { bytesConsumed = 0; return false; } // Check for an option negative sign. ('+' is not allowed.) if (c == Utf8Constants.Minus) { IsNegative = true; srcIndex++; if (srcIndex == source.Length) { bytesConsumed = 0; return false; } } // From here, we terminate on anything that's not a digit, ':' or '.' The '.' is only allowed after at least three components have // been specified. If we see it earlier, we'll assume that's an error and fail out rather than treating it as the end of data. // // Timespan has to start with a number - parse the first one. // if (!TryParseUInt32D(source.Slice(srcIndex), out V1, out int justConsumed)) { bytesConsumed = 0; return false; } srcIndex += justConsumed; // // Split out the second number (if any) For the 'c' format, a period might validly appear here as it;s used both to separate the day and the fraction - however, // the fraction is always the fourth component at earliest, so if we do see a period at this stage, always parse the integer as a regular integer, not as // a fraction. // ComponentParseResult result = ParseComponent(source, neverParseAsFraction: periodUsedToSeparateDay, ref srcIndex, out V2); if (result == ComponentParseResult.ParseFailure) { bytesConsumed = 0; return false; } else if (result == ComponentParseResult.NoMoreData) { bytesConsumed = srcIndex; return true; } else { Debug.Assert(result == ComponentParseResult.Colon || result == ComponentParseResult.Period); Separators |= ((uint)result) << 24; } // // Split out the third number (if any) // result = ParseComponent(source, false, ref srcIndex, out V3); if (result == ComponentParseResult.ParseFailure) { bytesConsumed = 0; return false; } else if (result == ComponentParseResult.NoMoreData) { bytesConsumed = srcIndex; return true; } else { Debug.Assert(result == ComponentParseResult.Colon || result == ComponentParseResult.Period); Separators |= ((uint)result) << 16; } // // Split out the fourth number (if any) // result = ParseComponent(source, false, ref srcIndex, out V4); if (result == ComponentParseResult.ParseFailure) { bytesConsumed = 0; return false; } else if (result == ComponentParseResult.NoMoreData) { bytesConsumed = srcIndex; return true; } else { Debug.Assert(result == ComponentParseResult.Colon || result == ComponentParseResult.Period); Separators |= ((uint)result) << 8; } // // Split out the fifth number (if any) // result = ParseComponent(source, false, ref srcIndex, out V5); if (result == ComponentParseResult.ParseFailure) { bytesConsumed = 0; return false; } else if (result == ComponentParseResult.NoMoreData) { bytesConsumed = srcIndex; return true; } else { Debug.Assert(result == ComponentParseResult.Colon || result == ComponentParseResult.Period); Separators |= (uint)result; } // // There cannot legally be a sixth number. If the next character is a period or colon, treat this as a error as it's likely // to indicate the start of a sixth number. Otherwise, treat as end of parse with data left over. // if (srcIndex != source.Length && (source[srcIndex] == Utf8Constants.Period || source[srcIndex] == Utf8Constants.Colon)) { bytesConsumed = 0; return false; } bytesConsumed = srcIndex; return true; } // // Look for a separator followed by an unsigned integer. // private static ComponentParseResult ParseComponent(ReadOnlySpan<byte> source, bool neverParseAsFraction, ref int srcIndex, out uint value) { if (srcIndex == source.Length) { value = default; return ComponentParseResult.NoMoreData; } byte c = source[srcIndex]; if (c == Utf8Constants.Colon || (c == Utf8Constants.Period && neverParseAsFraction)) { srcIndex++; if (!TryParseUInt32D(source.Slice(srcIndex), out value, out int bytesConsumed)) { value = default; return ComponentParseResult.ParseFailure; } srcIndex += bytesConsumed; return c == Utf8Constants.Colon ? ComponentParseResult.Colon : ComponentParseResult.Period; } else if (c == Utf8Constants.Period) { srcIndex++; if (!TryParseTimeSpanFraction(source.Slice(srcIndex), out value, out int bytesConsumed)) { value = default; return ComponentParseResult.ParseFailure; } srcIndex += bytesConsumed; return ComponentParseResult.Period; } else { value = default; return ComponentParseResult.NoMoreData; } } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections; using System.Linq; using System.Text; using System.IO; using System.Diagnostics.Contracts; using System.Web.UI.Adapters; using System.ComponentModel; namespace System.Web.UI { public class Control { protected internal virtual void AddedControl(Control control, int index) { Contract.Requires(control != null); } // protected virtual void AddParsedSubObject(object obj); // public virtual void ApplyStyleSheetSkin(Page page); // protected void BuildProfileTree(string parentId, bool calcViewState) // protected void ClearChildControlState(); // protected void ClearChildState(); // protected void ClearChildViewState(); // protected internal virtual void CreateChildControls(); // protected virtual ControlCollection CreateControlCollection(); // public virtual void DataBind(); // protected virtual void DataBind(bool raiseOnDataBinding); // protected virtual void DataBindChildren(); // public virtual void Dispose(); // protected virtual void EnsureChildControls(); // protected void EnsureID(); [Pure] public virtual Control FindControl(string id) { Contract.Requires(id != null); return default(Control); } [Pure] protected virtual Control FindControl(string id, int pathOffset) { Contract.Requires(id != null); return default(Control); } // public virtual void Focus(); [Pure] protected virtual IDictionary GetDesignModeState() { Contract.Ensures(Contract.Result<IDictionary>() != null); return default(IDictionary); } [Pure] public virtual bool HasControls() { return default(bool); } [Pure] protected bool HasEvents() { return default(bool); } [Pure] protected bool IsLiteralContent() { return default(bool); } // protected internal virtual void LoadControlState(object savedState); // internal void LoadControlStateInternal(object savedStateObj); // protected virtual void LoadViewState(object savedState); protected internal string MapPathSecure(string virtualPath) { Contract.Requires(!String.IsNullOrEmpty(virtualPath)); Contract.Ensures(Contract.Result<string>() != null); return default(string); } protected virtual bool OnBubbleEvent(object source, EventArgs args) { Contract.Requires(source != null); Contract.Requires(args != null); return default(bool); } protected virtual void OnDataBinding(EventArgs e) { Contract.Requires(e != null); } protected internal virtual void OnInit(EventArgs e) { Contract.Requires(e != null); } protected internal virtual void OnLoad(EventArgs e) { Contract.Requires(e != null); } protected internal virtual void OnPreRender(EventArgs e) { Contract.Requires(e != null); } protected internal virtual void OnUnload(EventArgs e) { Contract.Requires(e != null); } protected internal Stream OpenFile(string path) { Contract.Requires(path != null); Contract.Ensures(Contract.Result<Stream>() != null); return default(Stream); } protected void RaiseBubbleEvent(object source, EventArgs args) { Contract.Requires(source != null); Contract.Requires(args != null); } protected internal virtual void RemovedControl(Control control) { Contract.Requires(control != null); } protected internal virtual void Render(HtmlTextWriter writer) { Contract.Requires(writer != null); } protected internal virtual void RenderChildren(HtmlTextWriter writer) { Contract.Requires(writer != null); } public virtual void RenderControl(HtmlTextWriter writer) { Contract.Requires(writer != null); } protected void RenderControl(HtmlTextWriter writer, ControlAdapter adapter) { Contract.Requires(writer != null); } //protected virtual ControlAdapter ResolveAdapter() public virtual string ResolveClientUrl(string relativeUrl) { Contract.Requires(relativeUrl != null); Contract.Ensures(Contract.Result<string>() != null); return default(string); } public string ResolveUrl(string relativeUrl) { Contract.Requires(relativeUrl != null); Contract.Ensures(Contract.Result<string>() != null); return default(string); } // protected internal virtual object SaveControlState(); // protected virtual object SaveViewState(); // protected virtual void SetDesignModeState(IDictionary data); //public void SetRenderMethodDelegate(RenderMethod renderMethod); // protected virtual void TrackViewState(); // Properties // protected ControlAdapter Adapter { get; } //public string AppRelativeTemplateSourceDirectory { get; [EditorBrowsable(EditorBrowsableState.Never)] set; } // public Control BindingContainer // protected bool ChildControlsCreated { get; set; } public virtual string ClientID { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } // protected char ClientIDSeparator { get; } // protected internal virtual HttpContext Context { get; } public virtual ControlCollection Controls { get { Contract.Ensures(Contract.Result<ControlCollection>() != null); return default(ControlCollection); } } // protected internal bool DesignMode { get; } // internal bool EnableLegacyRendering { get; } // public virtual bool EnableTheming { get; set; } // public virtual bool EnableViewState { get; set; } protected EventHandlerList Events { get { Contract.Ensures(Contract.Result<EventHandlerList>() != null); return default(EventHandlerList); } } // protected bool HasChildViewState { get; } // public virtual string ID { get; set; } // protected char IdSeparator { get; } // protected internal bool IsChildControlStateCleared { get; } // protected bool IsTrackingViewState { get; } // protected internal bool IsViewStateEnabled { get; } // protected bool LoadViewStateByID { get; } // public virtual Control NamingContainer { get; } // public virtual Page Page { get; set; } // public virtual Control Parent { get; } // public ISite Site { get; set; } public virtual string SkinID { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } //public TemplateControl TemplateControl { get; [EditorBrowsable(EditorBrowsableState.Never)] set; } public virtual string TemplateSourceDirectory { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public virtual string UniqueID { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } protected virtual StateBag ViewState { get { Contract.Ensures(Contract.Result<StateBag>() != null); return default(StateBag); } } //protected virtual bool ViewStateIgnoresCase { get; } //public virtual bool Visible { get; set; } } public class StateBag { } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Hatfield.AnalyteManagement.Web.Areas.HelpPage.ModelDescriptions; using Hatfield.AnalyteManagement.Web.Areas.HelpPage.Models; namespace Hatfield.AnalyteManagement.Web.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using NGUI.Internal; using NGUI.UI; using UnityEngine; // ReSharper disable once CheckNamespace public abstract class UIWidget : MonoBehaviour { [CompilerGenerated] private static Comparison<UIWidget> f__amScache14; protected bool mChanged = true; [SerializeField, HideInInspector] private Color mColor = Color.white; [SerializeField, HideInInspector] private int mDepth; public Vector3 mDiffPos; public Quaternion mDiffRot; public Vector3 mDiffScale; private bool mForceVisible; private UIGeometry mGeom = new UIGeometry(); protected GameObject mGo; private float mLastAlpha; private Matrix4x4 mLocalToPanel; [HideInInspector, SerializeField] protected Material mMat; private Vector3 mOldV0; private Vector3 mOldV1; protected UIPanel mPanel; [HideInInspector, SerializeField] private Pivot mPivot = Pivot.Center; protected bool mPlayMode = true; [HideInInspector, SerializeField] protected Texture mTex; protected Transform mTrans; private bool mVisibleByPanel = true; protected UIWidget() { } protected virtual void Awake() { this.mGo = gameObject; this.mPlayMode = Application.isPlaying; } public void CheckLayer() { if (this.mPanel != null && this.mPanel.gameObject.layer != gameObject.layer) { Debug.LogWarning("You can't place widgets on a layer different than the UIPanel that manages them.\nIf you want to move widgets to a different layer, parent them to a new panel instead.", this); gameObject.layer = this.mPanel.gameObject.layer; } } [Obsolete("Use ParentHasChanged() instead")] public void CheckParent() { this.ParentHasChanged(); } public static int CompareFunc(UIWidget left, UIWidget right) { if (left.mDepth > right.mDepth) { return 1; } if (left.mDepth < right.mDepth) { return -1; } return 0; } public void CreatePanel() { if (this.mPanel == null && enabled && NGUITools.GetActive(gameObject) && this.material != null) { this.mPanel = UIPanel.Find(this.cachedTransform); if (this.mPanel != null) { this.CheckLayer(); this.mPanel.AddWidget(this); this.mChanged = true; } } } public virtual void MakePixelPerfect() { Vector3 localScale = this.cachedTransform.localScale; int num = Mathf.RoundToInt(localScale.x); int num2 = Mathf.RoundToInt(localScale.y); localScale.x = num; localScale.y = num2; localScale.z = 1f; Vector3 localPosition = this.cachedTransform.localPosition; localPosition.z = Mathf.RoundToInt(localPosition.z); if (num % 2 == 1 && (this.pivot == Pivot.Top || this.pivot == Pivot.Center || this.pivot == Pivot.Bottom)) { localPosition.x = Mathf.Floor(localPosition.x) + 0.5f; } else { localPosition.x = Mathf.Round(localPosition.x); } if (num2 % 2 == 1 && (this.pivot == Pivot.Left || this.pivot == Pivot.Center || this.pivot == Pivot.Right)) { localPosition.y = Mathf.Ceil(localPosition.y) - 0.5f; } else { localPosition.y = Mathf.Round(localPosition.y); } this.cachedTransform.localPosition = localPosition; this.cachedTransform.localScale = localScale; } public virtual void MarkAsChanged() { this.mChanged = true; if (this.mPanel != null && enabled && NGUITools.GetActive(gameObject) && !Application.isPlaying && this.material != null) { this.mPanel.AddWidget(this); this.CheckLayer(); } } public void MarkAsChangedLite() { this.mChanged = true; } private void OnDestroy() { if (this.mPanel != null) { this.mPanel.RemoveWidget(this); this.mPanel = null; } } private void OnDisable() { if (!this.keepMaterial) { this.material = null; } else if (this.mPanel != null) { this.mPanel.RemoveWidget(this); } this.mPanel = null; } protected virtual void OnEnable() { this.mChanged = true; if (!this.keepMaterial) { this.mMat = null; this.mTex = null; } this.mPanel = null; } public virtual void OnFill(List<Vector3> verts, List<Vector2> uvs, List<Color32> cols) { } protected virtual void OnStart() { } public void ParentHasChanged() { if (this.mPanel != null) { UIPanel panel = UIPanel.Find(this.cachedTransform); if (this.mPanel != panel) { this.mPanel.RemoveWidget(this); if (!this.keepMaterial || Application.isPlaying) { this.material = null; } this.mPanel = null; this.CreatePanel(); } } } public static List<UIWidget> Raycast(GameObject root, Vector2 mousePos) { List<UIWidget> list = new List<UIWidget>(); UICamera camera = UICamera.FindCameraForLayer(root.layer); if (camera != null) { Camera cachedCamera = camera.cachedCamera; foreach (UIWidget widget in root.GetComponentsInChildren<UIWidget>()) { if (NGUIMath.DistanceToRectangle(NGUIMath.CalculateWidgetCorners(widget), mousePos, cachedCamera) == 0f) { list.Add(widget); } } if (f__amScache14 == null) { f__amScache14 = (w1, w2) => w2.mDepth.CompareTo(w1.mDepth); } list.Sort(f__amScache14); } return list; } private void Start() { this.OnStart(); this.CreatePanel(); } public virtual void Update() { if (this.mPanel == null) { this.CreatePanel(); } } public bool UpdateGeometry(UIPanel p, bool forceVisible) { if (this.material != null && p != null) { this.mPanel = p; bool flag = false; float finalAlpha = this.finalAlpha; bool flag2 = finalAlpha > 0.001f; bool flag3 = forceVisible || this.mVisibleByPanel; if (this.cachedTransform.hasChanged) { this.mTrans.hasChanged = false; if (!this.mPanel.widgetsAreStatic) { Vector2 relativeSize = this.relativeSize; Vector2 pivotOffset = this.pivotOffset; Vector4 relativePadding = this.relativePadding; float x = pivotOffset.x * relativeSize.x - relativePadding.x; float y = pivotOffset.y * relativeSize.y + relativePadding.y; float num4 = x + relativeSize.x + relativePadding.x + relativePadding.z; float num5 = y - relativeSize.y - relativePadding.y - relativePadding.w; this.mLocalToPanel = p.worldToLocal * this.cachedTransform.localToWorldMatrix; flag = true; Vector3 v = new Vector3(x, y, 0f); Vector3 vector5 = new Vector3(num4, num5, 0f); v = this.mLocalToPanel.MultiplyPoint3x4(v); vector5 = this.mLocalToPanel.MultiplyPoint3x4(vector5); if (Vector3.SqrMagnitude(this.mOldV0 - v) > 1E-06f || Vector3.SqrMagnitude(this.mOldV1 - vector5) > 1E-06f) { this.mChanged = true; this.mOldV0 = v; this.mOldV1 = vector5; } } if (flag2 || this.mForceVisible != forceVisible) { this.mForceVisible = forceVisible; flag3 = forceVisible || this.mPanel.IsVisible(this); } } else if (flag2 && this.mForceVisible != forceVisible) { this.mForceVisible = forceVisible; flag3 = this.mPanel.IsVisible(this); } if (this.mVisibleByPanel != flag3) { this.mVisibleByPanel = flag3; this.mChanged = true; } if (this.mVisibleByPanel && this.mLastAlpha != finalAlpha) { this.mChanged = true; } this.mLastAlpha = finalAlpha; if (this.mChanged) { this.mChanged = false; if (this.isVisible) { this.mGeom.Clear(); this.OnFill(this.mGeom._vertices, this.mGeom._uvs, this.mGeom._colors); if (this.mGeom.HasVertices) { Vector3 vector6 = this.pivotOffset; Vector2 vector7 = this.relativeSize; vector6.x *= vector7.x; vector6.y *= vector7.y; if (!flag) { this.mLocalToPanel = p.worldToLocal * this.cachedTransform.localToWorldMatrix; } this.mGeom.ApplyOffset(vector6); this.mGeom.ApplyTransform(this.mLocalToPanel); } return true; } if (this.mGeom.HasVertices) { this.mGeom.Clear(); return true; } } } return false; } public void WriteToBuffers(List<Vector3> v, List<Vector2> u, List<Color32> c, List<Vector3> n, List<Vector4> t) { this.mGeom.WriteToBuffers(v, u, c, n, t); } public float alpha { get { return this.mColor.a; } set { Color mColor = this.mColor; mColor.a = value; this.color = mColor; } } public virtual Vector4 border { get { return Vector4.zero; } } public GameObject cachedGameObject { get { if (this.mGo == null) { this.mGo = gameObject; } return this.mGo; } } public Transform cachedTransform { get { if (this.mTrans == null) { this.mTrans = transform; } return this.mTrans; } } public Color color { get { return this.mColor; } set { if (!this.mColor.Equals(value)) { this.mColor = value; this.mChanged = true; } } } public int depth { get { return this.mDepth; } set { if (this.mDepth != value) { this.mDepth = value; if (this.mPanel != null) { this.mPanel.MarkMaterialAsChanged(this.material, true); } } } } public float finalAlpha { get { if (this.mPanel == null) { this.CreatePanel(); } return this.mPanel == null ? this.mColor.a : this.mColor.a * this.mPanel.alpha; } } public bool isVisible { get { return this.mVisibleByPanel && this.finalAlpha > 0.001f; } } public virtual bool keepMaterial { get { return false; } } public virtual Texture mainTexture { get { Material material = this.material; if (material != null) { if (material.mainTexture != null) { this.mTex = material.mainTexture; } else if (this.mTex != null) { if (this.mPanel != null) { this.mPanel.RemoveWidget(this); } this.mPanel = null; this.mMat.mainTexture = this.mTex; if (enabled) { this.CreatePanel(); } } } return this.mTex; } set { Material material = this.material; if (material == null || material.mainTexture != value) { if (this.mPanel != null) { this.mPanel.RemoveWidget(this); } this.mPanel = null; this.mTex = value; material = this.material; if (material != null) { material.mainTexture = value; if (enabled) { this.CreatePanel(); } } } } } public virtual Material material { get { return this.mMat; } set { if (this.mMat != value) { if (this.mMat != null && this.mPanel != null) { this.mPanel.RemoveWidget(this); } this.mPanel = null; this.mMat = value; this.mTex = null; if (this.mMat != null) { this.CreatePanel(); } } } } public UIPanel panel { get { if (this.mPanel == null) { this.CreatePanel(); } return this.mPanel; } set { this.mPanel = value; } } public Pivot pivot { get { return this.mPivot; } set { if (this.mPivot != value) { Vector3 vector = NGUIMath.CalculateWidgetCorners(this)[0]; this.mPivot = value; this.mChanged = true; Vector3 vector2 = NGUIMath.CalculateWidgetCorners(this)[0]; Transform cachedTransform = this.cachedTransform; Vector3 position = cachedTransform.position; float z = cachedTransform.localPosition.z; position.x += vector.x - vector2.x; position.y += vector.y - vector2.y; this.cachedTransform.position = position; position = this.cachedTransform.localPosition; position.x = Mathf.Round(position.x); position.y = Mathf.Round(position.y); position.z = z; this.cachedTransform.localPosition = position; } } } public Vector2 pivotOffset { get { Vector2 zero = Vector2.zero; Vector4 relativePadding = this.relativePadding; Pivot pivot = this.pivot; switch (pivot) { case Pivot.Top: case Pivot.Center: case Pivot.Bottom: zero.x = (relativePadding.x - relativePadding.z - 1f) * 0.5f; break; default: if (pivot != Pivot.TopRight && pivot != Pivot.Right && pivot != Pivot.BottomRight) { zero.x = relativePadding.x; } else { zero.x = -1f - relativePadding.z; } break; } switch (pivot) { case Pivot.Left: case Pivot.Center: case Pivot.Right: zero.y = (relativePadding.w - relativePadding.y + 1f) * 0.5f; return zero; } if (pivot != Pivot.BottomLeft && pivot != Pivot.Bottom && pivot != Pivot.BottomRight) { zero.y = -relativePadding.y; return zero; } zero.y = 1f + relativePadding.w; return zero; } } public virtual bool pixelPerfectAfterResize { get { return false; } } public virtual Vector4 relativePadding { get { return Vector4.zero; } } public virtual Vector2 relativeSize { get { return Vector2.one; } } public enum Pivot { TopLeft, Top, TopRight, Left, Center, Right, BottomLeft, Bottom, BottomRight } }
//--------------------------------------------------------------------------------- // Copyright 2013 Ceton Corp // Copyright 2013-2015 Tomasz Cielecki ([email protected]) // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, // INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR // CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing // permissions and limitations under the License. //--------------------------------------------------------------------------------- using System; using System.Globalization; using Android.Content; using Android.Preferences; using Cheesebaron.MvxPlugins.Settings.Interfaces; namespace Cheesebaron.MvxPlugins.Settings.Droid { public class Settings : ISettings { private readonly string SettingFileName; private ISharedPreferences SharedPreferences { get { var context = Android.App.Application.Context; //If file name is empty use defaults if(string.IsNullOrEmpty(SettingFileName)) return PreferenceManager.GetDefaultSharedPreferences(context); return context.GetSharedPreferences(SettingFileName, FileCreationMode.Append); } } /// <summary> /// Must not be combined with Settings(string settingsFileName) /// </summary> public Settings() { SettingFileName = "Cheesebaron.MvxPlugins.Settings.xml"; } /// <summary> /// Must keep compatibility with old version, and permits upgrade without loosing settings /// </summary> public Settings(string settingsFileName) { SettingFileName = settingsFileName; } public T GetValue<T>(string key, T defaultValue = default(T)) { if(string.IsNullOrEmpty(key)) throw new ArgumentException("Key must have a value", "key"); var type = typeof(T); if(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) type = Nullable.GetUnderlyingType(type); object returnVal; if(!Contains(key)) returnVal = defaultValue; else using(var sharedPrefs = SharedPreferences) { switch(Type.GetTypeCode(type)) { case TypeCode.Boolean: returnVal = sharedPrefs.GetBoolean(key, Convert.ToBoolean(defaultValue)); break; case TypeCode.Int64: try { returnVal = sharedPrefs.GetLong(key, Convert.ToInt64(defaultValue)); } catch(Exception) { returnVal = (long) sharedPrefs.GetInt(key, Convert.ToInt32(defaultValue)); } break; case TypeCode.Double: var s = sharedPrefs.GetString(key, ""); double dr; if (String.IsNullOrWhiteSpace(s) || !Double.TryParse(s, NumberStyles.Any, CultureInfo.InvariantCulture, out dr)) returnVal = defaultValue; else returnVal = dr; break; case TypeCode.Int32: returnVal = sharedPrefs.GetInt(key, Convert.ToInt32(defaultValue)); break; case TypeCode.Single: returnVal = sharedPrefs.GetFloat(key, Convert.ToSingle(defaultValue)); break; case TypeCode.String: returnVal = sharedPrefs.GetString(key, Convert.ToString(defaultValue)); break; case TypeCode.DateTime: { var ticks = sharedPrefs.GetLong(key, -1); if(ticks == -1) returnVal = defaultValue; else returnVal = new DateTime(ticks); break; } default: if(type.Name == typeof(DateTimeOffset).Name) { var ticks = sharedPrefs.GetString(key, ""); if(String.IsNullOrWhiteSpace(ticks)) returnVal = defaultValue; else returnVal = DateTimeOffset.Parse(ticks); break; } if(type.Name == typeof(Guid).Name) { var guid = sharedPrefs.GetString(key, ""); if(!string.IsNullOrEmpty(guid)) { Guid outGuid; Guid.TryParse(guid, out outGuid); returnVal = outGuid; } else returnVal = defaultValue; break; } throw new ArgumentException(string.Format("Type {0} is not supported", type), "defaultValue"); } } return (T) returnVal; } public bool AddOrUpdateValue<T>(string key, T value = default(T)) { if(string.IsNullOrEmpty(key)) throw new ArgumentException("Key must have a value", "key"); var type = typeof(T); if(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) type = Nullable.GetUnderlyingType(type); using(var sharedPrefs = SharedPreferences) using(var editor = sharedPrefs.Edit()) { switch(Type.GetTypeCode(type)) { case TypeCode.Boolean: editor.PutBoolean(key, Convert.ToBoolean(value)); break; case TypeCode.Int64: editor.PutLong(key, Convert.ToInt64(value)); break; case TypeCode.Int32: editor.PutInt(key, Convert.ToInt32(value)); break; case TypeCode.Single: editor.PutFloat(key, Convert.ToSingle(value)); break; case TypeCode.Double: editor.PutString(key, ((double)(object)value).ToString("G17", CultureInfo.InvariantCulture)); break; case TypeCode.String: editor.PutString(key, Convert.ToString(value)); break; case TypeCode.DateTime: editor.PutLong(key, ((DateTime) (object) value).Ticks); break; default: if(type.Name == typeof(DateTimeOffset).Name) { editor.PutString(key, ((DateTimeOffset) (object) value).ToString("o")); break; } if(type.Name == typeof(Guid).Name) { var g = value as Guid?; if(g.HasValue) editor.PutString(key, g.Value.ToString()); break; } throw new ArgumentException(string.Format("Type {0} is not supported", type), "value"); } return editor.Commit(); } } public bool Contains(string key) { if(string.IsNullOrEmpty(key)) throw new ArgumentException("Key must have a value", "key"); using(var defaults = SharedPreferences) { try { return defaults.Contains(key); } catch { return false; } } } public bool DeleteValue(string key) { if(string.IsNullOrEmpty(key)) throw new ArgumentException("Key must have a value", "key"); using(var sharedPrefs = SharedPreferences) using(var editor = sharedPrefs.Edit()) { editor.Remove(key); return editor.Commit(); } } public bool ClearAllValues() { using(var sharedPrefs = SharedPreferences) using(var editor = sharedPrefs.Edit()) { editor.Clear(); return editor.Commit(); } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public abstract class Vehicle : MonoBehaviour { protected float fwdRate, strafeRate, jumpRate, maxSpeed, explodeSpeed; [SerializeField] [Header("Vehicle Settings")] protected float resetDelay = 1; [SerializeField] private AudioClip[] jumpSFX, bounceSFX, explodeSFX; private AudioSource m_audioSource; [SerializeField] protected GameObject explodeFXPrefab; /// <summary> /// Child class to set these via input /// </summary> [Header("Vehicle Read Only")] [SerializeField] protected float m_fwdSpeed = 0; [SerializeField] protected float m_strafeSpeed = 0; [SerializeField] protected bool m_jumping = false, m_jumpPressed = false; private Rigidbody m_rigidbody; private Collider m_collider; public float Speed { get { return m_fwdSpeed; } } public float MaxSpeed { get { return maxSpeed; } } public enum State { Idle, Moving, Jumping, Crashed }; [SerializeField] private State m_state = State.Idle, m_prevState; public State VehicleState { get { return m_state; } } #region Pure Virtuals /// <summary> /// Obtain input and set m_fwdSpeed, m_strafeSpeed and m_jumpPressed, and call on every frame of gameplay /// </summary> protected abstract void HandleInput(); protected abstract void PostExplode(); protected abstract void PreExplode(); #endregion #region MonoBehaviour protected virtual void Start() { SetValues(); } void FixedUpdate() { Vector3 delta = new Vector3(m_strafeSpeed * Time.fixedDeltaTime, 0, m_fwdSpeed * Time.fixedDeltaTime); //Vector3 delta = new Vector3(m_strafeSpeed, 0, m_fwdSpeed); if (m_state != State.Crashed) { if (delta == Vector3.zero && m_state != State.Jumping) SwitchState(State.Idle); else if (m_state == State.Idle) SwitchState(State.Moving); } Vector3 newPos = transform.position + delta; m_rigidbody.MovePosition(newPos); if (m_jumpPressed && !m_jumping) { m_rigidbody.AddForce(0, jumpRate, 0, ForceMode.Impulse); m_audioSource.PlayOneShot(jumpSFX[Random.Range(0, jumpSFX.Length)]); m_jumping = true; } //CheckAhead(); } void OnCollisionEnter(Collision other) { ContactPoint[] points = other.contacts; if (m_collider.enabled && other.collider.tag.Equals("Ground")) { if (points[0].normal == Vector3.up) { m_jumping = false; SwitchState(m_prevState); m_audioSource.PlayOneShot(bounceSFX[Random.Range(0, bounceSFX.Length)], 0.5f); } if (points[0].normal == Vector3.back) { Logger.Log("Head on collision detected", this); if (m_fwdSpeed > explodeSpeed) StartCoroutine(Explode()); else m_fwdSpeed = 0; } } } void OnCollisionStay(Collision other) { ContactPoint[] points = other.contacts; if (m_collider.enabled && other.collider.tag.Equals("Ground")) { if (points[0].normal == Vector3.back) { Logger.Log("Head on collision detected", this); if (m_fwdSpeed > explodeSpeed) StartCoroutine(Explode()); else m_fwdSpeed = 0; } } } void OnCollisionExit(Collision other) { if (m_collider.enabled && other.collider.tag.Equals("Ground")) { m_jumping = true; SwitchState(State.Jumping); } } #endregion #region Implementation protected void SetValues() { m_rigidbody = GetComponent<Rigidbody>(); m_audioSource = GetComponent<AudioSource>(); m_collider = GetComponent<Collider>(); LevelManager lm = LevelManager.Instance; maxSpeed = lm.MaxSpeed; fwdRate = lm.FwdRate; strafeRate = lm.StrafeRate; jumpRate = lm.JumpRate; explodeSpeed = lm.ExplodeSpeed; } protected void SwitchState(State to) { if (m_state == to) return; if (to == State.Crashed) { m_prevState = m_state; m_state = to; Logger.Log("Player has crashed", this, Logger.Priority.Notification); return; } switch (m_state) { case State.Idle: switch (to) { case State.Moving: m_prevState = m_state; m_state = State.Moving; Logger.Log("Player is now moving", this, Logger.Priority.Notification); break; case State.Jumping: m_prevState = m_state; m_state = State.Jumping; Logger.Log("Player is now jumping", this, Logger.Priority.Notification); break; } break; case State.Moving: switch (to) { case State.Idle: m_prevState = m_state; m_state = State.Idle; Logger.Log("Player is now idle", this, Logger.Priority.Notification); break; case State.Jumping: m_prevState = m_state; m_state = State.Jumping; Logger.Log("Player is now jumping", this, Logger.Priority.Notification); break; } break; case State.Jumping: switch (to) { case State.Moving: case State.Idle: m_state = to; Logger.Log("Player has completed jumping", this, Logger.Priority.Notification); break; } break; case State.Crashed: switch (to) { case State.Idle: m_prevState = m_state; m_state = State.Idle; Logger.Log("Player is now Idle", this, Logger.Priority.Notification); break; } break; } } protected void Reset() { Logger.Log("Resetting Vehicle", this, Logger.Priority.Notification); m_rigidbody.isKinematic = false; // Switching kinematics is causing weird respawn issues //m_rigidbody.velocity = Vector3.zero; m_rigidbody.useGravity = true; m_collider.enabled = true; m_rigidbody.velocity = Vector3.zero; SwitchState(State.Idle); } void CheckAhead() { Bounds cb = m_collider.bounds; float rayDist = cb.max.z - transform.position.z; Ray ray = new Ray(transform.position, Vector3.forward); RaycastHit hit; bool isClear = !Physics.Raycast(ray, out hit, rayDist * 3); if (!isClear && hit.distance <= rayDist) { Logger.Log("Collision", this, Logger.Priority.Notification); if (hit.collider.tag.Equals("Ground") || hit.collider.tag.Equals("Obstacle")) { if (m_fwdSpeed > explodeSpeed) StartCoroutine(Explode()); else { Logger.Log("Speed not enough to explode", this, Logger.Priority.Notification); m_fwdSpeed = 0; } } } } protected IEnumerator Explode() { PreExplode(); m_rigidbody.isKinematic = true; // Switching kinematics is causing weird respawn issues m_rigidbody.useGravity = false; m_collider.enabled = false; m_strafeSpeed = 0; m_audioSource.PlayOneShot(explodeSFX[Random.Range(0, explodeSFX.Length)], 0.5f); if (explodeFXPrefab != null) { GameObject explosionFX = (GameObject)Instantiate(explodeFXPrefab, transform.position, Quaternion.identity); Logger.Log("Created explosion VFX", this); Destroy(explosionFX, explosionFX.GetComponent<ParticleSystem>().duration); } Logger.Log("Exploding", this, Logger.Priority.Notification); SwitchState(State.Crashed); while (m_fwdSpeed > 0) { m_fwdSpeed -= (maxSpeed * 0.1f); if (m_fwdSpeed < 0) m_fwdSpeed = 0; yield return null; } yield return new WaitForSeconds(1); PostExplode(); } #endregion }
// HTEditorTool v2.0 (MArs 2013) // HTEditorTool library is copyright (c) of Hedgehog Team // Please send feedback or bug reports to [email protected] using UnityEngine; using System.Collections; using UnityEditor; public class HTEditorToolKit{ public static Texture2D gradientTexture; public static Texture2D gradientChildTexture; public static Texture2D colorTexture; #region Helper public static void DrawTitle(string text){ GUIStyle labelStyle = new GUIStyle( EditorStyles.label); labelStyle.fontStyle = FontStyle.Bold; Color textColor=Color.black; if (EditorGUIUtility.isProSkin){ textColor = new Color( 242f/255f,152f/255f,13f/255f); } labelStyle.onActive.textColor = textColor; labelStyle.onFocused.textColor = textColor; labelStyle.onHover.textColor = textColor; labelStyle.onNormal.textColor = textColor; labelStyle.active.textColor = textColor; labelStyle.focused.textColor = textColor; labelStyle.hover.textColor = textColor; labelStyle.normal.textColor = textColor; Rect lastRect = DrawTitleGradient(); GUI.color = Color.white; EditorGUI.LabelField(new Rect(lastRect.x + 3, lastRect.y+1, lastRect.width - 5, lastRect.height),text,labelStyle); GUI.color = Color.white; } public static void DrawTitleChild(string text){ GUIStyle labelStyle = new GUIStyle( EditorStyles.label); Color textColor=Color.black; if (EditorGUIUtility.isProSkin){ textColor = new Color( 242f/255f,152f/255f,13f/255f); } labelStyle.onActive.textColor = textColor; labelStyle.onFocused.textColor = textColor; labelStyle.onHover.textColor = textColor; labelStyle.onNormal.textColor = textColor; labelStyle.active.textColor = textColor; labelStyle.focused.textColor = textColor; labelStyle.hover.textColor = textColor; labelStyle.normal.textColor = textColor; Rect lastRect = DrawTitleChildGradient(); GUI.color = Color.white; EditorGUI.LabelField(new Rect(lastRect.x + 3, lastRect.y+1, lastRect.width - 5, lastRect.height),text,labelStyle); GUI.color = Color.white; } public static bool DrawTitleFoldOut( bool foldOut,string text){ GUIStyle foldOutStyle = new GUIStyle( EditorStyles.foldout); foldOutStyle.fontStyle = FontStyle.Bold; Color foldTextColor=Color.black; if (EditorGUIUtility.isProSkin){ foldTextColor = new Color( 242f/255f,152f/255f,13f/255f); } foldOutStyle.onActive.textColor = foldTextColor; foldOutStyle.onFocused.textColor = foldTextColor; foldOutStyle.onHover.textColor = foldTextColor; foldOutStyle.onNormal.textColor = foldTextColor; foldOutStyle.active.textColor = foldTextColor; foldOutStyle.focused.textColor = foldTextColor; foldOutStyle.hover.textColor = foldTextColor; foldOutStyle.normal.textColor = foldTextColor; Rect lastRect = DrawTitleGradient(); GUI.color = Color.white; bool value = EditorGUI.Foldout(new Rect(lastRect.x + 3, lastRect.y+1, lastRect.width - 5, lastRect.height),foldOut,text,foldOutStyle); GUI.color = Color.white; return value; } public static bool DrawTitleChildFoldOut( bool foldOut,string text, int padding=0){ GUIStyle foldOutStyle = new GUIStyle( EditorStyles.foldout); //foldOutStyle.fontStyle = FontStyle.Bold; Color foldTextColor=Color.black; if (EditorGUIUtility.isProSkin){ foldTextColor = new Color( 242f/255f,152f/255f,13f/255f); } foldOutStyle.onActive.textColor = foldTextColor; foldOutStyle.onFocused.textColor = foldTextColor; foldOutStyle.onHover.textColor = foldTextColor; foldOutStyle.onNormal.textColor = foldTextColor; foldOutStyle.active.textColor = foldTextColor; foldOutStyle.focused.textColor = foldTextColor; foldOutStyle.hover.textColor = foldTextColor; foldOutStyle.normal.textColor = foldTextColor; Rect lastRect = DrawTitleChildGradient(padding); GUI.color = Color.white; bool value = EditorGUI.Foldout(new Rect(lastRect.x + 3, lastRect.y+1, lastRect.width - 5, lastRect.height),foldOut,text,foldOutStyle); GUI.color = Color.white; return value; } public static void DrawSeparatorLine(int padding=0) { GUILayout.Space(10); Rect lastRect = GUILayoutUtility.GetLastRect(); GUI.color = Color.gray; GUI.DrawTexture(new Rect(padding, lastRect.yMax-0, Screen.width, 1f), EditorGUIUtility.whiteTexture); GUI.color = Color.white; } private static Rect DrawTitleGradient() { GUILayout.Space(30); Rect lastRect = GUILayoutUtility.GetLastRect(); lastRect.yMin = lastRect.yMin + 5; lastRect.yMax = lastRect.yMax - 5; lastRect.width = Screen.width; GUI.DrawTexture(new Rect(0,lastRect.yMin,Screen.width, lastRect.yMax- lastRect.yMin), GetGradientTexture()); GUI.color = new Color(0.54f,0.54f,0.54f); GUI.DrawTexture(new Rect(0,lastRect.yMin,Screen.width,1f), EditorGUIUtility.whiteTexture); GUI.DrawTexture(new Rect(0,lastRect.yMax- 1f,Screen.width,1f), EditorGUIUtility.whiteTexture); return lastRect; } private static Rect DrawTitleChildGradient(int padding=0){ GUILayout.Space(30); Rect lastRect = GUILayoutUtility.GetLastRect(); lastRect.yMin = lastRect.yMin + 5; lastRect.yMax = lastRect.yMax - 5; lastRect.width = Screen.width; GUI.DrawTexture(new Rect(padding,lastRect.yMin,Screen.width, lastRect.yMax- lastRect.yMin), GetChildGradientTexture()); GUI.color = new Color(0.54f,0.54f,0.54f); GUI.DrawTexture(new Rect(padding,lastRect.yMin,Screen.width,1f), EditorGUIUtility.whiteTexture); GUI.DrawTexture(new Rect(padding,lastRect.yMax- 1f,Screen.width,1f), EditorGUIUtility.whiteTexture); return lastRect; } private static Texture2D GetColorTexture(Color color){ Texture2D myTexture = new Texture2D(1, 16); //myTexture.set_name("Color Texture by Hedgehog Team"); myTexture.hideFlags = HideFlags.HideInInspector; myTexture.filterMode = FilterMode.Bilinear; myTexture.hideFlags = HideFlags.DontSave; for (int i = 0; i < 16; i++) { myTexture.SetPixel(0, i, color); } myTexture.Apply(); return myTexture; } private static Texture2D GetGradientTexture(){ if (HTEditorToolKit.gradientTexture==null){ HTEditorToolKit.gradientTexture = CreateGradientTexture(); } return gradientTexture; } private static Texture2D CreateGradientTexture( ) { Texture2D myTexture = new Texture2D(1, 16); //myTexture.set_name("Gradient Texture by Hedgehog Team"); myTexture.hideFlags = HideFlags.HideInInspector; myTexture.filterMode = FilterMode.Bilinear; myTexture.hideFlags = HideFlags.DontSave; float start=0.4f; float end= 0.8f; float step = (end-start)/16; Color color = new Color(start,start,start); Color pixColor = color; for (int i = 0; i < 16; i++) { pixColor = new Color (pixColor.r+step, pixColor.b+step, pixColor.b+step,0.5f); myTexture.SetPixel(0, i, pixColor); } myTexture.Apply(); return myTexture; } private static Texture2D GetChildGradientTexture(){ if (HTEditorToolKit.gradientChildTexture==null){ HTEditorToolKit.gradientChildTexture = CreateChildGradientTexture(); } return gradientChildTexture; } private static Texture2D CreateChildGradientTexture( ) { Texture2D myTexture = new Texture2D(1, 16); //myTexture.set_name("Gradient Texture by Hedgehog Team"); myTexture.hideFlags = HideFlags.HideInInspector; myTexture.filterMode = FilterMode.Bilinear; myTexture.hideFlags = HideFlags.DontSave; float start=0.4f; float end= 0.8f; float step = (end-start)/16; Color color = new Color(start,start,start); Color pixColor = color; for (int i = 0; i < 16; i++) { pixColor = new Color (pixColor.r+step, pixColor.b+step, pixColor.b+step,0.2f); myTexture.SetPixel(0, i, pixColor); } myTexture.Apply(); return myTexture; } #endregion #region Asset tool public static bool CreateAssetDirectory(string rootPath,string name){ string directory = rootPath + "/" + name; if (!System.IO.Directory.Exists(directory)){ AssetDatabase.CreateFolder(rootPath,name); return true; } return false; } public static string GetAssetRootPath( string path){ string[] tokens = path.Split('/'); path=""; for (int i=0;i<tokens.Length-1;i++){ path+= tokens[i] +"/"; } return path; } #endregion }
using System.Collections.Generic; using System.Reflection; using UnityEngine; namespace SpeedrunTimerMod { class Cheats : MonoBehaviour { public static bool Enabled { get; set; } public static bool InvincibilityEnabled { get; private set; } public static bool FlashWatermarkOnStart { get; set; } public static bool LevelLoadedByCheat { get; private set; } static bool _loadingLevel; static FieldInfo _previousSphereField; static FieldInfo _activeColorSpheresField; static FieldInfo _allColorSpheresField; List<Savepoint> _savepoints; List<BeatLayerSwitch> _beatSwitches; Utils.Label _cheatWatermark; float _playerHue; AudioSource _cheatBeep; public void FlashWatermarkAcrossLoad() { FlashWatermarkOnStart = true; FlashWatermark(); } public void FlashWatermark(bool playSound = true) { if (!ModLoader.Settings.FlashCheatWatermark) return; _cheatWatermark.ResetTimer(); _cheatWatermark.Enabled = true; if (playSound) { _cheatBeep.Play(); } } void Awake() { if (!_loadingLevel) LevelLoadedByCheat = false; else _loadingLevel = false; _cheatBeep = gameObject.AddComponent<AudioSource>(); _cheatBeep.clip = Resources.Instance.CheatBeep; _cheatWatermark = new Utils.Label { positionDelegate = () => new Rect(0, UI.ScaleVertical(100), Screen.width, Screen.height - UI.ScaleVertical(100)), text = "CHEATS ENABLED", fontSize = 40, enableOutline = true, outlineColor = Color.black, style = new GUIStyle { fontStyle = FontStyle.Bold, alignment = TextAnchor.UpperCenter } }; if (ModLoader.Settings.FlashCheatWatermark) { _cheatWatermark.fontSize = 60; _cheatWatermark.positionDelegate = () => new Rect(0, 0, Screen.width, Screen.height); _cheatWatermark.displayTime = 2f; _cheatWatermark.text = "CHEAT USED"; _cheatWatermark.style.alignment = TextAnchor.MiddleCenter; } _cheatWatermark.style.normal.textColor = Color.magenta; } void Start() { if (Application.loadedLevelName == "Level_Menu") { InvincibilityEnabled = false; } if (FlashWatermarkOnStart) { FlashWatermarkOnStart = false; FlashWatermark(); } LoadTeleportPoints(); } void LoadTeleportPoints() { _savepoints = new List<Savepoint>(); _beatSwitches = new List<BeatLayerSwitch>(); var levelsFolder = GameObject.Find("Levels"); if (!levelsFolder) return; foreach (var savepoint in levelsFolder.GetComponentsInChildren<Savepoint>()) { if (!(savepoint is SpawnPoint)) _savepoints.Add(savepoint); } _savepoints.Sort((s1, s2) => s1.GetGlobalSavepointID().CompareTo(s2.GetGlobalSavepointID())); _beatSwitches.AddRange(levelsFolder.GetComponentsInChildren<BeatLayerSwitch>()); _beatSwitches.Sort((s1, s2) => s1.globalBeatLayer.CompareTo(s2.globalBeatLayer)); // last switch of level 1 is out of bounds // hub switch will bug out if used with cheats if (Application.loadedLevel <= 1) _beatSwitches.RemoveAt(_beatSwitches.Count - 1); } void Update() { if (Application.isLoadingLevel) return; if (!Enabled) { if ((Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) && Input.GetKeyDown(KeyCode.F12)) { Enabled = true; FlashWatermark(); } else return; } var player = Globals.player.GetComponent<MyCharacterController>(); var rightAlt = Input.GetKey(KeyCode.RightAlt); if (rightAlt || Input.GetKey(KeyCode.LeftAlt)) { for (var key = KeyCode.Alpha1; key <= KeyCode.Alpha4; key++) { if (!Input.GetKeyDown(key)) continue; FlashWatermarkAcrossLoad(); LoadLevel(key - KeyCode.Alpha0, rightAlt); break; } } else if (!player.IsForceMoveActive() && !player.IsLogicPause()) { for (var key = KeyCode.Alpha1; key <= KeyCode.Alpha9; key++) { int keyNum = key - KeyCode.Alpha1; if (Input.GetKeyDown(key)) { FlashWatermark(); TeleportToBeatLayerSwitch(keyNum); } } } if (Input.GetKeyDown(KeyCode.Delete)) { FlashWatermark(); TeleportToCurrentCheckpoint(); } else if (Input.GetKeyDown(KeyCode.Home)) { FlashWatermark(); var savepoint = _savepoints[0]; TeleportToSavepoint(savepoint); } else if (Input.GetKeyDown(KeyCode.End)) { FlashWatermark(); var savepoint = _savepoints[_savepoints.Count - 1]; TeleportToSavepoint(savepoint); } else if (Input.GetKeyDown(KeyCode.PageUp)) { FlashWatermark(); TeleportToNearestCheckpoint(); } else if (Input.GetKeyDown(KeyCode.PageDown)) { FlashWatermark(); TeleportToNearestCheckpoint(false); } if (Input.GetKeyDown(KeyCode.Backspace)) { FlashWatermark(); TogglePlayerColor(); } if (Input.GetKeyUp(KeyCode.I) && Application.loadedLevelName != "Level_Menu") { FlashWatermark(); InvincibilityEnabled = !InvincibilityEnabled; } if (Input.GetKeyDown(KeyCode.Q)) { FlashWatermark(); KillPlayer(); } RainbowPlayerUpdate(); } void RainbowPlayerUpdate() { if (!InvincibilityEnabled) return; var player = Globals.player.GetComponent<MyCharacterController>(); var c = Utils.HslToRgba(_playerHue, 1, 0.5f, 1); player.visualPlayer.SetColor(c, 1f); _playerHue += 0.5f * Time.deltaTime; if (_playerHue > 1) _playerHue = 0; } public static void LoadLevel(int level, bool mirrored) { // levels are offset by 1 in the 2017 update if (!ModLoader.IsLegacyVersion) level++; MirrorModeManager.mirrorModeActive = mirrored; MirrorModeManager.respawnFromMirror = false; _loadingLevel = true; LevelLoadedByCheat = true; Application.LoadLevel(level); } void TeleportToBeatLayerSwitch(int id) { if (id == 4 && Application.loadedLevelName.StartsWith("Level1_")) { var levelsFolder = GameObject.Find("Levels"); var bossGate = levelsFolder.GetComponentInChildren<BossGate>(); if (bossGate) TeleportToBeatLayerSwitch(bossGate); return; } if (id < 0 || id >= _beatSwitches.Count) { return; } var beatSwitch = _beatSwitches[id]; if (beatSwitch.globalBeatLayer > Globals.beatMaster.GetCurrentBeatLayer()) { // change the colors of the level and player according to the gate var player = Globals.player.GetComponent<MyCharacterController>(); player.visualPlayer.SetColor((id % 2 == 0) ? Color.black : Color.white, 1f); CheatColorSphere(id + 1); } TeleportToBeatLayerSwitch(beatSwitch); } void CheatColorSphere(int beatIndex) { if (beatIndex < 1) { return; } if (_previousSphereField == null) { _previousSphereField = typeof(ColorChangeSystem) .GetField("previousSphere", BindingFlags.Instance | BindingFlags.NonPublic); } if (_activeColorSpheresField == null) { _activeColorSpheresField = typeof(ColorChangeSystem) .GetField("activeColorSpheres", BindingFlags.Instance | BindingFlags.NonPublic); } if (_allColorSpheresField == null) { _allColorSpheresField = typeof(ColorChangeSystem) .GetField("allColorSpheres", BindingFlags.Instance | BindingFlags.NonPublic); } var previousSphere = (ColorSphere)_previousSphereField.GetValue(Globals.colorChangeSystem); var activeColorSpheres = (List<ColorSphere>)_activeColorSpheresField.GetValue(Globals.colorChangeSystem); var allColorSpheres = (List<ColorSphere>)_allColorSpheresField.GetValue(Globals.colorChangeSystem); activeColorSpheres.Clear(); if (beatIndex == 1) { _previousSphereField.SetValue(Globals.colorChangeSystem, null); activeColorSpheres.Add(allColorSpheres.Find(colorSphere => colorSphere.beatLayer == -1)); return; } if (beatIndex == 2) { var prev = allColorSpheres.Find(colorSphere => colorSphere.beatLayer == -1); _previousSphereField.SetValue(Globals.colorChangeSystem, prev); activeColorSpheres.Add(allColorSpheres.Find(colorSphere => colorSphere.beatLayer == 1)); return; } var previous = allColorSpheres.Find(colorSphere => colorSphere.beatLayer == beatIndex - 2); _previousSphereField.SetValue(Globals.colorChangeSystem, previous); activeColorSpheres.Add(allColorSpheres.Find(colorSphere => colorSphere.beatLayer == beatIndex - 1)); } public static void TeleportToBeatLayerSwitch(BeatLayerSwitch beatSwitch) { var player = Globals.player.GetComponent<MyCharacterController>(); player.SetVelocity(Vector2.zero); player.PlacePlayerCharacter(beatSwitch.transform.position, true); if (beatSwitch.globalBeatLayer >= Globals.beatMaster.GetCurrentBeatLayer()) beatSwitch.CheatUse(); } public static void TeleportToBeatLayerSwitch(BossGate bossGate) { var player = Globals.player.GetComponent<MyCharacterController>(); player.SetVelocity(Vector2.zero); player.PlacePlayerCharacter(bossGate.transform.position, true); bossGate.CheatUse(); } public static void TeleportToSavepoint(Savepoint savepoint) { var player = Globals.player.GetComponent<MyCharacterController>(); player.StopForceMoveTo(); player.PlacePlayerCharacter(savepoint.transform.position, savepoint.spawnPlayerOnGround); } public static void TeleportToCurrentCheckpoint() { var savepoint = Globals.levelsManager.GetSavepoint(); TeleportToSavepoint(savepoint); } public void TeleportToNearestCheckpoint(bool searchToRight = true) { var savepoint = GetNearestCheckpoint(searchToRight); if (savepoint != null) TeleportToSavepoint(savepoint); } Savepoint GetNearestCheckpoint(bool searchToRight = true) { var levelManager = Globals.levelsManager; var playerPos = Globals.player.transform.position; var currentSavePoint = levelManager.GetSavepoint(); var i = searchToRight ? 0 : _savepoints.Count - 1; for (; i >= 0 && i < _savepoints.Count; i += searchToRight ? 1 : -1) { var savepoint = _savepoints[i]; var savepointPos = savepoint.transform.position; var distance = savepointPos.x - playerPos.x; if (searchToRight) { if (distance > 0.1) return savepoint; } else { if (distance < -0.1) return savepoint; } } return null; } static Savepoint GetSavepoint(int id) { var originalCheckpt = Globals.levelsManager.GetCurrentCheckPoint(); Globals.levelsManager.SetCurrentCheckpoint(id); var s = Globals.levelsManager.GetSavepoint(); Globals.levelsManager.SetCurrentCheckpoint(originalCheckpt); return s; } public static void TogglePlayerColor() { var player = Globals.player.GetComponent<MyCharacterController>(); var color = player.visualPlayer.GetColor() == Color.black ? Color.white : Color.black; player.visualPlayer.SetColor(color, 1); } public static void KillPlayer() { var player = Globals.player.GetComponent<MyCharacterController>(); player.Kill(); } void OnGUI() { if (!Enabled) return; _cheatWatermark.OnGUI(); } } }
/* * BottomNavigationBar for Xamarin Forms * Copyright (c) 2016 Thrive GmbH and others (http://github.com/thrive-now). * * 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.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.IO; using System.Linq; using BottomBar.XamarinForms; using BottomNavigationBar; using BottomNavigationBar.Listeners; using Android.Views; using Android.Widget; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using Xamarin.Forms.Platform.Android.AppCompat; using BottomBar.Droid.Renderers; using BottomBar.Droid.Utils; [assembly: ExportRenderer (typeof (BottomBarPage), typeof (BottomBarPageRenderer))] namespace BottomBar.Droid.Renderers { public class BottomBarPageRenderer : VisualElementRenderer<BottomBarPage>, IOnTabClickListener { bool _disposed; BottomNavigationBar.BottomBar _bottomBar; FrameLayout _frameLayout; IPageController _pageController; public BottomBarPageRenderer () { AutoPackage = false; } #region IOnTabClickListener public void OnTabSelected (int position) { //Do we need this call? It's also done in OnElementPropertyChanged SwitchContent(Element.Children [position]); var bottomBarPage = Element as BottomBarPage; bottomBarPage.CurrentPage = Element.Children[position]; //bottomBarPage.RaiseCurrentPageChanged(); } public void OnTabReSelected (int position) { } #endregion protected override void Dispose (bool disposing) { if (disposing && !_disposed) { _disposed = true; RemoveAllViews (); foreach (Page pageToRemove in Element.Children) { IVisualElementRenderer pageRenderer = Platform.GetRenderer (pageToRemove); if (pageRenderer != null) { pageRenderer.ViewGroup.RemoveFromParent (); pageRenderer.Dispose (); } // pageToRemove.ClearValue (Platform.RendererProperty); } if (_bottomBar != null) { _bottomBar.SetOnTabClickListener (null); _bottomBar.Dispose (); _bottomBar = null; } if (_frameLayout != null) { _frameLayout.Dispose (); _frameLayout = null; } /*if (Element != null) { PageController.InternalChildren.CollectionChanged -= OnChildrenCollectionChanged; }*/ } base.Dispose (disposing); } protected override void OnAttachedToWindow () { base.OnAttachedToWindow (); _pageController.SendAppearing (); } protected override void OnDetachedFromWindow () { base.OnDetachedFromWindow (); _pageController.SendDisappearing (); } protected override void OnElementChanged (ElementChangedEventArgs<BottomBarPage> e) { base.OnElementChanged (e); if (e.NewElement != null) { BottomBarPage bottomBarPage = e.NewElement; if (_bottomBar == null) { _pageController = PageController.Create (bottomBarPage); // create a view which will act as container for Page's _frameLayout = new FrameLayout (Forms.Context); _frameLayout.LayoutParameters = new FrameLayout.LayoutParams (LayoutParams.MatchParent, LayoutParams.MatchParent, GravityFlags.Fill); AddView (_frameLayout, 0); // create bottomBar control _bottomBar = BottomNavigationBar.BottomBar.Attach (_frameLayout, null); _bottomBar.NoTabletGoodness (); if (bottomBarPage.FixedMode) { _bottomBar.UseFixedMode(); } switch (bottomBarPage.BarTheme) { case BottomBarPage.BarThemeTypes.Light: break; case BottomBarPage.BarThemeTypes.DarkWithAlpha: _bottomBar.UseDarkThemeWithAlpha(true); break; case BottomBarPage.BarThemeTypes.DarkWithoutAlpha: _bottomBar.UseDarkThemeWithAlpha(false); break; default: throw new ArgumentOutOfRangeException(); } _bottomBar.LayoutParameters = new LayoutParams (LayoutParams.MatchParent, LayoutParams.MatchParent); _bottomBar.SetOnTabClickListener (this); UpdateTabs (); UpdateBarBackgroundColor (); UpdateBarTextColor (); } if (bottomBarPage.CurrentPage != null) { SwitchContent (bottomBarPage.CurrentPage); } } } protected override void OnElementPropertyChanged (object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged (sender, e); if (e.PropertyName == nameof (TabbedPage.CurrentPage)) { SwitchContent (Element.CurrentPage); } else if (e.PropertyName == NavigationPage.BarBackgroundColorProperty.PropertyName) { UpdateBarBackgroundColor (); } else if (e.PropertyName == NavigationPage.BarTextColorProperty.PropertyName) { UpdateBarTextColor (); } } protected virtual void SwitchContent (Page view) { Context.HideKeyboard (this); _frameLayout.RemoveAllViews (); if (view == null) { return; } if (Platform.GetRenderer (view) == null) { Platform.SetRenderer (view, Platform.CreateRenderer (view)); } _frameLayout.AddView (Platform.GetRenderer (view).ViewGroup); } protected override void OnLayout (bool changed, int l, int t, int r, int b) { int width = r - l; int height = b - t; var context = Context; _bottomBar.Measure (MeasureSpecFactory.MakeMeasureSpec (width, MeasureSpecMode.Exactly), MeasureSpecFactory.MakeMeasureSpec (height, MeasureSpecMode.AtMost)); int tabsHeight = Math.Min (height, Math.Max (_bottomBar.MeasuredHeight, _bottomBar.MinimumHeight)); if (width > 0 && height > 0) { _pageController.ContainerArea = new Rectangle(0, 0, context.FromPixels(width), context.FromPixels(_frameLayout.Height)); ObservableCollection<Element> internalChildren = _pageController.InternalChildren; for (var i = 0; i < internalChildren.Count; i++) { var child = internalChildren [i] as VisualElement; if (child == null) { continue; } IVisualElementRenderer renderer = Platform.GetRenderer (child); var navigationRenderer = renderer as NavigationPageRenderer; if (navigationRenderer != null) { // navigationRenderer.ContainerPadding = tabsHeight; } } _bottomBar.Measure (MeasureSpecFactory.MakeMeasureSpec (width, MeasureSpecMode.Exactly), MeasureSpecFactory.MakeMeasureSpec (tabsHeight, MeasureSpecMode.Exactly)); _bottomBar.Layout (0, 0, width, tabsHeight); } base.OnLayout (changed, l, t, r, b); } void UpdateBarBackgroundColor () { if (_disposed || _bottomBar == null) { return; } _bottomBar.SetBackgroundColor (Element.BarBackgroundColor.ToAndroid ()); } void UpdateBarTextColor () { if (_disposed || _bottomBar == null) { return; } _bottomBar.SetActiveTabColor(Element.BarTextColor.ToAndroid()); // The problem SetActiveTabColor does only work in fiexed mode // haven't found yet how to set text color for tab items on_bottomBar, doesn't seem to have a direct way } void UpdateTabs () { // create tab items SetTabItems (); // set tab colors SetTabColors (); } void SetTabItems () { BottomBarTab [] tabs = Element.Children.Select (page => { var tabIconId = ResourceManagerEx.IdFromTitle (page.Icon, ResourceManager.DrawableClass); return new BottomBarTab (tabIconId, page.Title); }).ToArray (); _bottomBar.SetItems (tabs); } void SetTabColors () { for (int i = 0; i < Element.Children.Count; ++i) { Page page = Element.Children [i]; Color? tabColor = page.GetTabColor (); if (tabColor != null) { _bottomBar.MapColorForTab (i, tabColor.Value.ToAndroid ()); } } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/logging/v2/logging_metrics.proto // Original file comments: // Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using Grpc.Core; namespace Google.Logging.V2 { /// <summary> /// Service for configuring logs-based metrics. /// </summary> public static class MetricsServiceV2 { static readonly string __ServiceName = "google.logging.v2.MetricsServiceV2"; static readonly Marshaller<global::Google.Logging.V2.ListLogMetricsRequest> __Marshaller_ListLogMetricsRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Logging.V2.ListLogMetricsRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Logging.V2.ListLogMetricsResponse> __Marshaller_ListLogMetricsResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Logging.V2.ListLogMetricsResponse.Parser.ParseFrom); static readonly Marshaller<global::Google.Logging.V2.GetLogMetricRequest> __Marshaller_GetLogMetricRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Logging.V2.GetLogMetricRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Logging.V2.LogMetric> __Marshaller_LogMetric = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Logging.V2.LogMetric.Parser.ParseFrom); static readonly Marshaller<global::Google.Logging.V2.CreateLogMetricRequest> __Marshaller_CreateLogMetricRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Logging.V2.CreateLogMetricRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Logging.V2.UpdateLogMetricRequest> __Marshaller_UpdateLogMetricRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Logging.V2.UpdateLogMetricRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Logging.V2.DeleteLogMetricRequest> __Marshaller_DeleteLogMetricRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Logging.V2.DeleteLogMetricRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly Method<global::Google.Logging.V2.ListLogMetricsRequest, global::Google.Logging.V2.ListLogMetricsResponse> __Method_ListLogMetrics = new Method<global::Google.Logging.V2.ListLogMetricsRequest, global::Google.Logging.V2.ListLogMetricsResponse>( MethodType.Unary, __ServiceName, "ListLogMetrics", __Marshaller_ListLogMetricsRequest, __Marshaller_ListLogMetricsResponse); static readonly Method<global::Google.Logging.V2.GetLogMetricRequest, global::Google.Logging.V2.LogMetric> __Method_GetLogMetric = new Method<global::Google.Logging.V2.GetLogMetricRequest, global::Google.Logging.V2.LogMetric>( MethodType.Unary, __ServiceName, "GetLogMetric", __Marshaller_GetLogMetricRequest, __Marshaller_LogMetric); static readonly Method<global::Google.Logging.V2.CreateLogMetricRequest, global::Google.Logging.V2.LogMetric> __Method_CreateLogMetric = new Method<global::Google.Logging.V2.CreateLogMetricRequest, global::Google.Logging.V2.LogMetric>( MethodType.Unary, __ServiceName, "CreateLogMetric", __Marshaller_CreateLogMetricRequest, __Marshaller_LogMetric); static readonly Method<global::Google.Logging.V2.UpdateLogMetricRequest, global::Google.Logging.V2.LogMetric> __Method_UpdateLogMetric = new Method<global::Google.Logging.V2.UpdateLogMetricRequest, global::Google.Logging.V2.LogMetric>( MethodType.Unary, __ServiceName, "UpdateLogMetric", __Marshaller_UpdateLogMetricRequest, __Marshaller_LogMetric); static readonly Method<global::Google.Logging.V2.DeleteLogMetricRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteLogMetric = new Method<global::Google.Logging.V2.DeleteLogMetricRequest, global::Google.Protobuf.WellKnownTypes.Empty>( MethodType.Unary, __ServiceName, "DeleteLogMetric", __Marshaller_DeleteLogMetricRequest, __Marshaller_Empty); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Logging.V2.LoggingMetricsReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of MetricsServiceV2</summary> public abstract class MetricsServiceV2Base { /// <summary> /// Lists logs-based metrics. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Logging.V2.ListLogMetricsResponse> ListLogMetrics(global::Google.Logging.V2.ListLogMetricsRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Gets a logs-based metric. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Logging.V2.LogMetric> GetLogMetric(global::Google.Logging.V2.GetLogMetricRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Creates a logs-based metric. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Logging.V2.LogMetric> CreateLogMetric(global::Google.Logging.V2.CreateLogMetricRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Creates or updates a logs-based metric. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Logging.V2.LogMetric> UpdateLogMetric(global::Google.Logging.V2.UpdateLogMetricRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Deletes a logs-based metric. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteLogMetric(global::Google.Logging.V2.DeleteLogMetricRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } } /// <summary>Client for MetricsServiceV2</summary> public class MetricsServiceV2Client : ClientBase<MetricsServiceV2Client> { /// <summary>Creates a new client for MetricsServiceV2</summary> /// <param name="channel">The channel to use to make remote calls.</param> public MetricsServiceV2Client(Channel channel) : base(channel) { } /// <summary>Creates a new client for MetricsServiceV2 that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public MetricsServiceV2Client(CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected MetricsServiceV2Client() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected MetricsServiceV2Client(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Lists logs-based metrics. /// </summary> public virtual global::Google.Logging.V2.ListLogMetricsResponse ListLogMetrics(global::Google.Logging.V2.ListLogMetricsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListLogMetrics(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists logs-based metrics. /// </summary> public virtual global::Google.Logging.V2.ListLogMetricsResponse ListLogMetrics(global::Google.Logging.V2.ListLogMetricsRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListLogMetrics, null, options, request); } /// <summary> /// Lists logs-based metrics. /// </summary> public virtual AsyncUnaryCall<global::Google.Logging.V2.ListLogMetricsResponse> ListLogMetricsAsync(global::Google.Logging.V2.ListLogMetricsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListLogMetricsAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists logs-based metrics. /// </summary> public virtual AsyncUnaryCall<global::Google.Logging.V2.ListLogMetricsResponse> ListLogMetricsAsync(global::Google.Logging.V2.ListLogMetricsRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListLogMetrics, null, options, request); } /// <summary> /// Gets a logs-based metric. /// </summary> public virtual global::Google.Logging.V2.LogMetric GetLogMetric(global::Google.Logging.V2.GetLogMetricRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetLogMetric(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a logs-based metric. /// </summary> public virtual global::Google.Logging.V2.LogMetric GetLogMetric(global::Google.Logging.V2.GetLogMetricRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetLogMetric, null, options, request); } /// <summary> /// Gets a logs-based metric. /// </summary> public virtual AsyncUnaryCall<global::Google.Logging.V2.LogMetric> GetLogMetricAsync(global::Google.Logging.V2.GetLogMetricRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetLogMetricAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a logs-based metric. /// </summary> public virtual AsyncUnaryCall<global::Google.Logging.V2.LogMetric> GetLogMetricAsync(global::Google.Logging.V2.GetLogMetricRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetLogMetric, null, options, request); } /// <summary> /// Creates a logs-based metric. /// </summary> public virtual global::Google.Logging.V2.LogMetric CreateLogMetric(global::Google.Logging.V2.CreateLogMetricRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateLogMetric(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a logs-based metric. /// </summary> public virtual global::Google.Logging.V2.LogMetric CreateLogMetric(global::Google.Logging.V2.CreateLogMetricRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateLogMetric, null, options, request); } /// <summary> /// Creates a logs-based metric. /// </summary> public virtual AsyncUnaryCall<global::Google.Logging.V2.LogMetric> CreateLogMetricAsync(global::Google.Logging.V2.CreateLogMetricRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateLogMetricAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a logs-based metric. /// </summary> public virtual AsyncUnaryCall<global::Google.Logging.V2.LogMetric> CreateLogMetricAsync(global::Google.Logging.V2.CreateLogMetricRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateLogMetric, null, options, request); } /// <summary> /// Creates or updates a logs-based metric. /// </summary> public virtual global::Google.Logging.V2.LogMetric UpdateLogMetric(global::Google.Logging.V2.UpdateLogMetricRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateLogMetric(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates or updates a logs-based metric. /// </summary> public virtual global::Google.Logging.V2.LogMetric UpdateLogMetric(global::Google.Logging.V2.UpdateLogMetricRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateLogMetric, null, options, request); } /// <summary> /// Creates or updates a logs-based metric. /// </summary> public virtual AsyncUnaryCall<global::Google.Logging.V2.LogMetric> UpdateLogMetricAsync(global::Google.Logging.V2.UpdateLogMetricRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateLogMetricAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates or updates a logs-based metric. /// </summary> public virtual AsyncUnaryCall<global::Google.Logging.V2.LogMetric> UpdateLogMetricAsync(global::Google.Logging.V2.UpdateLogMetricRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateLogMetric, null, options, request); } /// <summary> /// Deletes a logs-based metric. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteLogMetric(global::Google.Logging.V2.DeleteLogMetricRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteLogMetric(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a logs-based metric. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteLogMetric(global::Google.Logging.V2.DeleteLogMetricRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteLogMetric, null, options, request); } /// <summary> /// Deletes a logs-based metric. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteLogMetricAsync(global::Google.Logging.V2.DeleteLogMetricRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteLogMetricAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a logs-based metric. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteLogMetricAsync(global::Google.Logging.V2.DeleteLogMetricRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteLogMetric, null, options, request); } protected override MetricsServiceV2Client NewInstance(ClientBaseConfiguration configuration) { return new MetricsServiceV2Client(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> public static ServerServiceDefinition BindService(MetricsServiceV2Base serviceImpl) { return ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_ListLogMetrics, serviceImpl.ListLogMetrics) .AddMethod(__Method_GetLogMetric, serviceImpl.GetLogMetric) .AddMethod(__Method_CreateLogMetric, serviceImpl.CreateLogMetric) .AddMethod(__Method_UpdateLogMetric, serviceImpl.UpdateLogMetric) .AddMethod(__Method_DeleteLogMetric, serviceImpl.DeleteLogMetric).Build(); } } } #endregion
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.ComponentModel; using System.Linq; using XenAdmin.Utils; using XenAPI; namespace XenAdmin.Dialogs { public interface ILicenseStatus : IDisposable { LicenseStatus.HostState CurrentState { get; } Host.Edition LicenseEdition { get; } TimeSpan LicenseExpiresIn { get; } TimeSpan LicenseExpiresExactlyIn { get; } DateTime? ExpiryDate { get; } event LicenseStatus.StatusUpdatedEvent ItemUpdated; bool Updated { get; } void BeginUpdate(); Host LicencedHost { get; } string LicenseEntitlements { get; } } public class LicenseStatus : ILicenseStatus { public enum HostState { Unknown, Expired, ExpiresSoon, RegularGrace, UpgradeGrace, Licensed, PartiallyLicensed, Free, Unavailable } private readonly EventHandlerList events = new EventHandlerList(); protected EventHandlerList Events { get { return events; } } private const string StatusUpdatedEventKey = "LicenseStatusStatusUpdatedEventKey"; public Host LicencedHost { get; private set; } private readonly AsyncServerTime serverTime = new AsyncServerTime(); public delegate void StatusUpdatedEvent(object sender, EventArgs e); public static bool IsInfinite(TimeSpan span) { return span.TotalDays >= 3653; } public static bool IsGraceLicence(TimeSpan span) { return span.TotalDays < 30; } private IXenObject XenObject { get; set; } public bool Updated { get; set; } public LicenseStatus(IXenObject xo) { SetDefaultOptions(); XenObject = xo; if (XenObject is Host host) LicencedHost = host; if (XenObject is Pool pool) SetMinimumLicenseValueHost(pool); serverTime.ServerTimeObtained -= ServerTimeUpdatedEventHandler; serverTime.ServerTimeObtained += ServerTimeUpdatedEventHandler; if (XenObject != null) { XenObject.Connection.ConnectionStateChanged -= Connection_ConnectionStateChanged; XenObject.Connection.ConnectionStateChanged += Connection_ConnectionStateChanged; } } void Connection_ConnectionStateChanged(object sender, EventArgs e) { if (LicencedHost != null) { TriggerStatusUpdatedEvent(); } } private void SetMinimumLicenseValueHost(Pool pool) { LicencedHost = pool.Connection.Resolve(pool.master); if(LicencedHost == null) return; foreach (Host host in pool.Connection.Cache.Hosts) { if(host.LicenseExpiryUTC() < LicencedHost.LicenseExpiryUTC()) LicencedHost = host; } } private void SetDefaultOptions() { CurrentState = HostState.Unknown; Updated = false; LicenseExpiresExactlyIn = new TimeSpan(); } public void BeginUpdate() { SetDefaultOptions(); serverTime.Fetch(LicencedHost); } private void ServerTimeUpdatedEventHandler() { if (LicencedHost != null) { CalculateLicenseState(); TriggerStatusUpdatedEvent(); } } protected void CalculateLicenseState() { LicenseExpiresExactlyIn = CalculateLicenceExpiresIn(); CurrentState = CalculateCurrentState(); Updated = true; } private void TriggerStatusUpdatedEvent() { StatusUpdatedEvent handler = Events[StatusUpdatedEventKey] as StatusUpdatedEvent; if (handler != null) handler.Invoke(this, EventArgs.Empty); } private bool InRegularGrace { get { return LicencedHost.license_params != null && LicencedHost.license_params.ContainsKey("grace") && LicenseExpiresIn.Ticks > 0 && LicencedHost.license_params["grace"] == "regular grace"; } } private bool InUpgradeGrace { get { return LicencedHost.license_params != null && LicencedHost.license_params.ContainsKey("grace") && LicenseExpiresIn.Ticks > 0 && LicencedHost.license_params["grace"] == "upgrade grace"; } } protected virtual TimeSpan CalculateLicenceExpiresIn() { //ServerTime is UTC DateTime currentRefTime = serverTime.ServerTime; return LicencedHost.LicenseExpiryUTC().Subtract(currentRefTime); } internal static bool PoolIsMixedFreeAndExpiring(IXenObject xenObject) { if (xenObject is Pool) { if (xenObject.Connection.Cache.Hosts.Length == 1) return false; int freeCount = xenObject.Connection.Cache.Hosts.Count(h => Host.GetEdition(h.edition) == Host.Edition.Free); if (freeCount == 0 || freeCount < xenObject.Connection.Cache.Hosts.Length) return false; var expiryGroups = from Host h in xenObject.Connection.Cache.Hosts let exp = h.LicenseExpiryUTC() group h by exp into g select new { ExpiryDate = g.Key, Hosts = g }; if(expiryGroups.Count() > 1) { expiryGroups.OrderBy(g => g.ExpiryDate); if ((expiryGroups.ElementAt(1).ExpiryDate - expiryGroups.ElementAt(0).ExpiryDate).TotalDays > 30) return true; } } return false; } internal static bool PoolIsPartiallyLicensed(IXenObject xenObject) { if (xenObject is Pool) { if (xenObject.Connection.Cache.Hosts.Length == 1) return false; int freeCount = xenObject.Connection.Cache.Hosts.Count(h => Host.GetEdition(h.edition) == Host.Edition.Free); return freeCount > 0 && freeCount < xenObject.Connection.Cache.Hosts.Length; } return false; } internal static bool PoolHasMixedLicenses(IXenObject xenObject) { var pool = xenObject as Pool; if (pool != null) { if (xenObject.Connection.Cache.Hosts.Length == 1) return false; if (xenObject.Connection.Cache.Hosts.Any(h => Host.GetEdition(h.edition) == Host.Edition.Free)) return false; var licenseGroups = from Host h in xenObject.Connection.Cache.Hosts let ed = Host.GetEdition(h.edition) group h by ed; return licenseGroups.Count() > 1; } return false; } private HostState CalculateCurrentState() { if (ExpiryDate.HasValue && ExpiryDate.Value.Day == 1 && ExpiryDate.Value.Month == 1 && ExpiryDate.Value.Year == 1970) { return HostState.Unavailable; } if (PoolIsPartiallyLicensed(XenObject)) return HostState.PartiallyLicensed; if (LicenseEdition == Host.Edition.Free) return HostState.Free; if (!IsGraceLicence(LicenseExpiresIn)) return HostState.Licensed; if (IsInfinite(LicenseExpiresIn)) { return HostState.Licensed; } if (LicenseExpiresIn.Ticks <= 0) { return HostState.Expired; } if (IsGraceLicence(LicenseExpiresIn)) { if (InRegularGrace) return HostState.RegularGrace; if (InUpgradeGrace) return HostState.UpgradeGrace; return HostState.ExpiresSoon; } return LicenseEdition == Host.Edition.Free ? HostState.Free : HostState.Licensed; } #region ILicenseStatus Members public event StatusUpdatedEvent ItemUpdated { add { Events.AddHandler(StatusUpdatedEventKey, value); } remove { Events.RemoveHandler(StatusUpdatedEventKey, value); } } public Host.Edition LicenseEdition { get { return Host.GetEdition(LicencedHost.edition); } } public HostState CurrentState { get; private set; } public TimeSpan LicenseExpiresExactlyIn { get; private set; } /// <summary> /// License expiry, just days, hrs, mins /// </summary> public TimeSpan LicenseExpiresIn { get { return new TimeSpan(LicenseExpiresExactlyIn.Days, LicenseExpiresExactlyIn.Hours, LicenseExpiresExactlyIn.Minutes, 0, 0); } } public DateTime? ExpiryDate { get { if (LicencedHost.license_params != null && LicencedHost.license_params.ContainsKey("expiry")) return LicencedHost.LicenseExpiryUTC().ToLocalTime(); return null; } } public string LicenseEntitlements { get { if (CurrentState == HostState.Licensed) { if (XenObject.Connection.Cache.Hosts.All(h => h.EnterpriseFeaturesEnabled())) return Messages.LICENSE_SUPPORT_AND_ENTERPRISE_FEATURES_ENABLED; if (XenObject.Connection.Cache.Hosts.All(h => h.DesktopPlusFeaturesEnabled())) return Messages.LICENSE_SUPPORT_AND_DESKTOP_PLUS_FEATURES_ENABLED; if (XenObject.Connection.Cache.Hosts.All(h => h.DesktopFeaturesEnabled())) return Messages.LICENSE_SUPPORT_AND_DESKTOP_FEATURES_ENABLED; if (XenObject.Connection.Cache.Hosts.All(h => h.DesktopCloudFeaturesEnabled())) return Messages.LICENSE_SUPPORT_AND_DESKTOP_CLOUD_FEATURES_ENABLED; if (XenObject.Connection.Cache.Hosts.All(h => h.PremiumFeaturesEnabled())) return Messages.LICENSE_SUPPORT_AND_PREMIUM_FEATURES_ENABLED; if (XenObject.Connection.Cache.Hosts.All(h => h.StandardFeaturesEnabled())) return Messages.LICENSE_SUPPORT_AND_STANDARD_FEATURES_ENABLED; if (XenObject.Connection.Cache.Hosts.All(h => h.EligibleForSupport())) return Messages.LICENSE_SUPPORT_AND_STANDARD_FEATURES_ENABLED; return Messages.LICENSE_NOT_ELIGIBLE_FOR_SUPPORT; } if (CurrentState == HostState.Free) { return Messages.LICENSE_NOT_ELIGIBLE_FOR_SUPPORT; } return Messages.UNKNOWN; } } #endregion #region IDisposable Members public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private bool disposed; public void Dispose(bool disposing) { if(!disposed) { if(disposing) { if (serverTime != null) serverTime.ServerTimeObtained -= ServerTimeUpdatedEventHandler; if (XenObject != null && XenObject.Connection != null) XenObject.Connection.ConnectionStateChanged -= Connection_ConnectionStateChanged; Events.Dispose(); } disposed = true; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\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; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void AsUInt16() { var test = new VectorAs__AsUInt16(); // Validates basic functionality works test.RunBasicScenario(); // Validates basic functionality works using the generic form, rather than the type-specific form of the method test.RunGenericScenario(); // Validates calling via reflection works test.RunReflectionScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorAs__AsUInt16 { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Vector256<UInt16> value; value = Vector256.Create(TestLibrary.Generator.GetUInt16()); Vector256<byte> byteResult = value.AsByte(); ValidateResult(byteResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); Vector256<double> doubleResult = value.AsDouble(); ValidateResult(doubleResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); Vector256<short> shortResult = value.AsInt16(); ValidateResult(shortResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); Vector256<int> intResult = value.AsInt32(); ValidateResult(intResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); Vector256<long> longResult = value.AsInt64(); ValidateResult(longResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); Vector256<sbyte> sbyteResult = value.AsSByte(); ValidateResult(sbyteResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); Vector256<float> floatResult = value.AsSingle(); ValidateResult(floatResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); Vector256<ushort> ushortResult = value.AsUInt16(); ValidateResult(ushortResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); Vector256<uint> uintResult = value.AsUInt32(); ValidateResult(uintResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); Vector256<ulong> ulongResult = value.AsUInt64(); ValidateResult(ulongResult, value); } public void RunGenericScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunGenericScenario)); Vector256<UInt16> value; value = Vector256.Create(TestLibrary.Generator.GetUInt16()); Vector256<byte> byteResult = value.As<UInt16, byte>(); ValidateResult(byteResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); Vector256<double> doubleResult = value.As<UInt16, double>(); ValidateResult(doubleResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); Vector256<short> shortResult = value.As<UInt16, short>(); ValidateResult(shortResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); Vector256<int> intResult = value.As<UInt16, int>(); ValidateResult(intResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); Vector256<long> longResult = value.As<UInt16, long>(); ValidateResult(longResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); Vector256<sbyte> sbyteResult = value.As<UInt16, sbyte>(); ValidateResult(sbyteResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); Vector256<float> floatResult = value.As<UInt16, float>(); ValidateResult(floatResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); Vector256<ushort> ushortResult = value.As<UInt16, ushort>(); ValidateResult(ushortResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); Vector256<uint> uintResult = value.As<UInt16, uint>(); ValidateResult(uintResult, value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); Vector256<ulong> ulongResult = value.As<UInt16, ulong>(); ValidateResult(ulongResult, value); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Vector256<UInt16> value; value = Vector256.Create(TestLibrary.Generator.GetUInt16()); object byteResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsByte)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<byte>)(byteResult), value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); object doubleResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsDouble)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<double>)(doubleResult), value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); object shortResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsInt16)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<short>)(shortResult), value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); object intResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsInt32)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<int>)(intResult), value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); object longResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsInt64)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<long>)(longResult), value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); object sbyteResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsSByte)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<sbyte>)(sbyteResult), value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); object floatResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsSingle)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<float>)(floatResult), value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); object ushortResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsUInt16)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<ushort>)(ushortResult), value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); object uintResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsUInt32)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<uint>)(uintResult), value); value = Vector256.Create(TestLibrary.Generator.GetUInt16()); object ulongResult = typeof(Vector256) .GetMethod(nameof(Vector256.AsUInt64)) .MakeGenericMethod(typeof(UInt16)) .Invoke(null, new object[] { value }); ValidateResult((Vector256<ulong>)(ulongResult), value); } private void ValidateResult<T>(Vector256<T> result, Vector256<UInt16> value, [CallerMemberName] string method = "") where T : struct { UInt16[] resultElements = new UInt16[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref resultElements[0]), result); UInt16[] valueElements = new UInt16[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref valueElements[0]), value); ValidateResult(resultElements, valueElements, typeof(T), method); } private void ValidateResult(UInt16[] resultElements, UInt16[] valueElements, Type targetType, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < ElementCount; i++) { if (resultElements[i] != valueElements[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt16>.As{targetType.Name}: {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", valueElements)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Windows; using System.Windows.Automation.Provider; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Interop; using System.Windows.Media; using MS.Internal; using MS.Win32; namespace System.Windows.Automation.Peers { /// public abstract class SelectorAutomationPeer : ItemsControlAutomationPeer, ISelectionProvider { /// protected SelectorAutomationPeer(Selector owner): base(owner) {} /// override protected AutomationControlType GetAutomationControlTypeCore() { return AutomationControlType.List; } /// override public object GetPattern(PatternInterface patternInterface) { if(patternInterface == PatternInterface.Selection) { return this; } return base.GetPattern(patternInterface); // ItemsControlAutomationPeer support Scroll pattern } /// internal override bool IsPropertySupportedByControlForFindItem(int id) { return SelectorAutomationPeer.IsPropertySupportedByControlForFindItemInternal(id); } internal static new bool IsPropertySupportedByControlForFindItemInternal(int id) { if (ItemsControlAutomationPeer.IsPropertySupportedByControlForFindItemInternal(id)) return true; else { if (SelectionItemPatternIdentifiers.IsSelectedProperty.Id == id) return true; else return false; } } /// <summary> /// Support for IsSelectedProperty should come from SelectorAutomationPeer only, /// </summary> internal override object GetSupportedPropertyValue(ItemAutomationPeer itemPeer, int propertyId) { return SelectorAutomationPeer.GetSupportedPropertyValueInternal(itemPeer, propertyId); } internal static new object GetSupportedPropertyValueInternal(AutomationPeer itemPeer, int propertyId) { if (SelectionItemPatternIdentifiers.IsSelectedProperty.Id == propertyId) { ISelectionItemProvider selectionItem = itemPeer.GetPattern(PatternInterface.SelectionItem) as ISelectionItemProvider; if (selectionItem != null) return selectionItem.IsSelected; else return null; } return ItemsControlAutomationPeer.GetSupportedPropertyValueInternal(itemPeer, propertyId); } //------------------------------------------------------------------- // // ISelectionProvider // //------------------------------------------------------------------- #region ISelectionProvider IRawElementProviderSimple [] ISelectionProvider.GetSelection() { Selector owner = (Selector)Owner; int count = owner._selectedItems.Count; int itemsCount = (owner as ItemsControl).Items.Count; if(count > 0 && itemsCount > 0) { List<IRawElementProviderSimple> selectedProviders = new List<IRawElementProviderSimple>(count); for(int i=0; i<count; i++) { SelectorItemAutomationPeer peer = FindOrCreateItemAutomationPeer(owner._selectedItems[i].Item) as SelectorItemAutomationPeer; if(peer != null) { selectedProviders.Add(ProviderFromPeer(peer)); } } return selectedProviders.ToArray(); } return null; } bool ISelectionProvider.CanSelectMultiple { get { Selector owner = (Selector)Owner; return owner.CanSelectMultiple; } } bool ISelectionProvider.IsSelectionRequired { get { return false; } } // Note: see bug 1555137 for details. // Never inline, as we don't want to unnecessarily link the // automation DLL via the ISelectionProvider interface type initialization. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] internal void RaiseSelectionEvents(SelectionChangedEventArgs e) { if (ItemPeers.Count == 0) { // ItemPeers.Count == 0 if children were never fetched. // in the case, when client probably is not interested in the details // of selection changes. but we still want to notify client about it. this.RaiseAutomationEvent(AutomationEvents.SelectionPatternOnInvalidated); return; } Selector owner = (Selector)Owner; // These counters are bound to selection only numAdded = number of items just added and included in the current selection, // numRemoved = number of items just removed from the selection, numSelected = total number of items currently selected after addition and removal. int numSelected = owner._selectedItems.Count; int numAdded = e.AddedItems.Count; int numRemoved = e.RemovedItems.Count; if (numSelected == 1 && numAdded == 1) { SelectorItemAutomationPeer peer = FindOrCreateItemAutomationPeer(owner._selectedItems[0].Item) as SelectorItemAutomationPeer; if(peer != null) { peer.RaiseAutomationEvent(AutomationEvents.SelectionItemPatternOnElementSelected); } } else { // If more than InvalidateLimit element change their state then we invalidate the selection container // Otherwise we fire Add/Remove from selection events if (numAdded + numRemoved > AutomationInteropProvider.InvalidateLimit) { this.RaiseAutomationEvent(AutomationEvents.SelectionPatternOnInvalidated); } else { int i; for (i = 0; i < numAdded; i++) { SelectorItemAutomationPeer peer = FindOrCreateItemAutomationPeer(e.AddedItems[i]) as SelectorItemAutomationPeer; if (peer != null) { peer.RaiseAutomationEvent(AutomationEvents.SelectionItemPatternOnElementAddedToSelection); } } for (i = 0; i < numRemoved; i++) { SelectorItemAutomationPeer peer = FindOrCreateItemAutomationPeer(e.RemovedItems[i]) as SelectorItemAutomationPeer; if (peer != null) { peer.RaiseAutomationEvent(AutomationEvents.SelectionItemPatternOnElementRemovedFromSelection); } } } } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Collections; using System.Collections.Specialized; using GenStrings; namespace System.Collections.Specialized.Tests { public class GetIntTests { public const int MAX_LEN = 50; // max length of random strings [Fact] public void Test01() { IntlStrings intl; NameValueCollection nvc; // simple string values string[] values = { "", " ", "a", "aA", "text", " SPaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // keys for simple string values string[] keys = { "zero", "oNe", " ", "", "aa", "1", System.DateTime.Today.ToString(), "$%^#", Int32.MaxValue.ToString(), " spaces", "2222222222222222222222222" }; int cnt = 0; // Count // initialize IntStrings intl = new IntlStrings(); // [] NameValueCollection is constructed as expected //----------------------------------------------------------------- nvc = new NameValueCollection(); // [] Get(int) on empty collection // Assert.Throws<ArgumentOutOfRangeException>(() => { nvc.Get(-1); }); Assert.Throws<ArgumentOutOfRangeException>(() => { nvc.Get(0); }); // [] Get(int) on collection filled with simple strings // cnt = nvc.Count; int len = values.Length; for (int i = 0; i < len; i++) { nvc.Add(keys[i], values[i]); } if (nvc.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, values.Length)); } // for (int i = 0; i < len; i++) { if (String.Compare(nvc.Get(i), values[i]) != 0) { Assert.False(true, string.Format("Error, returned: \"{1}\", expected \"{2}\"", i, nvc.Get(i), values[i])); } } // // Intl strings // [] Get(int) on collection filled with Intl strings // string[] intlValues = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { string val = intl.GetRandomString(MAX_LEN); while (Array.IndexOf(intlValues, val) != -1) val = intl.GetRandomString(MAX_LEN); intlValues[i] = val; } Boolean caseInsensitive = false; for (int i = 0; i < len * 2; i++) { if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant()) caseInsensitive = true; } nvc.Clear(); for (int i = 0; i < len; i++) { nvc.Add(intlValues[i + len], intlValues[i]); } if (nvc.Count != (len)) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, len)); } for (int i = 0; i < len; i++) { // if (String.Compare(nvc.Get(i), intlValues[i]) != 0) { Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, nvc.Get(i), intlValues[i])); } } // // [] Case sensitivity // string[] intlValuesLower = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { intlValues[i] = intlValues[i].ToUpperInvariant(); } for (int i = 0; i < len * 2; i++) { intlValuesLower[i] = intlValues[i].ToLowerInvariant(); } nvc.Clear(); // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { nvc.Add(intlValues[i + len], intlValues[i]); // adding uppercase strings } // for (int i = 0; i < len; i++) { // if (String.Compare(nvc.Get(i), intlValues[i]) != 0) { Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, nvc.Get(i), intlValues[i])); } if (!caseInsensitive && String.Compare(nvc.Get(i), intlValuesLower[i]) == 0) { Assert.False(true, string.Format("Error, returned lowercase when added uppercase", i)); } } // [] Get(int) on filled collection with multiple items with the same key // nvc.Clear(); len = values.Length; string k = "keykey"; string k1 = "hm1"; string exp = ""; string exp1 = ""; for (int i = 0; i < len; i++) { nvc.Add(k, "Value" + i); nvc.Add(k1, "iTem" + i); if (i < len - 1) { exp += "Value" + i + ","; exp1 += "iTem" + i + ","; } else { exp += "Value" + i; exp1 += "iTem" + i; } } if (nvc.Count != 2) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, 2)); } if (String.Compare(nvc.Get(0), exp) != 0) { Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc.Get(0), exp)); } if (String.Compare(nvc.Get(1), exp1) != 0) { Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc.Get(1), exp1)); } // // [] Get(-1) // cnt = nvc.Count; Assert.Throws<ArgumentOutOfRangeException>(() => { nvc.Get(-1); }); // // [] Get(count) // if (nvc.Count < 1) { for (int i = 0; i < len; i++) { nvc.Add(keys[i], values[i]); } } cnt = nvc.Count; Assert.Throws<ArgumentOutOfRangeException>(() => { nvc.Get(cnt); }); // // [] Get(count+1) // if (nvc.Count < 1) { for (int i = 0; i < len; i++) { nvc.Add(keys[i], values[i]); } } cnt = nvc.Count; Assert.Throws<ArgumentOutOfRangeException>(() => { nvc.Get(cnt + 1); }); // // Get(null) - calls other overloaded version of Get - Get(string) - no exception // [] Get(null) // string res = nvc.Get(null); if (res != null) { Assert.False(true, "Error, returned non-null "); } } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using MGTK.EventArguments; using MGTK.Services; namespace MGTK.Controls { public class ListBox : Control { protected Scrollbar horizontalScrollbar; protected Scrollbar verticalScrollbar; public InnerListBox innerListBox; private bool useVerticalScrollBar = true, useHorizontalScrollBar = false; private int MsToNextIndex = 150; private double LastUpdateIndexChange; public bool UseVerticalScrollBar { get { return useVerticalScrollBar; } set { useVerticalScrollBar = value; ConfigureCoordinatesAndSizes(); } } public bool UseHorizontalScrollBar { get { return useHorizontalScrollBar; } set { useHorizontalScrollBar = value; ConfigureCoordinatesAndSizes(); } } public object SelectedValue { get { return innerListBox.SelectedValue; } set { innerListBox.SelectedValue = value; } } public int SelectedIndex { get { return innerListBox.SelectedIndex; } set { if (innerListBox.SelectedIndex != value) { innerListBox.SelectedIndex = value; if (SelectedIndexChanged != null) SelectedIndexChanged(this, new EventArgs()); } } } public List<ListBoxItem> Items { get { return innerListBox.Items; } set { innerListBox.Items = value; ConfigureCoordinatesAndSizes(); } } public event EventHandler SelectedIndexChanged; public event EventHandler ListItemClick; public ListBox(Form formowner) : base(formowner) { horizontalScrollbar = new Scrollbar(formowner) { Type = ScrollBarType.Horizontal }; verticalScrollbar = new Scrollbar(formowner) { Type = ScrollBarType.Vertical }; innerListBox = new InnerListBox(formowner); innerListBox.Click += new EventHandler(innerListBox_Click); horizontalScrollbar.Parent = verticalScrollbar.Parent = innerListBox.Parent = this; horizontalScrollbar.IndexChanged += new EventHandler(horizontalScrollbar_IndexChanged); verticalScrollbar.IndexChanged += new EventHandler(verticalScrollbar_IndexChanged); innerListBox.SelectedIndexChanged += new EventHandler(innerListBox_SelectedIndexChanged); this.Controls.Add(innerListBox); this.Controls.Add(horizontalScrollbar); this.Controls.Add(verticalScrollbar); this.Init += new EventHandler(ListBox_Init); this.WidthChanged += new EventHandler(ListBox_SizeChanged); this.HeightChanged += new EventHandler(ListBox_SizeChanged); this.KeyDown += new ControlKeyEventHandler(ListBox_KeyDown); innerListBox.KeyDown += new ControlKeyEventHandler(ListBox_KeyDown); } void innerListBox_Click(object sender, EventArgs e) { if (ListItemClick != null) ListItemClick(this, new EventArgs()); } void innerListBox_SelectedIndexChanged(object sender, EventArgs e) { if (SelectedIndexChanged != null) SelectedIndexChanged(this, new EventArgs()); } void ListBox_KeyDown(object sender, ControlKeyEventArgs e) { if (gameTime.TotalGameTime.TotalMilliseconds - LastUpdateIndexChange > MsToNextIndex) { if (e.Key == Keys.Down) SelectedIndex++; if (e.Key == Keys.PageDown) SelectedIndex += innerListBox.NrItemsVisible; if (e.Key == Keys.Up) SelectedIndex--; if (e.Key == Keys.PageUp) SelectedIndex -= innerListBox.NrItemsVisible; if (e.Key == Keys.Left) horizontalScrollbar.Index--; if (e.Key == Keys.Right) horizontalScrollbar.Index++; if (SelectedIndex < verticalScrollbar.Index) verticalScrollbar.Index= SelectedIndex; if (SelectedIndex >= verticalScrollbar.Index + verticalScrollbar.NrItemsPerPage) verticalScrollbar.Index= SelectedIndex - innerListBox.NrItemsVisible + 1; LastUpdateIndexChange = gameTime.TotalGameTime.TotalMilliseconds; } } void verticalScrollbar_IndexChanged(object sender, EventArgs e) { innerListBox.ScrollY = verticalScrollbar.Index; } void horizontalScrollbar_IndexChanged(object sender, EventArgs e) { innerListBox.ScrollX = horizontalScrollbar.Index; } void ListBox_SizeChanged(object sender, EventArgs e) { ConfigureCoordinatesAndSizes(); } void ListBox_Init(object sender, EventArgs e) { ConfigureCoordinatesAndSizes(); } public override void Draw() { DrawingService.DrawFrame(SpriteBatchProvider, Theme.ListFrame, OwnerX + X, OwnerY + Y, Width, Height, Z - 0.001f); base.Draw(); } public override void Update() { horizontalScrollbar.Z = verticalScrollbar.Z = Z - 0.0015f; innerListBox.Z = Z - 0.001f; base.Update(); } public void ConfigureCoordinatesAndSizes() { innerListBox.X = 2; innerListBox.Y = 2; verticalScrollbar.X = Width - 16 - 2; verticalScrollbar.Y = 2; verticalScrollbar.Width = 16; verticalScrollbar.Height = Height - 4; horizontalScrollbar.X = 2; horizontalScrollbar.Y = Height - 16 - 2; horizontalScrollbar.Width = Width - 4; horizontalScrollbar.Height = 16; if (UseVerticalScrollBar) innerListBox.Width = Width - verticalScrollbar.Width - 4 - 1; else innerListBox.Width = Width - 4; if (UseHorizontalScrollBar) innerListBox.Height = Height - horizontalScrollbar.Height - 4 - 1; else innerListBox.Height = Height - 4; if (UseVerticalScrollBar && UseHorizontalScrollBar) { horizontalScrollbar.Width -= 16; verticalScrollbar.Height -= 16; } horizontalScrollbar.Visible = UseHorizontalScrollBar; verticalScrollbar.Visible = UseVerticalScrollBar; verticalScrollbar.NrItemsPerPage = innerListBox.NrItemsVisible; verticalScrollbar.TotalNrItems = innerListBox.Items.Count; if (Items != null && Items.Count > 0) { horizontalScrollbar.TotalNrItems = 0; horizontalScrollbar.NrItemsPerPage = 0; for (int i = 0; i < Items.Count; i++) { if (innerListBox.Items[i].Text.Length > horizontalScrollbar.TotalNrItems) horizontalScrollbar.TotalNrItems = innerListBox.Items[i].Text.Length; if (innerListBox.Items[i].NrCharsVisible > horizontalScrollbar.NrItemsPerPage) horizontalScrollbar.NrItemsPerPage = innerListBox.Items[i].NrCharsVisible; } } innerListBox.UpdateNrCharsVisible(); } public void AddItem(ListBoxItem item) { innerListBox.AddItem(item); ConfigureCoordinatesAndSizes(); } public void RemoveItem(ListBoxItem item) { innerListBox.RemoveItem(item); ConfigureCoordinatesAndSizes(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace SirindarApi.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime; using System.Diagnostics; using System.Collections.Generic; using System.Collections.Concurrent; using Internal.Runtime.Augments; namespace Internal.Reflection.Core.NonPortable { internal static partial class RuntimeTypeUnifier { // // TypeTable mapping raw RuntimeTypeHandles (normalized or otherwise) to RuntimeTypes. // // Note the relationship between RuntimeTypeHandleToRuntimeTypeCache and TypeTableForTypesWithEETypes and TypeTableForEENamedGenericTypes. // The latter two exist to enforce the creation of one Type instance per semantic identity. RuntimeTypeHandleToRuntimeTypeCache, on the other // hand, exists for fast lookup. It hashes and compares on the raw IntPtr value of the RuntimeTypeHandle. Because Redhawk // can and does create multiple EETypes for the same semantically identical type, the same RuntimeType can legitimately appear twice // in this table. The factory, however, does a second lookup in the true unifying tables rather than creating the RuntimeType itself. // Thus, the one-to-one relationship between Type reference identity and Type semantic identity is preserved. // private sealed class RuntimeTypeHandleToRuntimeTypeCache : ConcurrentUnifierW<RawRuntimeTypeHandleKey, RuntimeType> { private RuntimeTypeHandleToRuntimeTypeCache() { } protected sealed override RuntimeType Factory(RawRuntimeTypeHandleKey rawRuntimeTypeHandleKey) { RuntimeTypeHandle runtimeTypeHandle = rawRuntimeTypeHandleKey.RuntimeTypeHandle; // Desktop compat: Allows Type.GetTypeFromHandle(default(RuntimeTypeHandle)) to map to null. if (runtimeTypeHandle.RawValue == (IntPtr)0) return null; EETypePtr eeType = runtimeTypeHandle.ToEETypePtr(); return TypeTableForTypesWithEETypes.Table.GetOrAdd(eeType); } public static RuntimeTypeHandleToRuntimeTypeCache Table = new RuntimeTypeHandleToRuntimeTypeCache(); } // // Type table for *all* RuntimeTypes that have an EEType associated with it (named types, // arrays, constructed generic types.) // // The EEType itself serves as the dictionary key. // // This table's key uses semantic identity as the compare function. Thus, it properly serves to unify all semantically equivalent types // into a single Type instance. // private sealed class TypeTableForTypesWithEETypes : ConcurrentUnifierW<EETypePtr, RuntimeType> { private TypeTableForTypesWithEETypes() { } protected sealed override RuntimeType Factory(EETypePtr eeType) { RuntimeImports.RhEETypeClassification classification = RuntimeImports.RhGetEETypeClassification(eeType); switch (classification) { case RuntimeImports.RhEETypeClassification.Regular: return new RuntimeEENamedNonGenericType(eeType); case RuntimeImports.RhEETypeClassification.Array: return new RuntimeEEArrayType(eeType); case RuntimeImports.RhEETypeClassification.UnmanagedPointer: return new RuntimeEEPointerType(eeType); case RuntimeImports.RhEETypeClassification.GenericTypeDefinition: return new RuntimeEENamedGenericType(eeType); case RuntimeImports.RhEETypeClassification.Generic: // Reflection blocked constructed generic types simply pretend to not be generic // This is reasonable, as the behavior of reflection blocked types is supposed // to be that they expose the minimal information about a type that is necessary // for users of Object.GetType to move from that type to a type that isn't // reflection blocked. By not revealing that reflection blocked types are generic // we are making it appear as if implementation detail types exposed to user code // are all non-generic, which is theoretically possible, and by doing so // we avoid (in all known circumstances) the very complicated case of representing // the interfaces, base types, and generic parameter types of reflection blocked // generic type definitions. if (RuntimeAugments.Callbacks.IsReflectionBlocked(new RuntimeTypeHandle(eeType))) { return new RuntimeEENamedNonGenericType(eeType); } if (RuntimeImports.AreTypesAssignable(eeType, typeof(MDArrayRank2).TypeHandle.ToEETypePtr())) return new RuntimeEEArrayType(eeType, rank: 2); if (RuntimeImports.AreTypesAssignable(eeType, typeof(MDArrayRank3).TypeHandle.ToEETypePtr())) return new RuntimeEEArrayType(eeType, rank: 3); if (RuntimeImports.AreTypesAssignable(eeType, typeof(MDArrayRank4).TypeHandle.ToEETypePtr())) return new RuntimeEEArrayType(eeType, rank: 4); return new RuntimeEEConstructedGenericType(eeType); default: throw new ArgumentException(SR.Arg_InvalidRuntimeTypeHandle); } } public static TypeTableForTypesWithEETypes Table = new TypeTableForTypesWithEETypes(); } // // Type table for all SZ RuntimeArrayTypes. // The element type serves as the dictionary key. // private sealed class TypeTableForArrayTypes : ConcurrentUnifierWKeyed<RuntimeType, RuntimeArrayType> { protected sealed override RuntimeArrayType Factory(RuntimeType elementType) { // We only permit creating parameterized types if the pay-for-play policy specifically allows them *or* if the result // type would be an open type. RuntimeTypeHandle runtimeTypeHandle; RuntimeTypeHandle elementTypeHandle; if (elementType.InternalTryGetTypeHandle(out elementTypeHandle) && RuntimeAugments.Callbacks.TryGetArrayTypeForElementType(elementTypeHandle, out runtimeTypeHandle)) return (RuntimeArrayType)(RuntimeTypeUnifier.GetTypeForRuntimeTypeHandle(runtimeTypeHandle)); if (elementType.IsByRef) throw new TypeLoadException(SR.Format(SR.ArgumentException_InvalidArrayElementType, elementType)); if (elementType.InternalIsGenericTypeDefinition) throw new ArgumentException(SR.Format(SR.ArgumentException_InvalidArrayElementType, elementType)); if (!elementType.InternalIsOpen) throw RuntimeAugments.Callbacks.CreateMissingArrayTypeException(elementType, false, 1); return new RuntimeInspectionOnlyArrayType(elementType); } public static TypeTableForArrayTypes Table = new TypeTableForArrayTypes(); } // // Type table for all MultiDim RuntimeArrayTypes. // The element type serves as the dictionary key. // private sealed class TypeTableForMultiDimArrayTypes : ConcurrentUnifierWKeyed<RuntimeType, RuntimeArrayType> { public TypeTableForMultiDimArrayTypes(int rank) { _rank = rank; } protected sealed override RuntimeArrayType Factory(RuntimeType elementType) { // We only permit creating parameterized types if the pay-for-play policy specifically allows them *or* if the result // type would be an open type. RuntimeTypeHandle runtimeTypeHandle; RuntimeTypeHandle elementTypeHandle; if (elementType.InternalTryGetTypeHandle(out elementTypeHandle) && RuntimeAugments.Callbacks.TryGetMultiDimArrayTypeForElementType(elementTypeHandle, _rank, out runtimeTypeHandle)) return (RuntimeArrayType)(RuntimeTypeUnifier.GetTypeForRuntimeTypeHandle(runtimeTypeHandle)); if (elementType.IsByRef) throw new TypeLoadException(SR.Format(SR.ArgumentException_InvalidArrayElementType, elementType)); if (elementType.InternalIsGenericTypeDefinition) throw new ArgumentException(SR.Format(SR.ArgumentException_InvalidArrayElementType, elementType)); if (!elementType.InternalIsOpen) throw RuntimeAugments.Callbacks.CreateMissingArrayTypeException(elementType, true, _rank); return new RuntimeInspectionOnlyArrayType(elementType, _rank); } private int _rank; } // // For the hopefully rare case of multidim arrays, we have a dictionary of dictionaries. // private sealed class TypeTableForMultiDimArrayTypesTable : ConcurrentUnifier<int, TypeTableForMultiDimArrayTypes> { protected sealed override TypeTableForMultiDimArrayTypes Factory(int rank) { Debug.Assert(rank > 0); return new TypeTableForMultiDimArrayTypes(rank); } public static TypeTableForMultiDimArrayTypesTable Table = new TypeTableForMultiDimArrayTypesTable(); } // // Type table for all RuntimeByRefTypes. (There's no such thing as an EEType for a byref so all ByRef types are "inspection only.") // The target type serves as the dictionary key. // private sealed class TypeTableForByRefTypes : ConcurrentUnifierWKeyed<RuntimeType, RuntimeByRefType> { private TypeTableForByRefTypes() { } protected sealed override RuntimeByRefType Factory(RuntimeType targetType) { return new RuntimeByRefType(targetType); } public static TypeTableForByRefTypes Table = new TypeTableForByRefTypes(); } // // Type table for all RuntimePointerTypes. // The target type serves as the dictionary key. // private sealed class TypeTableForPointerTypes : ConcurrentUnifierWKeyed<RuntimeType, RuntimePointerType> { private TypeTableForPointerTypes() { } protected sealed override RuntimePointerType Factory(RuntimeType elementType) { RuntimeTypeHandle thElementType; if (elementType.InternalTryGetTypeHandle(out thElementType)) { RuntimeTypeHandle thForPointerType; if (RuntimeAugments.Callbacks.TryGetPointerTypeForTargetType(thElementType, out thForPointerType)) { Debug.Assert(thForPointerType.Classification == RuntimeImports.RhEETypeClassification.UnmanagedPointer); return (RuntimePointerType)(RuntimeTypeUnifier.GetTypeForRuntimeTypeHandle(thForPointerType)); } } return new RuntimeInspectionOnlyPointerType(elementType); } public static TypeTableForPointerTypes Table = new TypeTableForPointerTypes(); } // // Type table for all constructed generic types. // private sealed class TypeTableForConstructedGenericTypes : ConcurrentUnifierWKeyed<ConstructedGenericTypeKey, RuntimeConstructedGenericType> { private TypeTableForConstructedGenericTypes() { } protected sealed override RuntimeConstructedGenericType Factory(ConstructedGenericTypeKey key) { // We only permit creating parameterized types if the pay-for-play policy specifically allows them *or* if the result // type would be an open type. RuntimeTypeHandle runtimeTypeHandle; if (TryFindRuntimeTypeHandleForConstructedGenericType(key, out runtimeTypeHandle)) return (RuntimeConstructedGenericType)(RuntimeTypeUnifier.GetTypeForRuntimeTypeHandle(runtimeTypeHandle)); bool atLeastOneOpenType = false; foreach (RuntimeType genericTypeArgument in key.GenericTypeArguments) { if (genericTypeArgument.IsByRef || genericTypeArgument.InternalIsGenericTypeDefinition) throw new ArgumentException(SR.Format(SR.ArgumentException_InvalidTypeArgument, genericTypeArgument)); if (genericTypeArgument.InternalIsOpen) atLeastOneOpenType = true; } if (!atLeastOneOpenType) throw RuntimeAugments.Callbacks.CreateMissingConstructedGenericTypeException(key.GenericTypeDefinition, key.GenericTypeArguments); return new RuntimeInspectionOnlyConstructedGenericType(key.GenericTypeDefinition, key.GenericTypeArguments); } private bool TryFindRuntimeTypeHandleForConstructedGenericType(ConstructedGenericTypeKey key, out RuntimeTypeHandle runtimeTypeHandle) { runtimeTypeHandle = default(RuntimeTypeHandle); RuntimeTypeHandle genericTypeDefinitionHandle = default(RuntimeTypeHandle); if (!key.GenericTypeDefinition.InternalTryGetTypeHandle(out genericTypeDefinitionHandle)) return false; if (RuntimeAugments.Callbacks.IsReflectionBlocked(genericTypeDefinitionHandle)) return false; RuntimeType[] genericTypeArguments = key.GenericTypeArguments; RuntimeTypeHandle[] genericTypeArgumentHandles = new RuntimeTypeHandle[genericTypeArguments.Length]; for (int i = 0; i < genericTypeArguments.Length; i++) { if (!genericTypeArguments[i].InternalTryGetTypeHandle(out genericTypeArgumentHandles[i])) return false; } if (!RuntimeAugments.Callbacks.TryGetConstructedGenericTypeForComponents(genericTypeDefinitionHandle, genericTypeArgumentHandles, out runtimeTypeHandle)) return false; return true; } public static TypeTableForConstructedGenericTypes Table = new TypeTableForConstructedGenericTypes(); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Apis.AdExperienceReport.v1 { /// <summary>The AdExperienceReport Service.</summary> public class AdExperienceReportService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public AdExperienceReportService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public AdExperienceReportService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { Sites = new SitesResource(this); ViolatingSites = new ViolatingSitesResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "adexperiencereport"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://adexperiencereport.googleapis.com/"; #else "https://adexperiencereport.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://adexperiencereport.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Gets the Sites resource.</summary> public virtual SitesResource Sites { get; } /// <summary>Gets the ViolatingSites resource.</summary> public virtual ViolatingSitesResource ViolatingSites { get; } } /// <summary>A base abstract class for AdExperienceReport requests.</summary> public abstract class AdExperienceReportBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new AdExperienceReportBaseServiceRequest instance.</summary> protected AdExperienceReportBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes AdExperienceReport parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "sites" collection of methods.</summary> public class SitesResource { private const string Resource = "sites"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public SitesResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Gets a site's Ad Experience Report summary.</summary> /// <param name="name"> /// Required. The name of the site whose summary to get, e.g. `sites/http%3A%2F%2Fwww.google.com%2F`. Format: /// `sites/{site}` /// </param> public virtual GetRequest Get(string name) { return new GetRequest(service, name); } /// <summary>Gets a site's Ad Experience Report summary.</summary> public class GetRequest : AdExperienceReportBaseServiceRequest<Google.Apis.AdExperienceReport.v1.Data.SiteSummaryResponse> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary> /// Required. The name of the site whose summary to get, e.g. `sites/http%3A%2F%2Fwww.google.com%2F`. /// Format: `sites/{site}` /// </summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "get"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/{+name}"; /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^sites/[^/]+$", }); } } } /// <summary>The "violatingSites" collection of methods.</summary> public class ViolatingSitesResource { private const string Resource = "violatingSites"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ViolatingSitesResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Lists sites that are failing in the Ad Experience Report on at least one platform.</summary> public virtual ListRequest List() { return new ListRequest(service); } /// <summary>Lists sites that are failing in the Ad Experience Report on at least one platform.</summary> public class ListRequest : AdExperienceReportBaseServiceRequest<Google.Apis.AdExperienceReport.v1.Data.ViolatingSitesResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary>Gets the method name.</summary> public override string MethodName => "list"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/violatingSites"; /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } } } namespace Google.Apis.AdExperienceReport.v1.Data { /// <summary>A site's Ad Experience Report summary on a single platform.</summary> public class PlatformSummary : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The site's Ad Experience Report status on this platform.</summary> [Newtonsoft.Json.JsonPropertyAttribute("betterAdsStatus")] public virtual string BetterAdsStatus { get; set; } /// <summary> /// The time at which [enforcement](https://support.google.com/webtools/answer/7308033) against the site began /// or will begin on this platform. Not set when the filter_status is OFF. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("enforcementTime")] public virtual object EnforcementTime { get; set; } /// <summary> /// The site's [enforcement status](https://support.google.com/webtools/answer/7308033) on this platform. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("filterStatus")] public virtual string FilterStatus { get; set; } /// <summary>The time at which the site's status last changed on this platform.</summary> [Newtonsoft.Json.JsonPropertyAttribute("lastChangeTime")] public virtual object LastChangeTime { get; set; } /// <summary> /// The site's regions on this platform. No longer populated, because there is no longer any semantic difference /// between sites in different regions. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("region")] public virtual System.Collections.Generic.IList<string> Region { get; set; } /// <summary> /// A link to the full Ad Experience Report for the site on this platform.. Not set in ViolatingSitesResponse. /// Note that you must complete the [Search Console verification /// process](https://support.google.com/webmasters/answer/9008080) for the site before you can access the full /// report. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("reportUrl")] public virtual string ReportUrl { get; set; } /// <summary>Whether the site is currently under review on this platform.</summary> [Newtonsoft.Json.JsonPropertyAttribute("underReview")] public virtual System.Nullable<bool> UnderReview { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for GetSiteSummary.</summary> public class SiteSummaryResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The site's Ad Experience Report summary on desktop.</summary> [Newtonsoft.Json.JsonPropertyAttribute("desktopSummary")] public virtual PlatformSummary DesktopSummary { get; set; } /// <summary>The site's Ad Experience Report summary on mobile.</summary> [Newtonsoft.Json.JsonPropertyAttribute("mobileSummary")] public virtual PlatformSummary MobileSummary { get; set; } /// <summary>The name of the reviewed site, e.g. `google.com`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("reviewedSite")] public virtual string ReviewedSite { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for ListViolatingSites.</summary> public class ViolatingSitesResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The list of violating sites.</summary> [Newtonsoft.Json.JsonPropertyAttribute("violatingSites")] public virtual System.Collections.Generic.IList<SiteSummaryResponse> ViolatingSites { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System { using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Diagnostics.Contracts; using System.Runtime.Serialization; using System.Runtime.CompilerServices; [Serializable] public abstract class StringComparer : IComparer, IEqualityComparer, IComparer<string>, IEqualityComparer<string> { private static readonly CultureAwareComparer _invariantCulture = new CultureAwareComparer(CultureInfo.InvariantCulture, false); private static readonly CultureAwareComparer _invariantCultureIgnoreCase = new CultureAwareComparer(CultureInfo.InvariantCulture, true); private static readonly OrdinalComparer _ordinal = new OrdinalComparer(); private static readonly OrdinalIgnoreCaseComparer _ordinalIgnoreCase = new OrdinalIgnoreCaseComparer(); public static StringComparer InvariantCulture { get { Contract.Ensures(Contract.Result<StringComparer>() != null); return _invariantCulture; } } public static StringComparer InvariantCultureIgnoreCase { get { Contract.Ensures(Contract.Result<StringComparer>() != null); return _invariantCultureIgnoreCase; } } public static StringComparer CurrentCulture { get { Contract.Ensures(Contract.Result<StringComparer>() != null); return new CultureAwareComparer(CultureInfo.CurrentCulture, false); } } public static StringComparer CurrentCultureIgnoreCase { get { Contract.Ensures(Contract.Result<StringComparer>() != null); return new CultureAwareComparer(CultureInfo.CurrentCulture, true); } } public static StringComparer Ordinal { get { Contract.Ensures(Contract.Result<StringComparer>() != null); return _ordinal; } } public static StringComparer OrdinalIgnoreCase { get { Contract.Ensures(Contract.Result<StringComparer>() != null); return _ordinalIgnoreCase; } } // Convert a StringComparison to a StringComparer public static StringComparer FromComparison(StringComparison comparisonType) { switch (comparisonType) { case StringComparison.CurrentCulture: return CurrentCulture; case StringComparison.CurrentCultureIgnoreCase: return CurrentCultureIgnoreCase; case StringComparison.InvariantCulture: return InvariantCulture; case StringComparison.InvariantCultureIgnoreCase: return InvariantCultureIgnoreCase; case StringComparison.Ordinal: return Ordinal; case StringComparison.OrdinalIgnoreCase: return OrdinalIgnoreCase; default: throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType)); } } public static StringComparer Create(CultureInfo culture, bool ignoreCase) { if (culture == null) { throw new ArgumentNullException(nameof(culture)); } Contract.Ensures(Contract.Result<StringComparer>() != null); Contract.EndContractBlock(); return new CultureAwareComparer(culture, ignoreCase); } public int Compare(object x, object y) { if (x == y) return 0; if (x == null) return -1; if (y == null) return 1; String sa = x as String; if (sa != null) { String sb = y as String; if (sb != null) { return Compare(sa, sb); } } IComparable ia = x as IComparable; if (ia != null) { return ia.CompareTo(y); } throw new ArgumentException(Environment.GetResourceString("Argument_ImplementIComparable")); } public new bool Equals(Object x, Object y) { if (x == y) return true; if (x == null || y == null) return false; String sa = x as String; if (sa != null) { String sb = y as String; if (sb != null) { return Equals(sa, sb); } } return x.Equals(y); } public int GetHashCode(object obj) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } Contract.EndContractBlock(); string s = obj as string; if (s != null) { return GetHashCode(s); } return obj.GetHashCode(); } public abstract int Compare(String x, String y); public abstract bool Equals(String x, String y); public abstract int GetHashCode(string obj); } [Serializable] internal sealed class CultureAwareComparer : StringComparer #if FEATURE_RANDOMIZED_STRING_HASHING , IWellKnownStringEqualityComparer #endif { private readonly CompareInfo _compareInfo; private readonly CompareOptions _options; internal CultureAwareComparer(CultureInfo culture, bool ignoreCase) { _compareInfo = culture.CompareInfo; _options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None; } public override int Compare(string x, string y) { if (object.ReferenceEquals(x, y)) return 0; if (x == null) return -1; if (y == null) return 1; return _compareInfo.Compare(x, y, _options); } public override bool Equals(string x, string y) { if (object.ReferenceEquals(x, y)) return true; if (x == null || y == null) return false; return _compareInfo.Compare(x, y, _options) == 0; } public override int GetHashCode(string obj) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } return _compareInfo.GetHashCodeOfString(obj, _options); } // Equals method for the comparer itself. public override bool Equals(object obj) { var comparer = obj as CultureAwareComparer; return comparer != null && _options == comparer._options && _compareInfo.Equals(comparer._compareInfo); } public override int GetHashCode() { int hashCode = _compareInfo.GetHashCode(); return _options == CompareOptions.None ? hashCode : ~hashCode; } #if FEATURE_RANDOMIZED_STRING_HASHING IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() => this; #endif } [Serializable] internal sealed class OrdinalComparer : StringComparer #if FEATURE_RANDOMIZED_STRING_HASHING , IWellKnownStringEqualityComparer #endif { public override int Compare(string x, string y) => string.CompareOrdinal(x, y); public override bool Equals(string x, string y) => string.Equals(x, y); public override int GetHashCode(string obj) { if (obj == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj); } return obj.GetHashCode(); } // Equals/GetHashCode methods for the comparer itself. public override bool Equals(object obj) => obj is OrdinalComparer; public override int GetHashCode() => nameof(OrdinalComparer).GetHashCode(); #if FEATURE_RANDOMIZED_STRING_HASHING IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() => this; #endif } [Serializable] internal sealed class OrdinalIgnoreCaseComparer : StringComparer #if FEATURE_RANDOMIZED_STRING_HASHING , IWellKnownStringEqualityComparer #endif { public override int Compare(string x, string y) => string.Compare(x, y, StringComparison.OrdinalIgnoreCase); public override bool Equals(string x, string y) => string.Equals(x, y, StringComparison.OrdinalIgnoreCase); public override int GetHashCode(string obj) { if (obj == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj); } return TextInfo.GetHashCodeOrdinalIgnoreCase(obj); } // Equals/GetHashCode methods for the comparer itself. public override bool Equals(object obj) => obj is OrdinalIgnoreCaseComparer; public override int GetHashCode() => nameof(OrdinalIgnoreCaseComparer).GetHashCode(); #if FEATURE_RANDOMIZED_STRING_HASHING IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() => this; #endif } #if FEATURE_RANDOMIZED_STRING_HASHING // This interface is implemented by string comparers in the framework that can opt into // randomized hashing behaviors. internal interface IWellKnownStringEqualityComparer { // Get an IEqaulityComparer that can be serailzied (e.g., it exists in older versions). IEqualityComparer GetEqualityComparerForSerialization(); } #endif }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using IServiceProvider = System.IServiceProvider; using ShellConstants = Microsoft.VisualStudio.Shell.Interop.Constants; namespace Microsoft.VisualStudio.Project { /// <summary> /// This abstract class handles opening, saving of items in the hierarchy. /// </summary> [CLSCompliant(false)] public abstract class DocumentManager { #region fields private HierarchyNode node = null; #endregion #region properties protected HierarchyNode Node { get { return this.node; } } #endregion #region ctors protected DocumentManager(HierarchyNode node) { this.node = node; } #endregion #region virtual methods /// <summary> /// Open a document using the standard editor. This method has no implementation since a document is abstract in this context /// </summary> /// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param> /// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param> /// <param name="windowFrame">A reference to the window frame that is mapped to the document</param> /// <param name="windowFrameAction">Determine the UI action on the document window</param> /// <returns>NotImplementedException</returns> /// <remarks>See FileDocumentManager class for an implementation of this method</remarks> public virtual int Open(ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction) { throw new NotImplementedException(); } /// <summary> /// Open a document using a specific editor. This method has no implementation. /// </summary> /// <param name="editorFlags">Specifies actions to take when opening a specific editor. Possible editor flags are defined in the enumeration Microsoft.VisualStudio.Shell.Interop.__VSOSPEFLAGS</param> /// <param name="editorType">Unique identifier of the editor type</param> /// <param name="physicalView">Name of the physical view. If null, the environment calls MapLogicalView on the editor factory to determine the physical view that corresponds to the logical view. In this case, null does not specify the primary view, but rather indicates that you do not know which view corresponds to the logical view</param> /// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param> /// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param> /// <param name="frame">A reference to the window frame that is mapped to the document</param> /// <param name="windowFrameAction">Determine the UI action on the document window</param> /// <returns>NotImplementedException</returns> /// <remarks>See FileDocumentManager for an implementation of this method</remarks> public virtual int OpenWithSpecific(uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame frame, WindowFrameShowAction windowFrameAction) { throw new NotImplementedException(); } /// <summary> /// Close an open document window /// </summary> /// <param name="closeFlag">Decides how to close the document</param> /// <returns>S_OK if successful, otherwise an error is returned</returns> public virtual int Close(__FRAMECLOSE closeFlag) { if(this.node == null || this.node.ProjectMgr == null || this.node.ProjectMgr.IsClosed) { return VSConstants.E_FAIL; } // Get info about the document bool isDirty, isOpen, isOpenedByUs; uint docCookie; IVsPersistDocData ppIVsPersistDocData; this.GetDocInfo(out isOpen, out isDirty, out isOpenedByUs, out docCookie, out ppIVsPersistDocData); if(isOpenedByUs) { IVsUIShellOpenDocument shell = this.Node.ProjectMgr.Site.GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; Guid logicalView = Guid.Empty; uint grfIDO = 0; IVsUIHierarchy pHierOpen; uint[] itemIdOpen = new uint[1]; IVsWindowFrame windowFrame; int fOpen; ErrorHandler.ThrowOnFailure(shell.IsDocumentOpen(this.Node.ProjectMgr, this.Node.ID, this.Node.Url, ref logicalView, grfIDO, out pHierOpen, itemIdOpen, out windowFrame, out fOpen)); if(windowFrame != null) { docCookie = 0; return windowFrame.CloseFrame((uint)closeFlag); } } return VSConstants.S_OK; } /// <summary> /// Silently saves an open document /// </summary> /// <param name="saveIfDirty">Save the open document only if it is dirty</param> /// <remarks>The call to SaveDocData may return Microsoft.VisualStudio.Shell.Interop.PFF_RESULTS.STG_S_DATALOSS to indicate some characters could not be represented in the current codepage</remarks> public virtual void Save(bool saveIfDirty) { bool isDirty, isOpen, isOpenedByUs; uint docCookie; IVsPersistDocData persistDocData; this.GetDocInfo(out isOpen, out isDirty, out isOpenedByUs, out docCookie, out persistDocData); if(isDirty && saveIfDirty && persistDocData != null) { string name; int cancelled; ErrorHandler.ThrowOnFailure(persistDocData.SaveDocData(VSSAVEFLAGS.VSSAVE_SilentSave, out name, out cancelled)); } } #endregion #region helper methods /// <summary> /// Get document properties from RDT /// </summary> internal void GetDocInfo( out bool isOpen, // true if the doc is opened out bool isDirty, // true if the doc is dirty out bool isOpenedByUs, // true if opened by our project out uint docCookie, // VSDOCCOOKIE if open out IVsPersistDocData persistDocData) { isOpen = isDirty = isOpenedByUs = false; docCookie = (uint)ShellConstants.VSDOCCOOKIE_NIL; persistDocData = null; if(this.node == null || this.node.ProjectMgr == null || this.node.ProjectMgr.IsClosed) { return; } IVsHierarchy hierarchy; uint vsitemid = VSConstants.VSITEMID_NIL; VsShellUtilities.GetRDTDocumentInfo(this.node.ProjectMgr.Site, this.node.Url, out hierarchy, out vsitemid, out persistDocData, out docCookie); if(hierarchy == null || docCookie == (uint)ShellConstants.VSDOCCOOKIE_NIL) { return; } isOpen = true; // check if the doc is opened by another project if(Utilities.IsSameComObject(this.node.ProjectMgr, hierarchy)) { isOpenedByUs = true; } if(persistDocData != null) { int isDocDataDirty; ErrorHandler.ThrowOnFailure(persistDocData.IsDocDataDirty(out isDocDataDirty)); isDirty = (isDocDataDirty != 0); } } protected string GetOwnerCaption() { Debug.Assert(this.node != null, "No node has been initialized for the document manager"); object pvar; ErrorHandler.ThrowOnFailure(this.node.GetProperty(this.node.ID, (int)__VSHPROPID.VSHPROPID_Caption, out pvar)); return (pvar as string); } protected static void CloseWindowFrame(ref IVsWindowFrame windowFrame) { if(windowFrame != null) { try { ErrorHandler.ThrowOnFailure(windowFrame.CloseFrame(0)); } finally { windowFrame = null; } } } protected string GetFullPathForDocument() { string fullPath = String.Empty; Debug.Assert(this.node != null, "No node has been initialized for the document manager"); // Get the URL representing the item fullPath = this.node.GetMkDocument(); Debug.Assert(!String.IsNullOrEmpty(fullPath), "Could not retrive the fullpath for the node" + this.Node.ID.ToString(CultureInfo.CurrentCulture)); return fullPath; } #endregion #region static methods /// <summary> /// Updates the caption for all windows associated to the document. /// </summary> /// <param name="site">The service provider.</param> /// <param name="caption">The new caption.</param> /// <param name="docData">The IUnknown interface to a document data object associated with a registered document.</param> public static void UpdateCaption(IServiceProvider site, string caption, IntPtr docData) { if(site == null) { throw new ArgumentNullException("site"); } if(String.IsNullOrEmpty(caption)) { throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "caption"); } IVsUIShell uiShell = site.GetService(typeof(SVsUIShell)) as IVsUIShell; // We need to tell the windows to update their captions. IEnumWindowFrames windowFramesEnum; ErrorHandler.ThrowOnFailure(uiShell.GetDocumentWindowEnum(out windowFramesEnum)); IVsWindowFrame[] windowFrames = new IVsWindowFrame[1]; uint fetched; while(windowFramesEnum.Next(1, windowFrames, out fetched) == VSConstants.S_OK && fetched == 1) { IVsWindowFrame windowFrame = windowFrames[0]; object data; ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out data)); IntPtr ptr = Marshal.GetIUnknownForObject(data); try { if(ptr == docData) { ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID.VSFPROPID_OwnerCaption, caption)); } } finally { if(ptr != IntPtr.Zero) { Marshal.Release(ptr); } } } } /// <summary> /// Rename document in the running document table from oldName to newName. /// </summary> /// <param name="provider">The service provider.</param> /// <param name="oldName">Full path to the old name of the document.</param> /// <param name="newName">Full path to the new name of the document.</param> /// <param name="newItemId">The new item id of the document</param> public static void RenameDocument(IServiceProvider site, string oldName, string newName, uint newItemId) { if(site == null) { throw new ArgumentNullException("site"); } if(String.IsNullOrEmpty(oldName)) { throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "oldName"); } if(String.IsNullOrEmpty(newName)) { throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "newName"); } if(newItemId == VSConstants.VSITEMID_NIL) { throw new ArgumentNullException("newItemId"); } IVsRunningDocumentTable pRDT = site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; IVsUIShellOpenDocument doc = site.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument; if(pRDT == null || doc == null) return; IVsHierarchy pIVsHierarchy; uint itemId; IntPtr docData; uint uiVsDocCookie; ErrorHandler.ThrowOnFailure(pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, oldName, out pIVsHierarchy, out itemId, out docData, out uiVsDocCookie)); if(docData != IntPtr.Zero) { try { IntPtr pUnk = Marshal.GetIUnknownForObject(pIVsHierarchy); Guid iid = typeof(IVsHierarchy).GUID; IntPtr pHier; Marshal.QueryInterface(pUnk, ref iid, out pHier); try { ErrorHandler.ThrowOnFailure(pRDT.RenameDocument(oldName, newName, pHier, newItemId)); } finally { if(pHier != IntPtr.Zero) Marshal.Release(pHier); if(pUnk != IntPtr.Zero) Marshal.Release(pUnk); } } finally { Marshal.Release(docData); } } } #endregion } }
// Copyright (c) 2017 Jan Pluskal // //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.Diagnostics; using System.IO; using Castle.Core.Logging; using Castle.MicroKernel.Registration; using Castle.Services.Logging.Log4netIntegration; using Castle.Windsor; using log4net; using log4net.Config; using log4net.Layout; using log4net.Repository; using log4net.Repository.Hierarchy; namespace Netfox.Logger { public class NetfoxLogger : ILogger, IDisposable { public NetfoxLogger(NetfoxFileAppender netfoxFileAppender, NetfoxOutputAppender netfoxOutputAppender) { this.NetfoxFileAppender = netfoxFileAppender; this.NetfoxOutputAppender = netfoxOutputAppender; this.CreateLogger("default"); } public void CloseLoggingDirectory() { NetfoxFileAppender.Close();} public void ChangeLoggingDirectory(DirectoryInfo directoryInfo) { if(directoryInfo == null) { this.Logger?.Error($"ChangeLoggingDirectory failed - null {nameof(directoryInfo)}"); return; } try { if (!directoryInfo.Exists) directoryInfo.Create(); } catch(IOException e) { this.Logger?.Error("ChangeLoggingDirectory failed", e); } var oldLoggingDirectoryInfo = this.LoggingDirectory; try { this.LoggingDirectory = directoryInfo; this.NetfoxFileAppender.ChangeLoggingDirectory(directoryInfo); } catch(Exception e) { this.LoggingDirectory = oldLoggingDirectoryInfo; this.Logger?.Error("ChangeLoggingDirectory failed", e); } } public DirectoryInfo LoggingDirectory { get; private set; } public void CreateLogger(string loggerName) { //It will create a repository for each different arg it will receive var repositoryName = "Netfox"; ILoggerRepository repository = null; var repositories = LogManager.GetAllRepositories(); foreach (var loggerRepository in repositories) { if (loggerRepository.Name.Equals(repositoryName)) { repository = loggerRepository; break; } } if (repository == null) { //Create a new repository repository = LogManager.CreateRepository(repositoryName); var hierarchy = (Hierarchy)repository; hierarchy.Root.Additivity = false; //Add appenders you need: here I need a rolling file and a memoryappender hierarchy.Root.AddAppender(this.NetfoxOutputAppender); hierarchy.Root.AddAppender(this.NetfoxFileAppender); BasicConfigurator.Configure(repository); } //Returns a logger from a particular repository; //Logger with same name but different repository will log using different appenders var logger = LogManager.GetLogger(repositoryName, loggerName); var logg = new ExtendedLog4netFactory(); this.Logger = new ExtendedLog4netLogger(logger, logg); } public LoggerLevel BackgroundLoggerLevel { get => this.NetfoxFileAppender.LoggerLevel; set => this.NetfoxFileAppender.LoggerLevel = value; } public LoggerLevel ExplicitLoggerLevel { get => this.NetfoxOutputAppender.LoggerLevel; set => this.NetfoxOutputAppender.LoggerLevel = value; } private NetfoxFileAppender NetfoxFileAppender { get; set; } private NetfoxOutputAppender NetfoxOutputAppender { get; set; } public NetfoxLogger(string name):this(name,LoggerLevel.Debug) { } public NetfoxLogger(string name, LoggerLevel level) { this.CreateLogger(name); } public ExtendedLog4netLogger Logger { get; set; } #region Implementation of ILogger public ILogger CreateChildLogger(string loggerName) { return this.Logger?.CreateChildLogger(loggerName); } public void Trace(string message) { this.Logger.Trace(message); } public void Trace(Func<string> messageFactory) { this.Logger.Trace(messageFactory); } public void Trace(string message, Exception exception) { this.Logger.Trace(message, exception); } public void TraceFormat(string format, params object[] args) { this.Logger.Trace(string.Format(format, args));} public void TraceFormat(Exception exception, string format, params object[] args) { this.Logger.Trace(string.Format(format, args), exception); } public void TraceFormat(IFormatProvider formatProvider, string format, params object[] args) { this.Logger.Trace(string.Format(formatProvider, format, args)); } public void TraceFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args) { this.Logger.Trace(string.Format(formatProvider, format, args), exception); } public void Debug(string message) { this.Logger?.Debug(message); } public void Debug(Func<string> messageFactory) { this.Logger?.Debug(messageFactory); } public void Debug(string message, Exception exception) { this.Logger?.Debug(message, exception); } public void DebugFormat(string format, params object[] args) { this.Logger?.DebugFormat(format, args); } public void DebugFormat(Exception exception, string format, params object[] args) { this.Logger?.DebugFormat(exception, format, args); } public void DebugFormat(IFormatProvider formatProvider, string format, params object[] args) { this.Logger?.DebugFormat(formatProvider, format, args); } public void DebugFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args) { this.Logger?.DebugFormat(exception, formatProvider, format, args); } public void Error(string message) { this.Logger?.Error(message); } public void Error(Func<string> messageFactory) { this.Logger?.Error(messageFactory); } public void Error(string message, Exception exception) { this.Logger?.Error(message, exception); } public void ErrorFormat(string format, params object[] args) { this.Logger?.ErrorFormat(format, args); } public void ErrorFormat(Exception exception, string format, params object[] args) { this.Logger?.ErrorFormat(exception, format, args); } public void ErrorFormat(IFormatProvider formatProvider, string format, params object[] args) { this.Logger?.ErrorFormat(formatProvider, format, args); } public void ErrorFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args) { this.Logger?.ErrorFormat(exception, formatProvider, format, args); } public void Fatal(string message) { this.Logger?.Fatal(message); } public void Fatal(Func<string> messageFactory) { this.Logger?.Fatal(messageFactory); } public void Fatal(string message, Exception exception) { this.Logger?.Fatal(message, exception); } public void FatalFormat(string format, params object[] args) { this.Logger?.FatalFormat(format, args); } public void FatalFormat(Exception exception, string format, params object[] args) { this.Logger?.FatalFormat(exception, format, args); } public void FatalFormat(IFormatProvider formatProvider, string format, params object[] args) { this.Logger?.FatalFormat(formatProvider, format, args); } public void FatalFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args) { this.Logger?.FatalFormat(exception, formatProvider, format, args); } public void Info(string message) { this.Logger?.Info(message); } public void Info(Func<string> messageFactory) { this.Logger?.Info(messageFactory); } public void Info(string message, Exception exception) { this.Logger?.Info(message, exception); } public void InfoFormat(string format, params object[] args) { this.Logger?.InfoFormat(format, args); } public void InfoFormat(Exception exception, string format, params object[] args) { this.Logger?.InfoFormat(exception, format, args); } public void InfoFormat(IFormatProvider formatProvider, string format, params object[] args) { this.Logger?.InfoFormat(formatProvider, format, args); } public void InfoFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args) { this.Logger?.InfoFormat(exception, formatProvider, format, args); } public void Warn(string message) { this.Logger?.Warn(message); } public void Warn(Func<string> messageFactory) { this.Logger?.Warn(messageFactory); } public void Warn(string message, Exception exception) { this.Logger?.Warn(message, exception); } public void WarnFormat(string format, params object[] args) { this.Logger?.WarnFormat(format, args); } public void WarnFormat(Exception exception, string format, params object[] args) { this.Logger?.WarnFormat(exception, format, args); } public void WarnFormat(IFormatProvider formatProvider, string format, params object[] args) { this.Logger?.WarnFormat(formatProvider, format, args); } public void WarnFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args) { this.Logger?.WarnFormat(exception, formatProvider, format, args); } public bool IsTraceEnabled { get; } public bool IsDebugEnabled => this.Logger.IsDebugEnabled; public bool IsErrorEnabled => this.Logger.IsErrorEnabled; public bool IsFatalEnabled => this.Logger.IsFatalEnabled; public bool IsInfoEnabled => this.Logger.IsInfoEnabled; public bool IsWarnEnabled => this.Logger.IsWarnEnabled; #region IDisposable public void Dispose() { this.NetfoxFileAppender.Close(); this.NetfoxOutputAppender.Close(); } #endregion #endregion } }
using Microsoft.DirectX.DirectInput; using System; using System.Collections.Generic; using System.Drawing; using TGC.Core.Input; using TGC.Core.Mathematica; using TGC.Examples.Engine2D.Spaceship.Core; namespace TGC.Examples.Engine2D.Spaceship { internal class Spaceship : GameObject { //El angulo al que apunta la nave. private float angle; //El angulo al mouse. private float angleToMousePointer; //La posicion del centro del sprite private TGCVector2 centerPosition; private int contadorAnimacion; //El numero de sprite dentro del spritesheet private int currentSprite; //Cuanto tiempo paso desde que se disparo el ultimo misil. private float misilRateCounter; //La posicion de la nave. public TGCVector2 Position; //El factor de escalado. private float size; //El bitmap del spritesheet. private CustomBitmap spaceshipBitmap; //La velocidad de la nave. private TGCVector2 speed; //Los distintos sprites de animacion. private List<CustomSprite> sprites; public TGCVector2 spriteSize; //El estado de la nave. private StateEnum state; private TgcD3dInput Input { get; set; } public void Load(CustomBitmap bitmap, TgcD3dInput input) { Input = input; spaceshipBitmap = bitmap; sprites = new List<CustomSprite>(); spriteSize = new TGCVector2(41, 44); size = 2.0f; CustomSprite newSprite; for (var i = 0; i < 3; i++) { newSprite = new CustomSprite(); newSprite.Bitmap = spaceshipBitmap; newSprite.SrcRect = new Rectangle(i * (int)spriteSize.X, 0, (int)spriteSize.X, (int)spriteSize.Y); newSprite.Scaling = new TGCVector2(size, size); sprites.Add(newSprite); } currentSprite = 0; state = StateEnum.Idle; Position = new TGCVector2(100, 100); speed = TGCVector2.Zero; angleToMousePointer = 0; RestartPosition(); GameManager.Instance.userVars.addVar("elapsed"); GameManager.Instance.userVars.addVar("speedX"); GameManager.Instance.userVars.addVar("speedY"); GameManager.Instance.userVars.addVar("PosX"); GameManager.Instance.userVars.addVar("PosY"); GameManager.Instance.userVars.addVar("MousePosX"); GameManager.Instance.userVars.addVar("MousePosY"); GameManager.Instance.userVars.addVar("AngleMouse"); GameManager.Instance.userVars.addVar("Misiles"); } private void fireMissile() { //Si paso el tiempo suficiente if (misilRateCounter > 0.10f) { GameManager.Instance.fireMissile(centerPosition, angle - (float)Math.PI / 2.0f); misilRateCounter = 0; } } public void RestartPosition() { Position.X = GameManager.ScreenWidth / 2; Position.Y = GameManager.ScreenHeight / 2; } public override void Update(float elapsedTime) { //float dirX = 0; float dirY = 0; state = StateEnum.Idle; if (Input.keyDown(Key.A)) { // dirX = -1; // state = StateEnum.Moving; } if (Input.keyDown(Key.D)) { // dirX = 1; // state = StateEnum.Moving; } if (Input.keyDown(Key.W)) { dirY = -1; state = StateEnum.Moving; } if (Input.keyDown(Key.S)) { dirY = 1; state = StateEnum.Moving; } if (Input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT)) { fireMissile(); } if (state == StateEnum.Idle) { currentSprite = 0; } else { currentSprite = contadorAnimacion; if (contadorAnimacion > 1) { contadorAnimacion = 1; } else { contadorAnimacion++; } } //Las constantes const float maxSpeed = 400.0f; const float acceleration = 300.0f; const float deacceleration = 300.0f; //const float Epsilon = 0.2f; var spriteMouseVector = TGCVector2.Zero; var mouseVector = new TGCVector2(Input.Xpos, Input.Ypos); spriteMouseVector = TGCVector2.Subtract(mouseVector, Position + new TGCVector2(spriteSize.X / 2 * size, spriteSize.Y / 2 * size)); if (spriteMouseVector.Length() > 10f) angleToMousePointer = (float)Math.Atan2(spriteMouseVector.Y, spriteMouseVector.X); var MouseXAngle = (float)Math.Cos(angleToMousePointer); var MouseYAngle = (float)Math.Sin(angleToMousePointer); angle = angleToMousePointer + (float)Math.PI / 2.0f; if (dirY == 0) { speed.X -= Math.Sign(speed.X) * deacceleration * elapsedTime; speed.Y -= Math.Sign(speed.Y) * deacceleration * elapsedTime; } if (dirY == -1) { speed.X += acceleration * MouseXAngle * elapsedTime; speed.Y += acceleration * MouseYAngle * elapsedTime; } //Limitar la velocidad if (speed.Length() > maxSpeed) { speed.X = maxSpeed * MouseXAngle; speed.Y = maxSpeed * MouseYAngle; } Position.X += speed.X * elapsedTime; Position.Y += speed.Y * elapsedTime; centerPosition = Position + spriteSize * 0.5f * size; sprites[currentSprite].Position = Position; sprites[currentSprite].Rotation = angle; sprites[currentSprite].RotationCenter = new TGCVector2(spriteSize.X / 2 * size, spriteSize.Y / 2 * size); misilRateCounter += elapsedTime; if (Position.X > GameManager.ScreenWidth + spriteSize.X) Position.X = -spriteSize.X; if (Position.X < -spriteSize.X) Position.X = GameManager.ScreenWidth + spriteSize.X; if (Position.Y > GameManager.ScreenHeight + spriteSize.Y) Position.Y = -spriteSize.Y; if (Position.Y < -spriteSize.Y) Position.Y = GameManager.ScreenHeight + spriteSize.Y; GameManager.Instance.userVars.setValue("elapsed", elapsedTime); GameManager.Instance.userVars.setValue("speedX", speed.X); GameManager.Instance.userVars.setValue("speedY", speed.Y); GameManager.Instance.userVars.setValue("PosX", Position.X); GameManager.Instance.userVars.setValue("PosY", Position.Y); GameManager.Instance.userVars.setValue("MousePosX", Input.Xpos); GameManager.Instance.userVars.setValue("MousePosY", Input.Ypos); GameManager.Instance.userVars.setValue("AngleMouse", angleToMousePointer * 360 / (2 * Math.PI)); } public override void Render(float elapsedTime, Drawer2D drawer) { drawer.DrawSprite(sprites[currentSprite]); } private enum StateEnum { Idle, Moving } } }
//------------------------------------------------------------------------------ // <copyright file="Matrix.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Drawing.Drawing2D { using System.Runtime.InteropServices; using System.Diagnostics; using System; using System.Drawing; using Microsoft.Win32; using System.ComponentModel; using System.Drawing.Internal; /** * Represent a Matrix object */ /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix"]/*' /> /// <devdoc> /// Encapsulates a 3 X 3 affine matrix that /// represents a geometric transform. /// </devdoc> public sealed class Matrix : MarshalByRefObject, IDisposable { internal IntPtr nativeMatrix; /* * Create a new identity matrix */ /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.Matrix"]/*' /> /// <devdoc> /// Initializes a new instance of the <see cref='System.Drawing.Drawing2D.Matrix'/> class. /// </devdoc> public Matrix() { IntPtr matrix = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateMatrix(out matrix); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); this.nativeMatrix = matrix; } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.Matrix1"]/*' /> /// <devdoc> /// <para> /// Initialized a new instance of the <see cref='System.Drawing.Drawing2D.Matrix'/> class with the specified /// elements. /// </para> /// </devdoc> public Matrix(float m11, float m12, float m21, float m22, float dx, float dy) { IntPtr matrix = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateMatrix2(m11, m12, m21, m22, dx, dy, out matrix); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); this.nativeMatrix = matrix; } // float version /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.Matrix2"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.Drawing2D.Matrix'/> class to the geometrical transform /// defined by the specified rectangle and array of points. /// </para> /// </devdoc> public Matrix(RectangleF rect, PointF[] plgpts) { if (plgpts == null) { throw new ArgumentNullException("plgpts"); } if (plgpts.Length != 3) { throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.InvalidParameter); } IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(plgpts); try { IntPtr matrix = IntPtr.Zero; GPRECTF gprectf = new GPRECTF(rect); int status = SafeNativeMethods.Gdip.GdipCreateMatrix3(ref gprectf, new HandleRef(null, buf), out matrix); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } this.nativeMatrix = matrix; } finally { Marshal.FreeHGlobal(buf); } } // int version /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.Matrix3"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.Drawing2D.Matrix'/> class to the geometrical transform /// defined by the specified rectangle and array of points. /// </para> /// </devdoc> public Matrix(Rectangle rect, Point[] plgpts) { if (plgpts == null) { throw new ArgumentNullException("plgpts"); } if (plgpts.Length != 3) { throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.InvalidParameter); } IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(plgpts); try { IntPtr matrix = IntPtr.Zero; GPRECT gprect = new GPRECT(rect); int status = SafeNativeMethods.Gdip.GdipCreateMatrix3I(ref gprect, new HandleRef(null, buf), out matrix); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } this.nativeMatrix = matrix; } finally { Marshal.FreeHGlobal(buf); } } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.Dispose"]/*' /> /// <devdoc> /// Cleans up resources allocated for this /// <see cref='System.Drawing.Drawing2D.Matrix'/>. /// </devdoc> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } void Dispose(bool disposing) { if (nativeMatrix != IntPtr.Zero) { SafeNativeMethods.Gdip.GdipDeleteMatrix(new HandleRef(this, nativeMatrix)); nativeMatrix = IntPtr.Zero; } } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.Finalize"]/*' /> /// <devdoc> /// Cleans up resources allocated for this /// <see cref='System.Drawing.Drawing2D.Matrix'/>. /// </devdoc> ~Matrix() { Dispose(false); } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.Clone"]/*' /> /// <devdoc> /// Creates an exact copy of this <see cref='System.Drawing.Drawing2D.Matrix'/>. /// </devdoc> public Matrix Clone() { IntPtr cloneMatrix = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCloneMatrix(new HandleRef(this, nativeMatrix), out cloneMatrix); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return new Matrix(cloneMatrix); } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.Elements"]/*' /> /// <devdoc> /// Gets an array of floating-point values that /// represent the elements of this <see cref='System.Drawing.Drawing2D.Matrix'/>. /// </devdoc> public float[] Elements { get { float[] m; IntPtr buf = Marshal.AllocHGlobal(6 * 8); // 6 elements x 8 bytes (float) try { int status = SafeNativeMethods.Gdip.GdipGetMatrixElements(new HandleRef(this, nativeMatrix), buf); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } m = new float[6]; Marshal.Copy(buf, m, 0, 6); } finally { Marshal.FreeHGlobal(buf); } return m; } } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.OffsetX"]/*' /> /// <devdoc> /// Gets the x translation value (the dx value, /// or the element in the third row and first column) of this <see cref='System.Drawing.Drawing2D.Matrix'/>. /// </devdoc> public float OffsetX { get { return Elements[4];} } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.OffsetY"]/*' /> /// <devdoc> /// Gets the y translation value (the dy /// value, or the element in the third row and second column) of this <see cref='System.Drawing.Drawing2D.Matrix'/>. /// </devdoc> public float OffsetY { get { return Elements[5];} } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.Reset"]/*' /> /// <devdoc> /// Resets this <see cref='System.Drawing.Drawing2D.Matrix'/> to identity. /// </devdoc> public void Reset() { int status = SafeNativeMethods.Gdip.GdipSetMatrixElements(new HandleRef(this, nativeMatrix), 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.Multiply"]/*' /> /// <devdoc> /// <para> /// Multiplies this <see cref='System.Drawing.Drawing2D.Matrix'/> by the specified <see cref='System.Drawing.Drawing2D.Matrix'/> by prepending the specified <see cref='System.Drawing.Drawing2D.Matrix'/>. /// </para> /// </devdoc> public void Multiply(Matrix matrix) { Multiply(matrix, MatrixOrder.Prepend); } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.Multiply1"]/*' /> /// <devdoc> /// <para> /// Multiplies this <see cref='System.Drawing.Drawing2D.Matrix'/> by the specified <see cref='System.Drawing.Drawing2D.Matrix'/> in the specified order. /// </para> /// </devdoc> public void Multiply(Matrix matrix, MatrixOrder order) { if (matrix == null) { throw new ArgumentNullException("matrix"); } int status = SafeNativeMethods.Gdip.GdipMultiplyMatrix(new HandleRef(this, nativeMatrix), new HandleRef(matrix, matrix.nativeMatrix), order); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.Translate"]/*' /> /// <devdoc> /// <para> /// Applies the specified translation vector to /// the this <see cref='System.Drawing.Drawing2D.Matrix'/> by /// prepending the translation vector. /// </para> /// </devdoc> public void Translate(float offsetX, float offsetY) { Translate(offsetX, offsetY, MatrixOrder.Prepend); } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.Translate1"]/*' /> /// <devdoc> /// <para> /// Applies the specified translation vector to /// the this <see cref='System.Drawing.Drawing2D.Matrix'/> in the specified order. /// </para> /// </devdoc> public void Translate(float offsetX, float offsetY, MatrixOrder order) { int status = SafeNativeMethods.Gdip.GdipTranslateMatrix(new HandleRef(this, nativeMatrix), offsetX, offsetY, order); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.Scale"]/*' /> /// <devdoc> /// Applies the specified scale vector to this /// <see cref='System.Drawing.Drawing2D.Matrix'/> by prepending the scale vector. /// </devdoc> public void Scale(float scaleX, float scaleY) { Scale(scaleX, scaleY, MatrixOrder.Prepend); } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.Scale1"]/*' /> /// <devdoc> /// <para> /// Applies the specified scale vector to this /// <see cref='System.Drawing.Drawing2D.Matrix'/> using the specified order. /// </para> /// </devdoc> public void Scale(float scaleX, float scaleY, MatrixOrder order) { int status = SafeNativeMethods.Gdip.GdipScaleMatrix(new HandleRef(this, nativeMatrix), scaleX, scaleY, order); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.Rotate"]/*' /> /// <devdoc> /// <para> /// Rotates this <see cref='System.Drawing.Drawing2D.Matrix'/> clockwise about the /// origin by the specified angle. /// </para> /// </devdoc> public void Rotate(float angle) { Rotate(angle, MatrixOrder.Prepend); } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.Rotate1"]/*' /> /// <devdoc> /// <para> /// Rotates this <see cref='System.Drawing.Drawing2D.Matrix'/> clockwise about the /// origin by the specified /// angle in the specified order. /// </para> /// </devdoc> public void Rotate(float angle, MatrixOrder order) { int status = SafeNativeMethods.Gdip.GdipRotateMatrix(new HandleRef(this, nativeMatrix), angle, order); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.RotateAt"]/*' /> /// <devdoc> /// <para> /// Applies a clockwise rotation about the /// specified point to this <see cref='System.Drawing.Drawing2D.Matrix'/> by prepending the rotation. /// </para> /// </devdoc> public void RotateAt(float angle, PointF point) { RotateAt(angle, point, MatrixOrder.Prepend); } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.RotateAt1"]/*' /> /// <devdoc> /// <para> /// Applies a clockwise rotation about the specified point /// to this <see cref='System.Drawing.Drawing2D.Matrix'/> in the /// specified order. /// </para> /// </devdoc> public void RotateAt(float angle, PointF point, MatrixOrder order) { int status; // !! TO DO: We cheat with error codes here... if (order == MatrixOrder.Prepend) { status = SafeNativeMethods.Gdip.GdipTranslateMatrix(new HandleRef(this, nativeMatrix), point.X, point.Y, order); status |= SafeNativeMethods.Gdip.GdipRotateMatrix(new HandleRef(this, nativeMatrix), angle, order); status |= SafeNativeMethods.Gdip.GdipTranslateMatrix(new HandleRef(this, nativeMatrix), -point.X, -point.Y, order); } else { status = SafeNativeMethods.Gdip.GdipTranslateMatrix(new HandleRef(this, nativeMatrix), -point.X, -point.Y, order); status |= SafeNativeMethods.Gdip.GdipRotateMatrix(new HandleRef(this, nativeMatrix), angle, order); status |= SafeNativeMethods.Gdip.GdipTranslateMatrix(new HandleRef(this, nativeMatrix), point.X, point.Y, order); } if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.Shear"]/*' /> /// <devdoc> /// Applies the specified shear /// vector to this <see cref='System.Drawing.Drawing2D.Matrix'/> by prepending the shear vector. /// </devdoc> public void Shear(float shearX, float shearY) { int status = SafeNativeMethods.Gdip.GdipShearMatrix(new HandleRef(this, nativeMatrix), shearX, shearY, MatrixOrder.Prepend); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.Shear1"]/*' /> /// <devdoc> /// <para> /// Applies the specified shear /// vector to this <see cref='System.Drawing.Drawing2D.Matrix'/> in the specified order. /// </para> /// </devdoc> public void Shear(float shearX, float shearY, MatrixOrder order) { int status = SafeNativeMethods.Gdip.GdipShearMatrix(new HandleRef(this, nativeMatrix), shearX, shearY, order); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.Invert"]/*' /> /// <devdoc> /// Inverts this <see cref='System.Drawing.Drawing2D.Matrix'/>, if it is /// invertible. /// </devdoc> public void Invert() { int status = SafeNativeMethods.Gdip.GdipInvertMatrix(new HandleRef(this, nativeMatrix)); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } // float version /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.TransformPoints"]/*' /> /// <devdoc> /// <para> /// Applies the geometrical transform this <see cref='System.Drawing.Drawing2D.Matrix'/>represents to an /// array of points. /// </para> /// </devdoc> public void TransformPoints(PointF[] pts) { if (pts == null) throw new ArgumentNullException("pts"); IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(pts); try { int status = SafeNativeMethods.Gdip.GdipTransformMatrixPoints(new HandleRef(this, nativeMatrix), new HandleRef(null, buf), pts.Length); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } PointF[] newPts = SafeNativeMethods.Gdip.ConvertGPPOINTFArrayF(buf, pts.Length); for (int i=0; i<pts.Length; i++) { pts[i] = newPts[i]; } } finally { Marshal.FreeHGlobal(buf); } } // int version /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.TransformPoints1"]/*' /> /// <devdoc> /// <para> /// Applies the geometrical transform this <see cref='System.Drawing.Drawing2D.Matrix'/> represents to an array of points. /// </para> /// </devdoc> public void TransformPoints(Point[] pts) { if (pts == null) throw new ArgumentNullException("pts"); IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(pts); try { int status = SafeNativeMethods.Gdip.GdipTransformMatrixPointsI(new HandleRef(this, nativeMatrix), new HandleRef(null, buf), pts.Length); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } // must do an in-place copy because we only have a reference Point[] newPts = SafeNativeMethods.Gdip.ConvertGPPOINTArray(buf, pts.Length); for (int i=0; i<pts.Length; i++) { pts[i] = newPts[i]; } } finally { Marshal.FreeHGlobal(buf); } } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.TransformVectors"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void TransformVectors(PointF[] pts) { if (pts == null) { throw new ArgumentNullException("pts"); } IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(pts); try { int status = SafeNativeMethods.Gdip.GdipVectorTransformMatrixPoints(new HandleRef(this, nativeMatrix), new HandleRef(null, buf), pts.Length); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } // must do an in-place copy because we only have a reference PointF[] newPts = SafeNativeMethods.Gdip.ConvertGPPOINTFArrayF(buf, pts.Length); for (int i=0; i<pts.Length; i++) { pts[i] = newPts[i]; } } finally { Marshal.FreeHGlobal(buf); } } // int version /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.VectorTransformPoints"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void VectorTransformPoints(Point[] pts) { TransformVectors(pts); } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.TransformVectors1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void TransformVectors(Point[] pts) { if (pts == null) { throw new ArgumentNullException("pts"); } IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(pts); try { int status = SafeNativeMethods.Gdip.GdipVectorTransformMatrixPointsI(new HandleRef(this, nativeMatrix), new HandleRef(null, buf), pts.Length); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } // must do an in-place copy because we only have a reference Point[] newPts = SafeNativeMethods.Gdip.ConvertGPPOINTArray(buf, pts.Length); for (int i=0; i<pts.Length; i++) { pts[i] = newPts[i]; } } finally { Marshal.FreeHGlobal(buf); } } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.IsInvertible"]/*' /> /// <devdoc> /// Gets a value indicating whether this /// <see cref='System.Drawing.Drawing2D.Matrix'/> is invertible. /// </devdoc> public bool IsInvertible { get { int isInvertible; int status = SafeNativeMethods.Gdip.GdipIsMatrixInvertible(new HandleRef(this, nativeMatrix), out isInvertible); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return isInvertible != 0; } } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.IsIdentity"]/*' /> /// <devdoc> /// Gets a value indicating whether this <see cref='System.Drawing.Drawing2D.Matrix'/> is the identity matrix. /// </devdoc> public bool IsIdentity { get { int isIdentity; int status = SafeNativeMethods.Gdip.GdipIsMatrixIdentity(new HandleRef(this, nativeMatrix), out isIdentity); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return isIdentity != 0; } } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.Equals"]/*' /> /// <devdoc> /// <para> /// Tests whether the specified object is a /// <see cref='System.Drawing.Drawing2D.Matrix'/> and is identical to this <see cref='System.Drawing.Drawing2D.Matrix'/>. /// </para> /// </devdoc> public override bool Equals(object obj) { Matrix matrix2 = obj as Matrix; if (matrix2 == null) return false; int isEqual; int status = SafeNativeMethods.Gdip.GdipIsMatrixEqual(new HandleRef(this, nativeMatrix), new HandleRef(matrix2, matrix2.nativeMatrix), out isEqual); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return isEqual != 0; } /// <include file='doc\Matrix.uex' path='docs/doc[@for="Matrix.GetHashCode"]/*' /> /// <devdoc> /// <para> /// Returns a hash code. /// </para> /// </devdoc> public override int GetHashCode() { return base.GetHashCode(); } internal Matrix(IntPtr nativeMatrix) { SetNativeMatrix(nativeMatrix); } internal void SetNativeMatrix(IntPtr nativeMatrix) { this.nativeMatrix = nativeMatrix; } } }
//--------------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // // Description: Implementation of the class Geometry // // History: // //--------------------------------------------------------------------------- using System; using MS.Internal; using MS.Win32.PresentationCore; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Reflection; using System.Collections; using System.Globalization; using System.Security; using System.Windows.Media; using System.Windows.Media.Composition; using System.Windows; using System.Text.RegularExpressions; using System.Windows.Media.Animation; using System.Runtime.InteropServices; using System.Windows.Markup; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; namespace System.Windows.Media { #region Geometry /// <summary> /// This is the base class for all Geometry classes. A geometry has bounds, /// can be used to clip, fill or stroke. /// </summary> [Localizability(LocalizationCategory.None, Readability = Readability.Unreadable)] public abstract partial class Geometry : Animatable, DUCE.IResource { #region Constructors internal Geometry() { } #endregion #region Public properties /// <summary> /// Singleton empty model. /// </summary> public static Geometry Empty { get { return s_empty; } } /// <summary> /// Gets the bounds of this Geometry as an axis-aligned bounding box /// </summary> public virtual Rect Bounds { get { return PathGeometry.GetPathBounds( GetPathGeometryData(), null, // pen Matrix.Identity, StandardFlatteningTolerance, ToleranceType.Absolute, false); // Do not skip non-fillable figures } } /// <summary> /// Standard error tolerance (0.25) used for polygonal approximation of curved segments /// </summary> public static double StandardFlatteningTolerance { get { return c_tolerance; } } #endregion Public properties #region GetRenderBounds /// <summary> /// Returns the axis-aligned bounding rectangle when stroked with a pen. /// </summary> /// <param name="pen">The pen</param> /// <param name="tolerance">The computational error tolerance</param> /// <param name="type">The way the error tolerance will be interpreted - relative or absolute</param> public virtual Rect GetRenderBounds(Pen pen, double tolerance, ToleranceType type) { ReadPreamble(); Matrix matrix = Matrix.Identity; return GetBoundsInternal(pen, matrix, tolerance, type); } /// <summary> /// Returns the axis-aligned bounding rectangle when stroked with a pen. /// </summary> /// <param name="pen">The pen</param> public Rect GetRenderBounds(Pen pen) { ReadPreamble(); Matrix matrix = Matrix.Identity; return GetBoundsInternal(pen, matrix, StandardFlatteningTolerance, ToleranceType.Absolute); } #endregion GetRenderBounds #region Internal Methods /// <summary> /// Used to optimize Visual.ChangeVisualClip. This is not meant /// to be used generically since not all geometries implement /// the method (currently only RectangleGeometry is implemented). /// </summary> internal virtual bool AreClose(Geometry geometry) { return false; } /// <summary> /// Returns the axis-aligned bounding rectangle when stroked with a pen, after applying /// the supplied transform (if non-null). /// </summary> internal virtual Rect GetBoundsInternal(Pen pen, Matrix matrix, double tolerance, ToleranceType type) { if (IsObviouslyEmpty()) { return Rect.Empty; } PathGeometryData pathData = GetPathGeometryData(); return PathGeometry.GetPathBounds( pathData, pen, matrix, tolerance, type, true); /* skip hollows */ } /// <summary> /// Returns the axis-aligned bounding rectangle when stroked with a pen, after applying /// the supplied transform (if non-null). /// </summary> internal Rect GetBoundsInternal(Pen pen, Matrix matrix) { return GetBoundsInternal(pen, matrix, StandardFlatteningTolerance, ToleranceType.Absolute); } /// <SecurityNote> /// Critical - it does an elevation in calling MilUtility_PolygonBounds and is unsafe /// </SecurityNote> [SecurityCritical] internal unsafe static Rect GetBoundsHelper( Pen pen, Matrix *pWorldMatrix, Point* pPoints, byte *pTypes, uint pointCount, uint segmentCount, Matrix *pGeometryMatrix, double tolerance, ToleranceType type, bool fSkipHollows) { MIL_PEN_DATA penData; double[] dashArray = null; // If the pen contributes to the bounds, populate the CMD struct bool fPenContributesToBounds = Pen.ContributesToBounds(pen); if (fPenContributesToBounds) { pen.GetBasicPenData(&penData, out dashArray); } MilMatrix3x2D geometryMatrix; if (pGeometryMatrix != null) { geometryMatrix = CompositionResourceManager.MatrixToMilMatrix3x2D(ref (*pGeometryMatrix)); } Debug.Assert(pWorldMatrix != null); MilMatrix3x2D worldMatrix = CompositionResourceManager.MatrixToMilMatrix3x2D(ref (*pWorldMatrix)); Rect bounds; fixed (double *pDashArray = dashArray) { int hr = MilCoreApi.MilUtility_PolygonBounds( &worldMatrix, (fPenContributesToBounds) ? &penData : null, (dashArray == null) ? null : pDashArray, pPoints, pTypes, pointCount, segmentCount, (pGeometryMatrix == null) ? null : &geometryMatrix, tolerance, type == ToleranceType.Relative, fSkipHollows, &bounds ); if (hr == (int)MILErrors.WGXERR_BADNUMBER) { // When we encounter NaNs in the renderer, we absorb the error and draw // nothing. To be consistent, we report that the geometry has empty bounds. bounds = Rect.Empty; } else { HRESULT.Check(hr); } } return bounds; } internal virtual void TransformPropertyChangedHook(DependencyPropertyChangedEventArgs e) { // Do nothing here -- Overriden by PathGeometry to clear cached bounds. } internal Geometry GetTransformedCopy(Transform transform) { Geometry copy = Clone(); Transform internalTransform = Transform; if (transform != null && !transform.IsIdentity) { if (internalTransform == null || internalTransform.IsIdentity) { copy.Transform = transform; } else { copy.Transform = new MatrixTransform(internalTransform.Value * transform.Value); } } return copy; } #endregion Internal Methods /// <summary> /// ShouldSerializeTransform - this is called by the serializer to determine whether or not to /// serialize the Transform property. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeTransform() { Transform transform = Transform; return transform != null && !(transform.IsIdentity); } #region Public Methods /// <summary> /// Gets the area of this geometry /// <param name="tolerance">The computational error tolerance</param> /// <param name="type">The way the error tolerance will be interpreted - relative or absolute</param> /// </summary> ///<SecurityNote> /// Critical as this calls a method that elevates (MilUtility_GeometryGetArea) /// TreatAsSafe - net effect of this is to calculate the area of a geometry, so it's considered safe. ///</SecurityNote> [SecurityCritical] public virtual double GetArea(double tolerance, ToleranceType type) { ReadPreamble(); if (IsObviouslyEmpty()) { return 0; } PathGeometryData pathData = GetPathGeometryData(); if (pathData.IsEmpty()) { return 0; } double area; unsafe { // Call the core method on the path data fixed (byte* pbPathData = pathData.SerializedData) { Debug.Assert(pbPathData != (byte*)0); int hr = MilCoreApi.MilUtility_GeometryGetArea( pathData.FillRule, pbPathData, pathData.Size, &pathData.Matrix, tolerance, type == ToleranceType.Relative, &area); if (hr == (int)MILErrors.WGXERR_BADNUMBER) { // When we encounter NaNs in the renderer, we absorb the error and draw // nothing. To be consistent, we report that the geometry has 0 area. area = 0.0; } else { HRESULT.Check(hr); } } } return area; } /// <summary> /// Gets the area of this geometry /// </summary> public double GetArea() { return GetArea(StandardFlatteningTolerance, ToleranceType.Absolute); } /// <summary> /// Returns true if this geometry is empty /// </summary> public abstract bool IsEmpty(); /// <summary> /// Returns true if this geometry may have curved segments /// </summary> public abstract bool MayHaveCurves(); #endregion Public Methods #region Hit Testing /// <summary> /// Returns true if point is inside the fill region defined by this geometry. /// </summary> /// <param name="hitPoint">The point tested for containment</param> /// <param name="tolerance">Acceptable margin of error in distance computation</param> /// <param name="type">The way the error tolerance will be interpreted - relative or absolute</param> public bool FillContains(Point hitPoint, double tolerance, ToleranceType type) { return ContainsInternal(null, hitPoint, tolerance, type); } /// <summary> /// Returns true if point is inside the fill region defined by this geometry. /// </summary> /// <param name="hitPoint">The point tested for containment</param> public bool FillContains(Point hitPoint) { return ContainsInternal(null, hitPoint, StandardFlatteningTolerance, ToleranceType.Absolute); } /// <summary> /// Returns true if point is inside the stroke of a pen on this geometry. /// </summary> /// <param name="pen">The pen used to define the stroke</param> /// <param name="hitPoint">The point tested for containment</param> /// <param name="tolerance">Acceptable margin of error in distance computation</param> /// <param name="type">The way the error tolerance will be interpreted - relative or absolute</param> public bool StrokeContains(Pen pen, Point hitPoint, double tolerance, ToleranceType type) { if (pen == null) { return false; } return ContainsInternal(pen, hitPoint, tolerance, type); } /// <summary> /// Returns true if point is inside the stroke of a pen on this geometry. /// </summary> /// <param name="pen">The pen used to define the stroke</param> /// <param name="hitPoint">The point tested for containment</param> /// <param name="tolerance">The computational error tolerance</param> /// <param name="type">The way the error tolerance will be interpreted - relative or absolute</param> /// <SecurityNote> /// Critical - as this does an elevation in calling MilUtility_PathGeometryHitTest. /// TreatAsSafe - as this doesn't expose anything sensitive. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal virtual bool ContainsInternal(Pen pen, Point hitPoint, double tolerance, ToleranceType type) { if (IsObviouslyEmpty()) { return false; } PathGeometryData pathData = GetPathGeometryData(); if (pathData.IsEmpty()) { return false; } bool contains = false; unsafe { MIL_PEN_DATA penData; double[] dashArray = null; // If we have a pen, populate the CMD struct if (pen != null) { pen.GetBasicPenData(&penData, out dashArray); } fixed (byte* pbPathData = pathData.SerializedData) { Debug.Assert(pbPathData != (byte*)0); fixed (double * dashArrayFixed = dashArray) { int hr = MilCoreApi.MilUtility_PathGeometryHitTest( &pathData.Matrix, (pen == null) ? null : &penData, dashArrayFixed, pathData.FillRule, pbPathData, pathData.Size, tolerance, type == ToleranceType.Relative, &hitPoint, out contains); if (hr == (int)MILErrors.WGXERR_BADNUMBER) { // When we encounter NaNs in the renderer, we absorb the error and draw // nothing. To be consistent, we report that the geometry is never hittable. contains = false; } else { HRESULT.Check(hr); } } } } return contains; } /// <summary> /// Helper method to be used by derived implementations of ContainsInternal. /// </summary> /// <SecurityNote> /// Critical - Accepts pointers, does an elevation in calling MilUtility_PolygonHitTest. /// </SecurityNote> [SecurityCritical] internal unsafe bool ContainsInternal(Pen pen, Point hitPoint, double tolerance, ToleranceType type, Point *pPoints, uint pointCount, byte *pTypes, uint typeCount) { bool contains = false; MilMatrix3x2D matrix = CompositionResourceManager.TransformToMilMatrix3x2D(Transform); MIL_PEN_DATA penData; double[] dashArray = null; if (pen != null) { pen.GetBasicPenData(&penData, out dashArray); } fixed (double *dashArrayFixed = dashArray) { int hr = MilCoreApi.MilUtility_PolygonHitTest( &matrix, (pen == null) ? null : &penData, dashArrayFixed, pPoints, pTypes, pointCount, typeCount, tolerance, type == ToleranceType.Relative, &hitPoint, out contains); if (hr == (int)MILErrors.WGXERR_BADNUMBER) { // When we encounter NaNs in the renderer, we absorb the error and draw // nothing. To be consistent, we report that the geometry is never hittable. contains = false; } else { HRESULT.Check(hr); } } return contains; } /// <summary> /// Returns true if point is inside the stroke of a pen on this geometry. /// </summary> /// <param name="pen">The pen used to define the stroke</param> /// <param name="hitPoint">The point tested for containment</param> public bool StrokeContains(Pen pen, Point hitPoint) { return StrokeContains(pen, hitPoint, StandardFlatteningTolerance, ToleranceType.Absolute); } /// <summary> /// Returns true if a given geometry is contained inside this geometry. /// </summary> /// <param name="geometry">The geometry tested for containment</param> /// <param name="tolerance">Acceptable margin of error in distance computation</param> /// <param name="type">The way the error tolerance will be interpreted - relative or absolute</param> public bool FillContains(Geometry geometry, double tolerance, ToleranceType type) { IntersectionDetail detail = FillContainsWithDetail(geometry, tolerance, type); return (detail == IntersectionDetail.FullyContains); } /// <summary> /// Returns true if a given geometry is contained inside this geometry. /// </summary> /// <param name="geometry">The geometry tested for containment</param> public bool FillContains(Geometry geometry) { return FillContains(geometry, StandardFlatteningTolerance, ToleranceType.Absolute); } /// <summary> /// Returns true if a given geometry is inside this geometry. /// <param name="geometry">The geometry to test for containment in this Geometry</param> /// <param name="tolerance">Acceptable margin of error in distance computation</param> /// <param name="type">The way the error tolerance will be interpreted - relative or absolute</param> /// </summary> public virtual IntersectionDetail FillContainsWithDetail(Geometry geometry, double tolerance, ToleranceType type) { ReadPreamble(); if (IsObviouslyEmpty() || geometry == null || geometry.IsObviouslyEmpty()) { return IntersectionDetail.Empty; } return PathGeometry.HitTestWithPathGeometry(this, geometry, tolerance, type); } /// <summary> /// Returns if geometry is inside this geometry. /// <param name="geometry">The geometry to test for containment in this Geometry</param> /// </summary> public IntersectionDetail FillContainsWithDetail(Geometry geometry) { return FillContainsWithDetail(geometry, StandardFlatteningTolerance, ToleranceType.Absolute); } /// <summary> /// Returns if a given geometry is inside the stroke defined by a given pen on this geometry. /// <param name="pen">The pen</param> /// <param name="geometry">The geometry to test for containment in this Geometry</param> /// <param name="tolerance">Acceptable margin of error in distance computation</param> /// <param name="type">The way the error tolerance will be interpreted - relative or absolute</param> /// </summary> public IntersectionDetail StrokeContainsWithDetail(Pen pen, Geometry geometry, double tolerance, ToleranceType type) { if (IsObviouslyEmpty() || geometry == null || geometry.IsObviouslyEmpty() || pen == null) { return IntersectionDetail.Empty; } PathGeometry pathGeometry1 = GetWidenedPathGeometry(pen); return PathGeometry.HitTestWithPathGeometry(pathGeometry1, geometry, tolerance, type); } /// <summary> /// Returns if a given geometry is inside the stroke defined by a given pen on this geometry. /// <param name="pen">The pen</param> /// <param name="geometry">The geometry to test for containment in this Geometry</param> /// </summary> public IntersectionDetail StrokeContainsWithDetail(Pen pen, Geometry geometry) { return StrokeContainsWithDetail(pen, geometry, StandardFlatteningTolerance, ToleranceType.Absolute); } #endregion #region Geometric Flatten /// <summary> /// Approximate this geometry with a polygonal PathGeometry /// </summary> /// <param name="tolerance">The approximation error tolerance</param> /// <param name="type">The way the error tolerance will be interpreted - relative or absolute</param> /// <returns>Returns the polygonal approximation as a PathGeometry.</returns> ///<SecurityNote> /// Critical - calls code that performs an elevation. /// PublicOK - net effect of this code is to create an "flattened" shape from the current one. /// to "flatten" means to approximate with polygons. /// ( in effect creating a different flavor of this shape from this one). /// Considered safe. ///</SecurityNote> [SecurityCritical] public virtual PathGeometry GetFlattenedPathGeometry(double tolerance, ToleranceType type) { ReadPreamble(); if (IsObviouslyEmpty()) { return new PathGeometry(); } PathGeometryData pathData = GetPathGeometryData(); if (pathData.IsEmpty()) { return new PathGeometry(); } PathGeometry resultGeometry = null; unsafe { fixed (byte *pbPathData = pathData.SerializedData) { Debug.Assert(pbPathData != (byte*)0); FillRule fillRule = FillRule.Nonzero; PathGeometry.FigureList list = new PathGeometry.FigureList(); int hr = UnsafeNativeMethods.MilCoreApi.MilUtility_PathGeometryFlatten( &pathData.Matrix, pathData.FillRule, pbPathData, pathData.Size, tolerance, type == ToleranceType.Relative, new PathGeometry.AddFigureToListDelegate(list.AddFigureToList), out fillRule); if (hr == (int)MILErrors.WGXERR_BADNUMBER) { // When we encounter NaNs in the renderer, we absorb the error and draw // nothing. To be consistent, we return an empty geometry. resultGeometry = new PathGeometry(); } else { HRESULT.Check(hr); resultGeometry = new PathGeometry(list.Figures, fillRule, null); } } return resultGeometry; } } /// <summary> /// Approximate this geometry with a polygonal PathGeometry /// </summary> /// <returns>Returns the polygonal approximation as a PathGeometry.</returns> public PathGeometry GetFlattenedPathGeometry() { // Use the default tolerance interpreted as absolute return GetFlattenedPathGeometry(StandardFlatteningTolerance, ToleranceType.Absolute); } #endregion Flatten #region Geometric Widen /// <summary> /// Create the contour of the stroke defined by given pen when it draws this path /// </summary> /// <param name="pen">The pen used for stroking this path</param> /// <param name="tolerance">The computational error tolerance</param> /// <param name="type">The way the error tolerance will be interpreted - relative or absolute</param> /// <returns>Returns the contour as a PathGeometry.</returns> ///<SecurityNote> /// Critical as this calls a method that elevates ( SUC on PathGeometryWiden). /// PublicOK - net effect of this is to create a new PathGeometry "widened" with a new pen. /// To "widen" a path is what we do internally when we draw a path with a pen: we generate the contour of the stroke and then fill it. /// The exposed method returns that contour as a PathGeometry. /// In effect we're creating a different flavor of the current shape from this one. /// /// Considered safe. ///</SecurityNote> [SecurityCritical] public virtual PathGeometry GetWidenedPathGeometry(Pen pen, double tolerance, ToleranceType type) { ReadPreamble(); if (pen == null) { throw new System.ArgumentNullException("pen"); } if (IsObviouslyEmpty()) { return new PathGeometry(); } PathGeometryData pathData = GetPathGeometryData(); if (pathData.IsEmpty()) { return new PathGeometry(); } PathGeometry resultGeometry = null; unsafe { MIL_PEN_DATA penData; double[] dashArray = null; pen.GetBasicPenData(&penData, out dashArray); fixed (byte *pbPathData = pathData.SerializedData) { Debug.Assert(pbPathData != (byte*)0); FillRule fillRule = FillRule.Nonzero; PathGeometry.FigureList list = new PathGeometry.FigureList(); // The handle to the pDashArray, if we have one. // Since the dash array is optional, we may not need to Free it. GCHandle handle = new GCHandle(); // Pin the pDashArray, if we have one. if (dashArray != null) { handle = GCHandle.Alloc(dashArray, GCHandleType.Pinned); } try { int hr = UnsafeNativeMethods.MilCoreApi.MilUtility_PathGeometryWiden( &penData, (dashArray == null) ? null : (double*)handle.AddrOfPinnedObject(), &pathData.Matrix, pathData.FillRule, pbPathData, pathData.Size, tolerance, type == ToleranceType.Relative, new PathGeometry.AddFigureToListDelegate(list.AddFigureToList), out fillRule); if (hr == (int)MILErrors.WGXERR_BADNUMBER) { // When we encounter NaNs in the renderer, we absorb the error and draw // nothing. To be consistent, we return an empty geometry. resultGeometry = new PathGeometry(); } else { HRESULT.Check(hr); resultGeometry = new PathGeometry(list.Figures, fillRule, null); } } finally { if (handle.IsAllocated) { handle.Free(); } } } return resultGeometry; } } /// <summary> /// Create the contour of the stroke defined by given pen when it draws this path /// </summary> /// <param name="pen">The pen used for stroking this path</param> /// <returns>Returns the contour as a PathGeometry.</returns> public PathGeometry GetWidenedPathGeometry(Pen pen) { // Use the default tolerance interpreted as absolute return GetWidenedPathGeometry(pen, StandardFlatteningTolerance, ToleranceType.Absolute); } #endregion Widen #region Combine /// <summary> /// Returns the result of a Boolean combination of two Geometry objects. /// </summary> /// <param name="geometry1">The first Geometry object</param> /// <param name="geometry2">The second Geometry object</param> /// <param name="mode">The mode in which the objects will be combined</param> /// <param name="transform">A transformation to apply to the result, or null</param> /// <param name="tolerance">The computational error tolerance</param> /// <param name="type">The way the error tolerance will be interpreted - relative or absolute</param> public static PathGeometry Combine( Geometry geometry1, Geometry geometry2, GeometryCombineMode mode, Transform transform, double tolerance, ToleranceType type) { return PathGeometry.InternalCombine(geometry1, geometry2, mode, transform, tolerance, type); } /// <summary> /// Returns the result of a Boolean combination of two Geometry objects. /// </summary> /// <param name="geometry1">The first Geometry object</param> /// <param name="geometry2">The second Geometry object</param> /// <param name="mode">The mode in which the objects will be combined</param> /// <param name="transform">A transformation to apply to the result, or null</param> public static PathGeometry Combine( Geometry geometry1, Geometry geometry2, GeometryCombineMode mode, Transform transform) { return PathGeometry.InternalCombine( geometry1, geometry2, mode, transform, Geometry.StandardFlatteningTolerance, ToleranceType.Absolute); } #endregion Combine #region Outline /// <summary> /// Get a simplified contour of the filled region of this PathGeometry /// </summary> /// <param name="tolerance">The computational error tolerance</param> /// <param name="type">The way the error tolerance will be interpreted - relative or absolute</param> /// <returns>Returns an equivalent geometry, properly oriented with no self-intersections.</returns> /// <SecurityNote> /// Critical - as this calls GetGlyphs() which is critical. /// Safe - as this doesn't expose font information but just gives out a Geometry. /// </SecurityNote> [SecurityCritical] public virtual PathGeometry GetOutlinedPathGeometry(double tolerance, ToleranceType type) { ReadPreamble(); if (IsObviouslyEmpty()) { return new PathGeometry(); } PathGeometryData pathData = GetPathGeometryData(); if (pathData.IsEmpty()) { return new PathGeometry(); } PathGeometry resultGeometry = null; unsafe { fixed (byte* pbPathData = pathData.SerializedData) { Invariant.Assert(pbPathData != (byte*)0); FillRule fillRule = FillRule.Nonzero; PathGeometry.FigureList list = new PathGeometry.FigureList(); int hr = UnsafeNativeMethods.MilCoreApi.MilUtility_PathGeometryOutline( &pathData.Matrix, pathData.FillRule, pbPathData, pathData.Size, tolerance, type == ToleranceType.Relative, new PathGeometry.AddFigureToListDelegate(list.AddFigureToList), out fillRule); if (hr == (int)MILErrors.WGXERR_BADNUMBER) { // When we encounter NaNs in the renderer, we absorb the error and draw // nothing. To be consistent, we return an empty geometry. resultGeometry = new PathGeometry(); } else { HRESULT.Check(hr); resultGeometry = new PathGeometry(list.Figures, fillRule, null); } } } return resultGeometry; } /// <summary> /// Get a simplified contour of the filled region of this PathGeometry /// </summary> /// <returns>Returns an equivalent geometry, properly oriented with no self-intersections.</returns> public PathGeometry GetOutlinedPathGeometry() { return GetOutlinedPathGeometry(StandardFlatteningTolerance, ToleranceType.Absolute); } #endregion Outline #region Internal internal abstract PathGeometry GetAsPathGeometry(); /// <summary> /// GetPathGeometryData - returns a struct which contains this Geometry represented /// as a path geometry's serialized format. /// </summary> internal abstract PathGeometryData GetPathGeometryData(); internal PathFigureCollection GetPathFigureCollection() { return GetTransformedFigureCollection(null); } // Get the combination of the internal transform with a given transform. // Return true if the result is nontrivial. internal Matrix GetCombinedMatrix(Transform transform) { Matrix matrix = Matrix.Identity; Transform internalTransform = Transform; if (internalTransform != null && !internalTransform.IsIdentity) { matrix = internalTransform.Value; if (transform != null && !transform.IsIdentity) { matrix *= transform.Value; } } else if (transform != null && !transform.IsIdentity) { matrix = transform.Value; } return matrix; } internal abstract PathFigureCollection GetTransformedFigureCollection(Transform transform); // This method is used for eliminating unnecessary work when the geometry is obviously empty. // For most Geometry types the definite IsEmpty() query is just as cheap. The exceptions will // be CombinedGeometry and GeometryGroup. internal virtual bool IsObviouslyEmpty() { return IsEmpty(); } /// <summary> /// Can serialize "this" to a string /// </summary> internal virtual bool CanSerializeToString() { return false; } internal struct PathGeometryData { ///<SecurityNote> /// Critical as this has an unsafe block. /// TreatAsSafe - net effect is simply to read data. ///</SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal bool IsEmpty() { if ((SerializedData == null) || (SerializedData.Length <= 0)) { return true; } unsafe { fixed (byte *pbPathData = SerializedData) { MIL_PATHGEOMETRY* pPathGeometry = (MIL_PATHGEOMETRY*)pbPathData; return pPathGeometry->FigureCount <= 0; } } } internal FillRule FillRule; internal MilMatrix3x2D Matrix; internal byte[] SerializedData; /// <SecurityNote> /// Critical: Manipulates unsafe code /// TreatAsSafe - net effect is simply to read data. /// </SecurityNote> internal uint Size { [SecurityCritical, SecurityTreatAsSafe] get { if ((SerializedData == null) || (SerializedData.Length <= 0)) { return 0; } unsafe { fixed (byte *pbPathData = SerializedData) { MIL_PATHGEOMETRY* pPathGeometryData = (MIL_PATHGEOMETRY*)pbPathData; uint size = pPathGeometryData == null ? 0 : pPathGeometryData->Size; Invariant.Assert(size <= (uint)SerializedData.Length); return size; } } } } } internal static PathGeometryData GetEmptyPathGeometryData() { return s_emptyPathGeometryData; } #endregion Internal #region Private ///<SecurityNote> /// Critical as this has an unsafe block. /// TreatAsSafe - This allocates a buffer locally and writes to it. ///</SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private static PathGeometryData MakeEmptyPathGeometryData() { PathGeometryData data = new PathGeometryData(); data.FillRule = FillRule.EvenOdd; data.Matrix = CompositionResourceManager.MatrixToMilMatrix3x2D(Matrix.Identity); unsafe { int size = sizeof(MIL_PATHGEOMETRY); data.SerializedData = new byte[size]; fixed (byte *pbData = data.SerializedData) { MIL_PATHGEOMETRY *pPathGeometry = (MIL_PATHGEOMETRY*)pbData; // implicitly set pPathGeometry->Flags = 0; pPathGeometry->FigureCount = 0; pPathGeometry->Size = (UInt32)size; } } return data; } private static Geometry MakeEmptyGeometry() { Geometry empty = new StreamGeometry(); empty.Freeze(); return empty; } private const double c_tolerance = 0.25; private static Geometry s_empty = MakeEmptyGeometry(); private static PathGeometryData s_emptyPathGeometryData = MakeEmptyPathGeometryData(); #endregion Private } #endregion }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace HomesideHeroes.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// ZipEntry.cs // // Copyright (c) 2006, 2007, 2008 Microsoft Corporation. All rights reserved. // // Part of an implementation of a zipfile class library. // See the file ZipFile.cs for the license and for further information. // // Tue, 27 Mar 2007 15:30 using System; namespace Argus.IO.Compression { /// <summary> /// Represents a single entry in a ZipFile. Typically, applications /// get a ZipEntry by enumerating the entries within a ZipFile. /// </summary> public class ZipEntry { private ZipEntry() { } /// <summary> /// The time and date at which the file indicated by the ZipEntry was last modified. /// </summary> public DateTime LastModified { get { return _LastModified; } } /// <summary> /// When this is set, this class trims the volume (eg C:\) from any /// fully-qualified pathname on the ZipEntry, /// before writing the ZipEntry into the ZipFile. This flag affects only /// zip creation. /// </summary> public bool TrimVolumeFromFullyQualifiedPaths { get { return _TrimVolumeFromFullyQualifiedPaths; } set { _TrimVolumeFromFullyQualifiedPaths = value; } } /// <summary> /// The name of the filesystem file, referred to by the ZipEntry. /// This may be different than the path used in the archive itself. /// </summary> public string LocalFileName { get { return _LocalFileName; } } /// <summary> /// The name of the file contained in the ZipEntry. /// When writing a zip, this path has backslashes replaced with /// forward slashes, according to the zip spec, for compatibility /// with Unix and Amiga. /// </summary> public string FileName { get { return _FileNameInArchive; } } /// <summary> /// The version of the zip engine needed to read the ZipEntry. This is usually 0x14. /// </summary> public Int16 VersionNeeded { get { return _VersionNeeded; } } /// <summary> /// The comment attached to the ZipEntry. /// </summary> public string Comment { get { return _Comment; } set { _Comment= value; } } /// <summary> /// a bitfield as defined in the zip spec. /// </summary> public Int16 BitField { get { return _BitField; } } /// <summary> /// The compression method employed for this ZipEntry. 0x08 = Deflate. 0x00 = Store (no compression). /// </summary> public Int16 CompressionMethod { get { return _CompressionMethod; } } /// <summary> /// The compressed size of the file, in bytes, within the zip archive. /// </summary> public Int32 CompressedSize { get { return _CompressedSize; } } /// <summary> /// The size of the file, in bytes, before compression, or after extraction. /// </summary> public Int32 UncompressedSize { get { return _UncompressedSize; } } /// <summary> /// The ratio of compressed size to uncompressed size. /// </summary> public Double CompressionRatio { get { // this may return NaN return 100 * (1.0 - (1.0 * CompressedSize) / (1.0 * UncompressedSize)); } } /// <summary> /// True if the entry is a directory (not a file). /// This is a readonly property on the entry. /// </summary> public bool IsDirectory { get { return _IsDirectory; } } /// <summary> /// Specifies that the extraction should overwrite any existing files. /// This applies only when calling an Extract method. /// </summary> public bool OverwriteOnExtract { get { return _OverwriteOnExtract; } set { _OverwriteOnExtract = value; } } private byte[] _FileData { get { if (__filedata == null) { } return __filedata; } } private System.IO.Compression.DeflateStream CompressedStream { get { if (_CompressedStream == null) { // we read from the underlying memory stream after data is written to the compressed stream _UnderlyingMemoryStream = new System.IO.MemoryStream(); bool LeaveUnderlyingStreamOpen = true; // we write to the compressed stream, and compression happens as we write. _CompressedStream = new System.IO.Compression.DeflateStream(_UnderlyingMemoryStream, System.IO.Compression.CompressionMode.Compress, LeaveUnderlyingStreamOpen); } return _CompressedStream; } } internal byte[] Header { get { return _header; } } private static bool ReadHeader(System.IO.Stream s, ZipEntry ze) { int signature = Argus.IO.Compression.Shared.ReadSignature(s); // Return false if this is not a local file header signature. if (ZipEntry.IsNotValidSig(signature)) { s.Seek(-4, System.IO.SeekOrigin.Current); // unread the signature // Getting "not a ZipEntry signature" is not always wrong or an error. // This can happen when walking through a zipfile. After the last compressed entry, // we expect to read a ZipDirEntry signature. When we get this is how we // know we've reached the end of the compressed entries. if (ZipDirEntry.IsNotValidSig(signature)) { throw new Exception(String.Format(" ZipEntry::Read(): Bad signature ({0:X8}) at position 0x{1:X8}", signature, s.Position)); } return false; } byte[] block = new byte[26]; int n = s.Read(block, 0, block.Length); if (n != block.Length) return false; int i = 0; ze._VersionNeeded = (short)(block[i++] + block[i++] * 256); ze._BitField = (short)(block[i++] + block[i++] * 256); ze._CompressionMethod = (short)(block[i++] + block[i++] * 256); ze._LastModDateTime = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256; // the PKZIP spec says that if bit 3 is set (0x0008), then the CRC, Compressed size, and uncompressed size // come directly after the file data. The only way to find it is to scan the zip archive for the signature of // the Data Descriptor, and presume that that signature does not appear in the (compressed) data of the compressed file. if ((ze._BitField & 0x0008) != 0x0008) { ze._Crc32 = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256; ze._CompressedSize = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256; ze._UncompressedSize = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256; } else { // the CRC, compressed size, and uncompressed size are stored later in the stream. // here, we advance the pointer. i += 12; } Int16 filenameLength = (short)(block[i++] + block[i++] * 256); Int16 extraFieldLength = (short)(block[i++] + block[i++] * 256); block = new byte[filenameLength]; n = s.Read(block, 0, block.Length); ze._FileNameInArchive = Argus.IO.Compression.Shared.StringFromBuffer(block, 0, block.Length); // when creating an entry by reading, the LocalFileName is the same as the FileNameInArchivre ze._LocalFileName = ze._FileNameInArchive; ze._Extra = new byte[extraFieldLength]; n = s.Read(ze._Extra, 0, ze._Extra.Length); // transform the time data into something usable ze._LastModified = Argus.IO.Compression.Shared.PackedToDateTime(ze._LastModDateTime); // actually get the compressed size and CRC if necessary if ((ze._BitField & 0x0008) == 0x0008) { long posn = s.Position; long SizeOfDataRead = Argus.IO.Compression.Shared.FindSignature(s, ZipConstants.ZipEntryDataDescriptorSignature); if (SizeOfDataRead == -1) return false; // read 3x 4-byte fields (CRC, Compressed Size, Uncompressed Size) block = new byte[12]; n = s.Read(block, 0, block.Length); if (n != 12) return false; i = 0; ze._Crc32 = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256; ze._CompressedSize = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256; ze._UncompressedSize = block[i++] + block[i++] * 256 + block[i++] * 256 * 256 + block[i++] * 256 * 256 * 256; if (SizeOfDataRead != ze._CompressedSize) throw new Exception("Data format error (bit 3 is set)"); // seek back to previous position, to read file data s.Seek(posn, System.IO.SeekOrigin.Begin); } return true; } private static bool IsNotValidSig(int signature) { return (signature != ZipConstants.ZipEntrySignature); } /// <summary> /// Reads one ZipEntry from the given stream. /// </summary> /// <param name="s">the stream to read from.</param> /// <returns>the ZipEntry read from the stream.</returns> internal static ZipEntry Read(System.IO.Stream s) { ZipEntry entry = new ZipEntry(); if (!ReadHeader(s, entry)) return null; entry.__filedata = new byte[entry.CompressedSize]; int n = s.Read(entry._FileData, 0, entry._FileData.Length); if (n != entry._FileData.Length) { throw new Exception("badly formatted zip file."); } // finally, seek past the (already read) Data descriptor if necessary if ((entry._BitField & 0x0008) == 0x0008) { s.Seek(16, System.IO.SeekOrigin.Current); } return entry; } internal static ZipEntry Create(String filename) { return ZipEntry.Create(filename, null); } internal static ZipEntry Create(String filename, string DirectoryPathInArchive) { ZipEntry entry = new ZipEntry(); entry._LocalFileName = filename; // may include a path if (DirectoryPathInArchive == null) entry._FileNameInArchive = filename; else { // explicitly specify a pathname for this file entry._FileNameInArchive = System.IO.Path.Combine(DirectoryPathInArchive, System.IO.Path.GetFileName(filename)); } entry._LastModified = System.IO.File.GetLastWriteTime(filename); // adjust the time if the .NET BCL thinks it is in DST. // see the note elsewhere in this file for more info. if (entry._LastModified.IsDaylightSavingTime()) { System.DateTime AdjustedTime = entry._LastModified - new System.TimeSpan(1, 0, 0); entry._LastModDateTime = Argus.IO.Compression.Shared.DateTimeToPacked(AdjustedTime); } else entry._LastModDateTime = Argus.IO.Compression.Shared.DateTimeToPacked(entry._LastModified); // we don't actually slurp in the file until the caller invokes Write on this entry. return entry; } /// <summary> /// Extract the entry to the filesystem, starting at the current working directory. /// </summary> /// /// <overloads>This method has five overloads.</overloads> /// /// <remarks> /// <para> /// The last modified time of the created file may be adjusted /// during extraction to compensate /// for differences in how the .NET Base Class Library deals /// with daylight saving time (DST) versus how the Windows /// filesystem deals with daylight saving time. /// See http://blogs.msdn.com/oldnewthing/archive/2003/10/24/55413.aspx for more context. ///</para> /// <para> /// In a nutshell: Daylight savings time rules change regularly. In /// 2007, for example, the inception week of DST changed. In 1977, /// DST was in place all year round. in 1945, likewise. And so on. /// Win32 does not attempt to guess which time zone rules were in /// effect at the time in question. It will render a time as /// "standard time" and allow the app to change to DST as necessary. /// .NET makes a different choice. ///</para> /// <para> /// Compare the output of FileInfo.LastWriteTime.ToString("f") with /// what you see in the property sheet for a file that was last /// written to on the other side of the DST transition. For example, /// suppose the file was last modified on October 17, during DST but /// DST is not currently in effect. Explorer's file properties /// reports Thursday, October 17, 2003, 8:45:38 AM, but .NETs /// FileInfo reports Thursday, October 17, 2003, 9:45 AM. ///</para> /// <para> /// Win32 says, "Thursday, October 17, 2002 8:45:38 AM PST". Note: /// Pacific STANDARD Time. Even though October 17 of that year /// occurred during Pacific Daylight Time, Win32 displays the time as /// standard time because that's what time it is NOW. ///</para> /// <para> /// .NET BCL assumes that the current DST rules were in place at the /// time in question. So, .NET says, "Well, if the rules in effect /// now were also in effect on October 17, 2003, then that would be /// daylight time" so it displays "Thursday, October 17, 2003, 9:45 /// AM PDT" - daylight time. ///</para> /// <para> /// So .NET gives a value which is more intuitively correct, but is /// also potentially incorrect, and which is not invertible. Win32 /// gives a value which is intuitively incorrect, but is strictly /// correct. ///</para> /// <para> /// With this adjustment, I add one hour to the tweaked .NET time, if /// necessary. That is to say, if the time in question had occurred /// in what the .NET BCL assumed to be DST (an assumption that may be /// wrong given the constantly changing DST rules). /// </para> /// </remarks> public void Extract() { Extract("."); } /// <summary> /// Extract the entry to a file in the filesystem, potentially overwriting /// any existing file. /// </summary> /// <remarks> /// <para> /// See the remarks on the non-parameterized version of the extract() method, /// for information on the last modified time of the created file. /// </para> /// </remarks> /// <param name="WantOverwrite">true if the caller wants to overwrite an existing file by the same name in the filesystem.</param> public void Extract(bool WantOverwrite) { Extract(".", WantOverwrite); } /// <summary> /// Extracts the entry to the specified stream. /// For example, the caller could specify Console.Out, or a MemoryStream. /// </summary> /// <param name="s">the stream to which the entry should be extracted. </param> public void Extract(System.IO.Stream s) { Extract(null, s); } /// <summary> /// Extract the entry to the filesystem, starting at the specified base directory. /// </summary> /// <para> /// See the remarks on the non-parameterized version of the extract() method, /// for information on the last modified time of the created file. /// </para> /// <param name="BaseDirectory">the pathname of the base directory</param> public void Extract(string BaseDirectory) { Extract(BaseDirectory, null); } /// <summary> /// Extract the entry to the filesystem, starting at the specified base directory, /// and potentially overwriting existing files in the filesystem. /// </summary> /// <para> /// See the remarks on the non-parameterized version of the extract() method, /// for information on the last modified time of the created file. /// </para> /// <param name="BaseDirectory">the pathname of the base directory</param> /// <param name="Overwrite">If true, overwrite any existing files if necessary upon extraction.</param> public void Extract(string BaseDirectory, bool Overwrite) { OverwriteOnExtract = Overwrite; Extract(BaseDirectory, null); } // pass in either basedir or s, but not both. // In other words, you can extract to a stream or to a directory, but not both! private void Extract(string basedir, System.IO.Stream s) { string TargetFile = null; if (basedir != null) { TargetFile = System.IO.Path.Combine(basedir, FileName); // check if a directory if ((IsDirectory) || (FileName.EndsWith("/"))) { if (!System.IO.Directory.Exists(TargetFile)) System.IO.Directory.CreateDirectory(TargetFile); return; } } else if (s != null) { if ((IsDirectory) || (FileName.EndsWith("/"))) // extract a directory to streamwriter? nothing to do! return; } else throw new Exception("Invalid input."); using (System.IO.MemoryStream memstream = new System.IO.MemoryStream(_FileData)) { System.IO.Stream input = null; try { if (CompressedSize == UncompressedSize) { // the System.IO.Compression.DeflateStream class does not handle uncompressed data. // so if an entry is not compressed, then we just translate the bytes directly. input = memstream; } else { input = new System.IO.Compression.DeflateStream(memstream, System.IO.Compression.CompressionMode.Decompress); } if (TargetFile != null) { // ensure the target path exists if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(TargetFile))) { System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(TargetFile)); } } System.IO.Stream output = null; try { if (TargetFile != null) { if ((OverwriteOnExtract) && (System.IO.File.Exists(TargetFile))) { System.IO.File.Delete(TargetFile); } output = new System.IO.FileStream(TargetFile, System.IO.FileMode.CreateNew); } else output = s; byte[] bytes = new byte[4096]; int n; if (_Debug) { Console.WriteLine("{0}: _FileData.Length= {1}", TargetFile, _FileData.Length); Console.WriteLine("{0}: memstream.Position: {1}", TargetFile, memstream.Position); n = _FileData.Length; if (n > 1000) { n = 500; Console.WriteLine("{0}: truncating dump from {1} to {2} bytes...", TargetFile, _FileData.Length, n); } for (int j = 0; j < n; j += 2) { if ((j > 0) && (j % 40 == 0)) System.Console.WriteLine(); System.Console.Write(" {0:X2}", _FileData[j]); if (j + 1 < n) System.Console.Write("{0:X2}", _FileData[j + 1]); } System.Console.WriteLine("\n"); } n = 1; // anything non-zero while (n != 0) { if (_Debug) Console.WriteLine("{0}: about to read...", TargetFile); n = input.Read(bytes, 0, bytes.Length); if (_Debug) Console.WriteLine("{0}: got {1} bytes", TargetFile, n); if (n > 0) { if (_Debug) Console.WriteLine("{0}: about to write...", TargetFile); output.Write(bytes, 0, n); } } } finally { // we only close the output stream if we opened it. if ((output != null) && (TargetFile != null)) { output.Close(); output.Dispose(); } } if (TargetFile != null) { // We may have to adjust the last modified time to compensate // for differences in how the .NET Base Class Library deals // with daylight saving time (DST) versus how the Windows // filesystem deals with daylight saving time. See // http://blogs.msdn.com/oldnewthing/archive/2003/10/24/55413.aspx for some context. // in a nutshell: Daylight savings time rules change regularly. In // 2007, for example, the inception week of DST changed. In 1977, // DST was in place all year round. in 1945, likewise. And so on. // Win32 does not attempt to guess which time zone rules were in // effect at the time in question. It will render a time as // "standard time" and allow the app to change to DST as necessary. // .NET makes a different choice. // ------------------------------------------------------- // Compare the output of FileInfo.LastWriteTime.ToString("f") with // what you see in the property sheet for a file that was last // written to on the other side of the DST transition. For example, // suppose the file was last modified on October 17, during DST but // DST is not currently in effect. Explorer's file properties // reports Thursday, October 17, 2003, 8:45:38 AM, but .NETs // FileInfo reports Thursday, October 17, 2003, 9:45 AM. // Win32 says, "Thursday, October 17, 2002 8:45:38 AM PST". Note: // Pacific STANDARD Time. Even though October 17 of that year // occurred during Pacific Daylight Time, Win32 displays the time as // standard time because that's what time it is NOW. // .NET BCL assumes that the current DST rules were in place at the // time in question. So, .NET says, "Well, if the rules in effect // now were also in effect on October 17, 2003, then that would be // daylight time" so it displays "Thursday, October 17, 2003, 9:45 // AM PDT" - daylight time. // So .NET gives a value which is more intuitively correct, but is // also potentially incorrect, and which is not invertible. Win32 // gives a value which is intuitively incorrect, but is strictly // correct. // ------------------------------------------------------- // With this adjustment, I add one hour to the tweaked .NET time, if // necessary. That is to say, if the time in question had occurred // in what the .NET BCL assumed to be DST (an assumption that may be // wrong given the constantly changing DST rules). if (LastModified.IsDaylightSavingTime()) { DateTime AdjustedLastModified = LastModified + new System.TimeSpan(1, 0, 0); System.IO.File.SetLastWriteTime(TargetFile, AdjustedLastModified); } else System.IO.File.SetLastWriteTime(TargetFile, LastModified); } } finally { // we only close the output stream if we opened it. // we cannot use using() here because in some cases we do not want to Dispose the stream! if ((input != null) && (input != memstream)) { input.Close(); input.Dispose(); } } } } internal void MarkAsDirectory() { _IsDirectory = true; } internal void WriteCentralDirectoryEntry(System.IO.Stream s) { byte[] bytes = new byte[4096]; int i = 0; // signature bytes[i++] = (byte)(ZipConstants.ZipDirEntrySignature & 0x000000FF); bytes[i++] = (byte)((ZipConstants.ZipDirEntrySignature & 0x0000FF00) >> 8); bytes[i++] = (byte)((ZipConstants.ZipDirEntrySignature & 0x00FF0000) >> 16); bytes[i++] = (byte)((ZipConstants.ZipDirEntrySignature & 0xFF000000) >> 24); // Version Made By bytes[i++] = Header[4]; bytes[i++] = Header[5]; // Version Needed, Bitfield, compression method, lastmod, // crc, compressed and uncompressed sizes, filename length and extra field length - // are all the same as the local file header. So just copy them int j = 0; for (j = 0; j < 26; j++) bytes[i + j] = Header[4 + j]; i += j; // positioned at next available byte int commentLength = 0; // File (entry) Comment Length if ((Comment == null) || (Comment.Length == 0)) { // no comment! bytes[i++] = (byte)0; bytes[i++] = (byte)0; } else { commentLength = Comment.Length; // the size of our buffer defines the max length of the comment we can write if (commentLength + i > bytes.Length) commentLength = bytes.Length - i; bytes[i++] = (byte)(commentLength & 0x00FF); bytes[i++] = (byte)((commentLength & 0xFF00) >> 8); } // Disk number start bytes[i++] = 0; bytes[i++] = 0; // internal file attrs bytes[i++] = (byte) ((IsDirectory)?0:1); bytes[i++] = 0; // external file attrs bytes[i++] = (byte)((IsDirectory) ? 0x10 : 0x20); bytes[i++] = 0; bytes[i++] = 0xb6; // ?? not sure, this might also be zero bytes[i++] = 0x81; // ?? ditto // relative offset of local header (I think this can be zero) bytes[i++] = (byte)(_RelativeOffsetOfHeader & 0x000000FF); bytes[i++] = (byte)((_RelativeOffsetOfHeader & 0x0000FF00) >> 8); bytes[i++] = (byte)((_RelativeOffsetOfHeader & 0x00FF0000) >> 16); bytes[i++] = (byte)((_RelativeOffsetOfHeader & 0xFF000000) >> 24); if (_Debug) System.Console.WriteLine("\ninserting filename into CDS: (length= {0})", Header.Length - 30); // actual filename (starts at offset 34 in header) for (j = 0; j < Header.Length - 30; j++) { bytes[i + j] = Header[30 + j]; if (_Debug) System.Console.Write(" {0:X2}", bytes[i + j]); } if (_Debug) System.Console.WriteLine(); i += j; // "Extra field" // in this library, it is always nothing // file (entry) comment if (commentLength != 0) { char[] c = Comment.ToCharArray(); // now actually write the comment itself into the byte buffer for (j = 0; (j < commentLength) && (i + j < bytes.Length); j++) { bytes[i + j] = System.BitConverter.GetBytes(c[j])[0]; } i += j; } s.Write(bytes, 0, i); } private void WriteHeader(System.IO.Stream s, byte[] bytes) { // write the header info int i = 0; // signature bytes[i++] = (byte)(ZipConstants.ZipEntrySignature & 0x000000FF); bytes[i++] = (byte)((ZipConstants.ZipEntrySignature & 0x0000FF00) >> 8); bytes[i++] = (byte)((ZipConstants.ZipEntrySignature & 0x00FF0000) >> 16); bytes[i++] = (byte)((ZipConstants.ZipEntrySignature & 0xFF000000) >> 24); // version needed Int16 FixedVersionNeeded = 0x14; // from examining existing zip files bytes[i++] = (byte)(FixedVersionNeeded & 0x00FF); bytes[i++] = (byte)((FixedVersionNeeded & 0xFF00) >> 8); // bitfield Int16 BitField = 0x00; // from examining existing zip files bytes[i++] = (byte)(BitField & 0x00FF); bytes[i++] = (byte)((BitField & 0xFF00) >> 8); Int16 CompressionMethod = 0x00; // 0x08 = Deflate, 0x00 == No Compression // compression for directories = 0x00 (No Compression) if (!IsDirectory) { CompressionMethod = 0x08; // CRC32 (Int32) if (_FileData != null) { // If we have FileData, that means we've read this entry from an // existing zip archive. We must just copy the existing file data, // CRC, compressed size, and uncompressed size // over to the new (updated) archive. } else { // special case zero-length files System.IO.FileInfo fi = new System.IO.FileInfo(LocalFileName); if (fi.Length == 0) { CompressionMethod = 0x00; _UncompressedSize = 0; _CompressedSize = 0; _Crc32 = 0; } else { // Read in the data from the file in the filesystem, compress it, and // calculate a CRC on it as we read. CRC32 crc32 = new CRC32(); using (System.IO.Stream input = System.IO.File.OpenRead(LocalFileName)) { UInt32 crc = crc32.GetCrc32AndCopy(input, CompressedStream); _Crc32 = (Int32)crc; } CompressedStream.Close(); // to get the footer bytes written to the underlying stream _CompressedStream = null; _UncompressedSize = crc32.TotalBytesRead; _CompressedSize = (Int32)_UnderlyingMemoryStream.Length; // It is possible that applying this stream compression on a previously compressed // file will actually increase the size of the data. In that case, we back-off // and just store the uncompressed (really, already compressed) data. // We need to recompute the CRC, and point to the right data. if (_CompressedSize > _UncompressedSize) { using (System.IO.Stream input = System.IO.File.OpenRead(LocalFileName)) { _UnderlyingMemoryStream = new System.IO.MemoryStream(); UInt32 crc = crc32.GetCrc32AndCopy(input, _UnderlyingMemoryStream); _Crc32 = (Int32)crc; } _UncompressedSize = crc32.TotalBytesRead; _CompressedSize = (Int32)_UnderlyingMemoryStream.Length; if (_CompressedSize != _UncompressedSize) throw new Exception("No compression but unequal stream lengths!"); CompressionMethod = 0x00; } } } } // compression method bytes[i++] = (byte)(CompressionMethod & 0x00FF); bytes[i++] = (byte)((CompressionMethod & 0xFF00) >> 8); // LastMod bytes[i++] = (byte)(_LastModDateTime & 0x000000FF); bytes[i++] = (byte)((_LastModDateTime & 0x0000FF00) >> 8); bytes[i++] = (byte)((_LastModDateTime & 0x00FF0000) >> 16); bytes[i++] = (byte)((_LastModDateTime & 0xFF000000) >> 24); // calculated above bytes[i++] = (byte)(_Crc32 & 0x000000FF); bytes[i++] = (byte)((_Crc32 & 0x0000FF00) >> 8); bytes[i++] = (byte)((_Crc32 & 0x00FF0000) >> 16); bytes[i++] = (byte)((_Crc32 & 0xFF000000) >> 24); // CompressedSize (Int32) bytes[i++] = (byte)(_CompressedSize & 0x000000FF); bytes[i++] = (byte)((_CompressedSize & 0x0000FF00) >> 8); bytes[i++] = (byte)((_CompressedSize & 0x00FF0000) >> 16); bytes[i++] = (byte)((_CompressedSize & 0xFF000000) >> 24); // UncompressedSize (Int32) if (_Debug) System.Console.WriteLine("Uncompressed Size: {0}", _UncompressedSize); bytes[i++] = (byte)(_UncompressedSize & 0x000000FF); bytes[i++] = (byte)((_UncompressedSize & 0x0000FF00) >> 8); bytes[i++] = (byte)((_UncompressedSize & 0x00FF0000) >> 16); bytes[i++] = (byte)((_UncompressedSize & 0xFF000000) >> 24); // filename length (Int16) Int16 filenameLength = (Int16)FileName.Length; // see note below about TrimVolumeFromFullyQualifiedPaths. if ((TrimVolumeFromFullyQualifiedPaths) && (FileName[1] == ':') && (FileName[2] == '\\')) filenameLength -= 3; // apply upper bound to the length if (filenameLength + i > bytes.Length) filenameLength = (Int16)(bytes.Length - (Int16)i); bytes[i++] = (byte)(filenameLength & 0x00FF); bytes[i++] = (byte)((filenameLength & 0xFF00) >> 8); // extra field length (short) Int16 ExtraFieldLength = 0x00; bytes[i++] = (byte)(ExtraFieldLength & 0x00FF); bytes[i++] = (byte)((ExtraFieldLength & 0xFF00) >> 8); // Tue, 27 Mar 2007 16:35 // Creating a zip that contains entries with "fully qualified" pathnames // can result in a zip archive that is unreadable by Windows Explorer. // Such archives are valid according to other tools but not to explorer. // To avoid this, we can trim off the leading volume name and slash (eg // c:\) when creating (writing) a zip file. We do this by default and we // leave the old behavior available with the // TrimVolumeFromFullyQualifiedPaths flag - set it to false to get the old // behavior. It only affects zip creation. // Tue, 05 Feb 2008 12:25 // Replace backslashes with forward slashes in the archive // the filename written to the archive char[] c = ((TrimVolumeFromFullyQualifiedPaths) && (FileName[1] == ':') && (FileName[2] == '\\')) ? FileName.Substring(3).Replace("\\", "/").ToCharArray() : // trim off volume letter, colon, and slash FileName.Replace("\\", "/").ToCharArray(); int j = 0; if (_Debug) { System.Console.WriteLine("local header: writing filename, {0} chars", c.Length); System.Console.WriteLine("starting offset={0}", i); } for (j = 0; (j < c.Length) && (i + j < bytes.Length); j++) { bytes[i + j] = System.BitConverter.GetBytes(c[j])[0]; if (_Debug) System.Console.Write(" {0:X2}", bytes[i + j]); } if (_Debug) System.Console.WriteLine(); i += j; // extra field (we always write nothing in this implementation) // ;; // remember the file offset of this header _RelativeOffsetOfHeader = (int)s.Length; if (_Debug) { System.Console.WriteLine("\nAll header data:"); for (j = 0; j < i; j++) System.Console.Write(" {0:X2}", bytes[j]); System.Console.WriteLine(); } // finally, write the header to the stream s.Write(bytes, 0, i); // preserve this header data for use with the central directory structure. _header = new byte[i]; if (_Debug) System.Console.WriteLine("preserving header of {0} bytes", _header.Length); for (j = 0; j < i; j++) _header[j] = bytes[j]; } internal void Write(System.IO.Stream s) { byte[] bytes = new byte[4096]; int n; // write the header: WriteHeader(s, bytes); if (IsDirectory) return; // nothing more to do! (need to close memory stream?) if (_Debug) { Console.WriteLine("{0}: writing compressed data to zipfile...", FileName); Console.WriteLine("{0}: total data length: {1}", FileName, _CompressedSize); } if (_CompressedSize == 0) { // nothing more to write. //(need to close memory stream?) if (_UnderlyingMemoryStream != null) { _UnderlyingMemoryStream.Close(); _UnderlyingMemoryStream = null; } return; } // write the actual file data: if (_FileData != null) { // use the existing compressed data we read from the extant zip archive s.Write(_FileData, 0, _FileData.Length); } else { // rely on the compressed data we created in WriteHeader _UnderlyingMemoryStream.Position = 0; while ((n = _UnderlyingMemoryStream.Read(bytes, 0, bytes.Length)) != 0) { if (_Debug) { Console.WriteLine("{0}: transferring {1} bytes...", FileName, n); for (int j = 0; j < n; j += 2) { if ((j > 0) && (j % 40 == 0)) System.Console.WriteLine(); System.Console.Write(" {0:X2}", bytes[j]); if (j + 1 < n) System.Console.Write("{0:X2}", bytes[j + 1]); } System.Console.WriteLine("\n"); } s.Write(bytes, 0, n); } //_CompressedStream.Close(); //_CompressedStream= null; _UnderlyingMemoryStream.Close(); _UnderlyingMemoryStream = null; } } private bool _Debug = false; private DateTime _LastModified; private bool _TrimVolumeFromFullyQualifiedPaths = true; // by default, trim them. private string _LocalFileName; private string _FileNameInArchive; private Int16 _VersionNeeded; private Int16 _BitField; private Int16 _CompressionMethod; private string _Comment; private bool _IsDirectory; private Int32 _CompressedSize; private Int32 _UncompressedSize; private Int32 _LastModDateTime; private Int32 _Crc32; private byte[] _Extra; private bool _OverwriteOnExtract = false; private byte[] __filedata; private System.IO.MemoryStream _UnderlyingMemoryStream; private System.IO.Compression.DeflateStream _CompressedStream; private byte[] _header; private int _RelativeOffsetOfHeader; } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Threading; using NLog.Common; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class AutoFlushTargetWrapperTests : NLogTestBase { [Fact] public void AutoFlushTargetWrapperSyncTest1() { var myTarget = new MyTarget(); var wrapper = new AutoFlushTargetWrapper { WrappedTarget = myTarget, }; myTarget.Initialize(null); wrapper.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; bool continuationHit = false; AsyncContinuation continuation = ex => { lastException = ex; continuationHit = true; }; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.True(continuationHit); Assert.Null(lastException); Assert.Equal(1, myTarget.FlushCount); Assert.Equal(1, myTarget.WriteCount); continuationHit = false; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.True(continuationHit); Assert.Null(lastException); Assert.Equal(2, myTarget.WriteCount); Assert.Equal(2, myTarget.FlushCount); } [Fact] public void AutoFlushTargetWrapperAsyncTest1() { var myTarget = new MyAsyncTarget(); var wrapper = new AutoFlushTargetWrapper(myTarget); myTarget.Initialize(null); wrapper.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { lastException = ex; continuationHit.Set(); }; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.Null(lastException); Assert.Equal(1, myTarget.FlushCount); Assert.Equal(1, myTarget.WriteCount); continuationHit.Reset(); wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.Null(lastException); Assert.Equal(2, myTarget.WriteCount); Assert.Equal(2, myTarget.FlushCount); } [Fact] public void AutoFlushTargetWrapperAsyncTest2() { var myTarget = new MyAsyncTarget(); var wrapper = new AutoFlushTargetWrapper(myTarget); myTarget.Initialize(null); wrapper.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; for (int i = 0; i < 100; ++i) { wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(ex => lastException = ex)); } var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { continuationHit.Set(); }; wrapper.Flush(ex => { }); Assert.Null(lastException); wrapper.Flush(continuation); Assert.Null(lastException); continuationHit.WaitOne(); Assert.Null(lastException); wrapper.Flush(ex => { }); // Executed right away Assert.Null(lastException); Assert.Equal(100, myTarget.WriteCount); Assert.Equal(103, myTarget.FlushCount); } [Fact] public void AutoFlushTargetWrapperAsyncWithExceptionTest1() { var myTarget = new MyAsyncTarget { ThrowExceptions = true, }; var wrapper = new AutoFlushTargetWrapper(myTarget); myTarget.Initialize(null); wrapper.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { lastException = ex; continuationHit.Set(); }; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.NotNull(lastException); Assert.IsType<InvalidOperationException>(lastException); // no flush on exception Assert.Equal(0, myTarget.FlushCount); Assert.Equal(1, myTarget.WriteCount); continuationHit.Reset(); lastException = null; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.NotNull(lastException); Assert.IsType<InvalidOperationException>(lastException); Assert.Equal(0, myTarget.FlushCount); Assert.Equal(2, myTarget.WriteCount); } [Fact] public void AutoFlushConditionConfigurationTest() { LogManager.Configuration = CreateConfigurationFromString( @"<nlog> <targets> <target type='AutoFlushWrapper' condition='level >= LogLevel.Debug' name='FlushOnError'> <target name='d2' type='Debug' /> </target> </targets> <rules> <logger name='*' level='Warn' writeTo='FlushOnError'> </logger> </rules> </nlog>"); var target = LogManager.Configuration.FindTargetByName("FlushOnError") as AutoFlushTargetWrapper; Assert.NotNull(target); Assert.NotNull(target.Condition); Assert.Equal("(level >= Debug)", target.Condition.ToString()); Assert.Equal("d2", target.WrappedTarget.Name); } [Fact] public void AutoFlushOnConditionTest() { var testTarget = new MyTarget(); var autoFlushWrapper = new AutoFlushTargetWrapper(testTarget); autoFlushWrapper.Condition = "level > LogLevel.Info"; testTarget.Initialize(null); autoFlushWrapper.Initialize(null); AsyncContinuation continuation = ex => { }; autoFlushWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Info, "*", "test").WithContinuation(continuation)); autoFlushWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "test").WithContinuation(continuation)); Assert.Equal(2, testTarget.WriteCount); Assert.Equal(0, testTarget.FlushCount); autoFlushWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Warn, "*", "test").WithContinuation(continuation)); autoFlushWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Error, "*", "test").WithContinuation(continuation)); Assert.Equal(4, testTarget.WriteCount); Assert.Equal(2, testTarget.FlushCount); } [Fact] public void MultipleConditionalAutoFlushWrappersTest() { var testTarget = new MyTarget(); var autoFlushOnLevelWrapper = new AutoFlushTargetWrapper(testTarget); autoFlushOnLevelWrapper.Condition = "level > LogLevel.Info"; var autoFlushOnMessageWrapper = new AutoFlushTargetWrapper(autoFlushOnLevelWrapper); autoFlushOnMessageWrapper.Condition = "contains('${message}','FlushThis')"; testTarget.Initialize(null); autoFlushOnLevelWrapper.Initialize(null); autoFlushOnMessageWrapper.Initialize(null); AsyncContinuation continuation = ex => { }; autoFlushOnMessageWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "test").WithContinuation(continuation)); Assert.Equal(1, testTarget.WriteCount); Assert.Equal(0, testTarget.FlushCount); autoFlushOnMessageWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Fatal, "*", "test").WithContinuation(continuation)); Assert.Equal(2, testTarget.WriteCount); Assert.Equal(1, testTarget.FlushCount); autoFlushOnMessageWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "Please FlushThis").WithContinuation(continuation)); Assert.Equal(3, testTarget.WriteCount); Assert.Equal(2, testTarget.FlushCount); } [Fact] public void BufferingAutoFlushWrapperTest() { var testTarget = new MyTarget(); var bufferingTargetWrapper = new BufferingTargetWrapper(testTarget, 100); var autoFlushOnLevelWrapper = new AutoFlushTargetWrapper(bufferingTargetWrapper); autoFlushOnLevelWrapper.Condition = "level > LogLevel.Info"; testTarget.Initialize(null); bufferingTargetWrapper.Initialize(null); autoFlushOnLevelWrapper.Initialize(null); AsyncContinuation continuation = ex => { }; autoFlushOnLevelWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "test").WithContinuation(continuation)); Assert.Equal(0, testTarget.WriteCount); Assert.Equal(0, testTarget.FlushCount); autoFlushOnLevelWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Fatal, "*", "test").WithContinuation(continuation)); Assert.Equal(2, testTarget.WriteCount); Assert.Equal(1, testTarget.FlushCount); autoFlushOnLevelWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "Please FlushThis").WithContinuation(continuation)); Assert.Equal(2, testTarget.WriteCount); Assert.Equal(1, testTarget.FlushCount); } class MyAsyncTarget : Target { public int FlushCount { get; private set; } public int WriteCount { get; private set; } protected override void Write(LogEventInfo logEvent) { throw new NotSupportedException(); } protected override void Write(AsyncLogEventInfo logEvent) { Assert.True(this.FlushCount <= this.WriteCount); this.WriteCount++; ThreadPool.QueueUserWorkItem( s => { if (this.ThrowExceptions) { logEvent.Continuation(new InvalidOperationException("Some problem!")); logEvent.Continuation(new InvalidOperationException("Some problem!")); } else { logEvent.Continuation(null); logEvent.Continuation(null); } }); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { this.FlushCount++; ThreadPool.QueueUserWorkItem( s => asyncContinuation(null)); } public bool ThrowExceptions { get; set; } } class MyTarget : Target { public int FlushCount { get; set; } public int WriteCount { get; set; } protected override void Write(LogEventInfo logEvent) { Assert.True(this.FlushCount <= this.WriteCount); this.WriteCount++; } protected override void FlushAsync(AsyncContinuation asyncContinuation) { this.FlushCount++; asyncContinuation(null); } } } }