context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Orleans.Configuration;
using Orleans.Configuration.Validators;
using Orleans.GrainDirectory;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.ConsistentRing;
using Orleans.Runtime.Counters;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.LogConsistency;
using Orleans.Runtime.MembershipService;
using Orleans.Metadata;
using Orleans.Runtime.Messaging;
using Orleans.Runtime.MultiClusterNetwork;
using Orleans.Runtime.Placement;
using Orleans.Runtime.Providers;
using Orleans.Runtime.ReminderService;
using Orleans.Runtime.Scheduler;
using Orleans.Runtime.Versions;
using Orleans.Runtime.Versions.Compatibility;
using Orleans.Runtime.Versions.Selector;
using Orleans.Serialization;
using Orleans.Statistics;
using Orleans.Streams;
using Orleans.Streams.Core;
using Orleans.Timers;
using Orleans.Versions;
using Orleans.Versions.Compatibility;
using Orleans.Versions.Selector;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Transactions;
using Orleans.LogConsistency;
using Microsoft.Extensions.Logging;
using Orleans.ApplicationParts;
using Orleans.Runtime.Utilities;
using System;
using System.Reflection;
using System.Linq;
using Microsoft.Extensions.Options;
using Orleans.Timers.Internal;
using Microsoft.AspNetCore.Connections;
using Orleans.Networking.Shared;
using Orleans.Configuration.Internal;
namespace Orleans.Hosting
{
internal static class DefaultSiloServices
{
internal static void AddDefaultServices(IApplicationPartManager applicationPartManager, IServiceCollection services)
{
services.AddOptions();
services.AddTransient<IConfigurationValidator, EndpointOptionsValidator>();
// Options logging
services.TryAddSingleton(typeof(IOptionFormatter<>), typeof(DefaultOptionsFormatter<>));
services.TryAddSingleton(typeof(IOptionFormatterResolver<>), typeof(DefaultOptionsFormatterResolver<>));
// Register system services.
services.TryAddSingleton<ILocalSiloDetails, LocalSiloDetails>();
services.TryAddSingleton<ISiloHost, SiloWrapper>();
services.TryAddTransient<ILifecycleSubject, LifecycleSubject>();
services.TryAddSingleton<SiloLifecycleSubject>();
services.TryAddFromExisting<ISiloLifecycleSubject, SiloLifecycleSubject>();
services.TryAddFromExisting<ISiloLifecycle, SiloLifecycleSubject>();
services.AddSingleton<SiloOptionsLogger>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, SiloOptionsLogger>();
services.PostConfigure<SiloMessagingOptions>(options =>
{
//
// Assign environment specific defaults post configuration if user did not configured otherwise.
//
if (options.SiloSenderQueues == 0)
{
options.SiloSenderQueues = Environment.ProcessorCount;
}
if (options.GatewaySenderQueues == 0)
{
options.GatewaySenderQueues = Environment.ProcessorCount;
}
});
services.TryAddSingleton<TelemetryManager>();
services.TryAddFromExisting<ITelemetryProducer, TelemetryManager>();
services.TryAddSingleton<IAppEnvironmentStatistics, AppEnvironmentStatistics>();
services.TryAddSingleton<IHostEnvironmentStatistics, NoOpHostEnvironmentStatistics>();
services.TryAddSingleton<SiloStatisticsManager>();
services.TryAddSingleton<ApplicationRequestsStatisticsGroup>();
services.TryAddSingleton<StageAnalysisStatisticsGroup>();
services.TryAddSingleton<SchedulerStatisticsGroup>();
services.TryAddSingleton<SerializationStatisticsGroup>();
services.TryAddSingleton<OverloadDetector>();
services.TryAddSingleton<ExecutorService>();
// queue balancer contructing related
services.TryAddTransient<IStreamQueueBalancer, ConsistentRingQueueBalancer>();
services.TryAddSingleton<FallbackSystemTarget>();
services.TryAddSingleton<LifecycleSchedulingSystemTarget>();
services.AddLogging();
services.TryAddSingleton<ITimerRegistry, TimerRegistry>();
services.TryAddSingleton<IReminderRegistry, ReminderRegistry>();
services.TryAddSingleton<GrainRuntime>();
services.TryAddSingleton<IGrainRuntime, GrainRuntime>();
services.TryAddSingleton<IGrainCancellationTokenRuntime, GrainCancellationTokenRuntime>();
services.TryAddSingleton<OrleansTaskScheduler>();
services.AddFromExisting<IHealthCheckParticipant, OrleansTaskScheduler>();
services.TryAddSingleton<GrainFactory>(sp => sp.GetService<InsideRuntimeClient>().ConcreteGrainFactory);
services.TryAddFromExisting<IGrainFactory, GrainFactory>();
services.TryAddFromExisting<IInternalGrainFactory, GrainFactory>();
services.TryAddFromExisting<IGrainReferenceConverter, GrainFactory>();
services.TryAddSingleton<IGrainReferenceRuntime, GrainReferenceRuntime>();
services.TryAddSingleton<TypeMetadataCache>();
services.TryAddSingleton<ActivationDirectory>();
services.TryAddSingleton<ActivationCollector>();
services.TryAddSingleton<LocalGrainDirectory>();
services.TryAddFromExisting<ILocalGrainDirectory, LocalGrainDirectory>();
services.TryAddSingleton(sp => sp.GetRequiredService<LocalGrainDirectory>().GsiActivationMaintainer);
services.TryAddSingleton<GrainTypeManager>();
services.TryAddSingleton<MessageCenter>();
services.TryAddFromExisting<IMessageCenter, MessageCenter>();
services.TryAddFromExisting<ISiloMessageCenter, MessageCenter>();
services.TryAddSingleton(FactoryUtility.Create<MessageCenter, Gateway>);
services.AddSingleton<Gateway>(sp => sp.GetRequiredService<MessageCenter>().Gateway);
services.TryAddSingleton<Dispatcher>(sp => sp.GetRequiredService<Catalog>().Dispatcher);
services.TryAddSingleton<InsideRuntimeClient>();
services.TryAddFromExisting<IRuntimeClient, InsideRuntimeClient>();
services.TryAddFromExisting<ISiloRuntimeClient, InsideRuntimeClient>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, InsideRuntimeClient>();
services.TryAddSingleton<IGrainServiceFactory, GrainServiceFactory>();
services.TryAddSingleton<IFatalErrorHandler, FatalErrorHandler>();
services.TryAddSingleton<MultiClusterGossipChannelFactory>();
services.TryAddSingleton<MultiClusterOracle>();
services.TryAddSingleton<MultiClusterRegistrationStrategyManager>();
services.TryAddFromExisting<IMultiClusterOracle, MultiClusterOracle>();
services.TryAddSingleton<DeploymentLoadPublisher>();
services.TryAddSingleton<IAsyncTimerFactory, AsyncTimerFactory>();
services.TryAddSingleton<MembershipTableManager>();
services.AddFromExisting<IHealthCheckParticipant, MembershipTableManager>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, MembershipTableManager>();
services.TryAddSingleton<MembershipSystemTarget>();
services.AddFromExisting<IMembershipService, MembershipSystemTarget>();
services.TryAddSingleton<IMembershipGossiper, MembershipGossiper>();
services.TryAddSingleton<IRemoteSiloProber, RemoteSiloProber>();
services.TryAddSingleton<SiloStatusOracle>();
services.TryAddFromExisting<ISiloStatusOracle, SiloStatusOracle>();
services.AddSingleton<ClusterHealthMonitor>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, ClusterHealthMonitor>();
services.AddFromExisting<IHealthCheckParticipant, ClusterHealthMonitor>();
services.AddSingleton<MembershipAgent>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, MembershipAgent>();
services.AddFromExisting<IHealthCheckParticipant, MembershipAgent>();
services.AddSingleton<MembershipTableCleanupAgent>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, MembershipTableCleanupAgent>();
services.AddFromExisting<IHealthCheckParticipant, MembershipTableCleanupAgent>();
services.AddSingleton<SiloStatusListenerManager>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, SiloStatusListenerManager>();
services.AddSingleton<ClusterMembershipService>();
services.TryAddFromExisting<IClusterMembershipService, ClusterMembershipService>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, ClusterMembershipService>();
services.TryAddSingleton<ClientObserverRegistrar>();
services.TryAddSingleton<SiloProviderRuntime>();
services.TryAddFromExisting<IStreamProviderRuntime, SiloProviderRuntime>();
services.TryAddFromExisting<IProviderRuntime, SiloProviderRuntime>();
services.TryAddSingleton<ImplicitStreamSubscriberTable>();
services.TryAddSingleton<MessageFactory>();
services.TryAddSingleton<IGrainRegistrar<GlobalSingleInstanceRegistration>, GlobalSingleInstanceRegistrar>();
services.TryAddSingleton<IGrainRegistrar<ClusterLocalRegistration>, ClusterLocalRegistrar>();
services.TryAddSingleton<RegistrarManager>();
services.TryAddSingleton<Factory<Grain, IMultiClusterRegistrationStrategy, ILogConsistencyProtocolServices>>(FactoryUtility.Create<Grain, IMultiClusterRegistrationStrategy, ProtocolServices>);
services.TryAddSingleton(FactoryUtility.Create<GrainDirectoryPartition>);
// Placement
services.AddSingleton<IConfigurationValidator, ActivationCountBasedPlacementOptionsValidator>();
services.TryAddSingleton<PlacementDirectorsManager>();
services.TryAddSingleton<ClientObserversPlacementDirector>();
// Configure the default placement strategy.
services.TryAddSingleton<PlacementStrategy, RandomPlacement>();
// Placement directors
services.AddPlacementDirector<RandomPlacement, RandomPlacementDirector>();
services.AddPlacementDirector<PreferLocalPlacement, PreferLocalPlacementDirector>();
services.AddPlacementDirector<StatelessWorkerPlacement, StatelessWorkerDirector>();
services.Replace(new ServiceDescriptor(typeof(StatelessWorkerPlacement), sp => new StatelessWorkerPlacement(), ServiceLifetime.Singleton));
services.AddPlacementDirector<ActivationCountBasedPlacement, ActivationCountPlacementDirector>();
services.AddPlacementDirector<HashBasedPlacement, HashBasedPlacementDirector>();
// Activation selectors
services.AddSingletonKeyedService<Type, IActivationSelector, RandomPlacementDirector>(typeof(RandomPlacement));
services.AddSingletonKeyedService<Type, IActivationSelector, StatelessWorkerDirector>(typeof(StatelessWorkerPlacement));
// Versioning
services.TryAddSingleton<VersionSelectorManager>();
services.TryAddSingleton<CachedVersionSelectorManager>();
// Version selector strategy
if (!services.Any(x => x.ServiceType == typeof(IVersionStore)))
{
services.TryAddSingleton<GrainVersionStore>();
services.AddFromExisting<IVersionStore, GrainVersionStore>();
}
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, GrainVersionStore>();
services.AddSingletonNamedService<VersionSelectorStrategy, AllCompatibleVersions>(nameof(AllCompatibleVersions));
services.AddSingletonNamedService<VersionSelectorStrategy, LatestVersion>(nameof(LatestVersion));
services.AddSingletonNamedService<VersionSelectorStrategy, MinimumVersion>(nameof(MinimumVersion));
// Versions selectors
services.AddSingletonKeyedService<Type, IVersionSelector, MinimumVersionSelector>(typeof(MinimumVersion));
services.AddSingletonKeyedService<Type, IVersionSelector, LatestVersionSelector>(typeof(LatestVersion));
services.AddSingletonKeyedService<Type, IVersionSelector, AllCompatibleVersionsSelector>(typeof(AllCompatibleVersions));
// Compatibility
services.TryAddSingleton<CompatibilityDirectorManager>();
// Compatability strategy
services.AddSingletonNamedService<CompatibilityStrategy, AllVersionsCompatible>(nameof(AllVersionsCompatible));
services.AddSingletonNamedService<CompatibilityStrategy, BackwardCompatible>(nameof(BackwardCompatible));
services.AddSingletonNamedService<CompatibilityStrategy, StrictVersionCompatible>(nameof(StrictVersionCompatible));
// Compatability directors
services.AddSingletonKeyedService<Type, ICompatibilityDirector, BackwardCompatilityDirector>(typeof(BackwardCompatible));
services.AddSingletonKeyedService<Type, ICompatibilityDirector, AllVersionsCompatibilityDirector>(typeof(AllVersionsCompatible));
services.AddSingletonKeyedService<Type, ICompatibilityDirector, StrictVersionCompatibilityDirector>(typeof(StrictVersionCompatible));
services.TryAddSingleton<Factory<IGrainRuntime>>(sp => () => sp.GetRequiredService<IGrainRuntime>());
// Grain activation
services.TryAddSingleton<Catalog>();
services.TryAddSingleton<GrainCreator>();
services.TryAddSingleton<IGrainActivator, DefaultGrainActivator>();
services.TryAddScoped<ActivationData.GrainActivationContextFactory>();
services.TryAddScoped<IGrainActivationContext>(sp => sp.GetRequiredService<ActivationData.GrainActivationContextFactory>().Context);
services.TryAddSingleton<IStreamSubscriptionManagerAdmin>(sp => new StreamSubscriptionManagerAdmin(sp.GetRequiredService<IStreamProviderRuntime>()));
services.TryAddSingleton<IConsistentRingProvider>(
sp =>
{
// TODO: make this not sux - jbragg
var consistentRingOptions = sp.GetRequiredService<IOptions<ConsistentRingOptions>>().Value;
var siloDetails = sp.GetRequiredService<ILocalSiloDetails>();
var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
if (consistentRingOptions.UseVirtualBucketsConsistentRing)
{
return new VirtualBucketsRingProvider(siloDetails.SiloAddress, loggerFactory, consistentRingOptions.NumVirtualBucketsConsistentRing);
}
return new ConsistentRingProvider(siloDetails.SiloAddress, loggerFactory);
});
services.TryAddSingleton(typeof(IKeyedServiceCollection<,>), typeof(KeyedServiceCollection<,>));
// Serialization
services.TryAddSingleton<SerializationManager>(sp=>ActivatorUtilities.CreateInstance<SerializationManager>(sp,
sp.GetRequiredService<IOptions<SiloMessagingOptions>>().Value.LargeMessageWarningThreshold));
services.TryAddSingleton<ITypeResolver, CachedTypeResolver>();
services.TryAddSingleton<IFieldUtils, FieldUtils>();
services.AddSingleton<BinaryFormatterSerializer>();
services.AddSingleton<BinaryFormatterISerializableSerializer>();
services.AddFromExisting<IKeyedSerializer, BinaryFormatterISerializableSerializer>();
#pragma warning disable CS0618 // Type or member is obsolete
services.AddSingleton<ILBasedSerializer>();
services.AddFromExisting<IKeyedSerializer, ILBasedSerializer>();
#pragma warning restore CS0618 // Type or member is obsolete
// Transactions
services.TryAddSingleton<ITransactionAgent, DisabledTransactionAgent>();
// Application Parts
services.TryAddSingleton<IApplicationPartManager>(applicationPartManager);
applicationPartManager.AddApplicationPart(new AssemblyPart(typeof(RuntimeVersion).Assembly) { IsFrameworkAssembly = true });
applicationPartManager.AddApplicationPart(new AssemblyPart(typeof(Silo).Assembly) { IsFrameworkAssembly = true });
applicationPartManager.AddFeatureProvider(new BuiltInTypesSerializationFeaturePopulator());
applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider<GrainInterfaceFeature>());
applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider<GrainClassFeature>());
applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider<SerializerFeature>());
services.AddTransient<IConfigurationValidator, ApplicationPartValidator>();
//Add default option formatter if none is configured, for options which are required to be configured
services.ConfigureFormatter<SiloOptions>();
services.ConfigureFormatter<ProcessExitHandlingOptions>();
services.ConfigureFormatter<SchedulingOptions>();
services.ConfigureFormatter<PerformanceTuningOptions>();
services.ConfigureFormatter<SerializationProviderOptions>();
services.ConfigureFormatter<ConnectionOptions>();
services.ConfigureFormatter<SiloMessagingOptions>();
services.ConfigureFormatter<TypeManagementOptions>();
services.ConfigureFormatter<ClusterMembershipOptions>();
services.ConfigureFormatter<GrainDirectoryOptions>();
services.ConfigureFormatter<ActivationCountBasedPlacementOptions>();
services.ConfigureFormatter<GrainCollectionOptions>();
services.ConfigureFormatter<GrainVersioningOptions>();
services.ConfigureFormatter<ConsistentRingOptions>();
services.ConfigureFormatter<MultiClusterOptions>();
services.ConfigureFormatter<StatisticsOptions>();
services.ConfigureFormatter<TelemetryOptions>();
services.ConfigureFormatter<LoadSheddingOptions>();
services.ConfigureFormatter<EndpointOptions>();
services.ConfigureFormatter<ClusterOptions>();
// This validator needs to construct the IMembershipOracle and the IMembershipTable
// so move it in the end so other validator are called first
services.AddTransient<IConfigurationValidator, ClusterOptionsValidator>();
services.AddTransient<IConfigurationValidator, SiloClusteringValidator>();
services.AddTransient<IConfigurationValidator, DevelopmentClusterMembershipOptionsValidator>();
// Enable hosted client.
services.TryAddSingleton<HostedClient>();
services.TryAddFromExisting<IHostedClient, HostedClient>();
services.AddFromExisting<ILifecycleParticipant<ISiloLifecycle>, HostedClient>();
services.TryAddSingleton<InvokableObjectManager>();
services.TryAddSingleton<InternalClusterClient>();
services.TryAddFromExisting<IInternalClusterClient, InternalClusterClient>();
services.TryAddFromExisting<IClusterClient, InternalClusterClient>();
// Enable collection specific Age limits
services.AddOptions<GrainCollectionOptions>()
.Configure<IApplicationPartManager>((options, parts) =>
{
var grainClasses = new GrainClassFeature();
parts.PopulateFeature(grainClasses);
foreach (var grainClass in grainClasses.Classes)
{
var attr = grainClass.ClassType.GetCustomAttribute<CollectionAgeLimitAttribute>();
if (attr != null)
{
var className = TypeUtils.GetFullName(grainClass.ClassType);
options.ClassSpecificCollectionAge[className] = attr.Amount;
}
}
});
// Validate all CollectionAgeLimit values for the right configuration.
services.AddTransient<IConfigurationValidator, GrainCollectionOptionsValidator>();
services.AddTransient<IConfigurationValidator, LoadSheddingValidator>();
services.TryAddSingleton<ITimerManager, TimerManagerImpl>();
// persistent state facet support
services.TryAddSingleton<IPersistentStateFactory, PersistentStateFactory>();
services.TryAddSingleton(typeof(IAttributeToFactoryMapper<PersistentStateAttribute>), typeof(PersistentStateAttributeMapper));
// Networking
services.TryAddSingleton<ConnectionManager>();
services.AddSingleton<ILifecycleParticipant<ISiloLifecycle>, ConnectionManagerLifecycleAdapter<ISiloLifecycle>>();
services.AddSingleton<ILifecycleParticipant<ISiloLifecycle>, SiloConnectionMaintainer>();
services.AddSingletonKeyedService<object, IConnectionFactory>(
SiloConnectionFactory.ServicesKey,
(sp, key) => ActivatorUtilities.CreateInstance<SocketConnectionFactory>(sp));
services.AddSingletonKeyedService<object, IConnectionListenerFactory>(
SiloConnectionListener.ServicesKey,
(sp, key) => ActivatorUtilities.CreateInstance<SocketConnectionListenerFactory>(sp));
services.AddSingletonKeyedService<object, IConnectionListenerFactory>(
GatewayConnectionListener.ServicesKey,
(sp, key) => ActivatorUtilities.CreateInstance<SocketConnectionListenerFactory>(sp));
services.TryAddTransient<IMessageSerializer>(sp => ActivatorUtilities.CreateInstance<MessageSerializer>(sp,
sp.GetRequiredService<IOptions<SiloMessagingOptions>>().Value.MaxMessageHeaderSize,
sp.GetRequiredService<IOptions<SiloMessagingOptions>>().Value.MaxMessageBodySize));
services.TryAddSingleton<ConnectionFactory, SiloConnectionFactory>();
services.TryAddSingleton<INetworkingTrace, NetworkingTrace>();
// Use Orleans server.
services.AddSingleton<ILifecycleParticipant<ISiloLifecycle>, SiloConnectionListener>();
services.AddSingleton<ILifecycleParticipant<ISiloLifecycle>, GatewayConnectionListener>();
services.AddSingleton<SocketSchedulers>();
services.AddSingleton<SharedMemoryPool>();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Diagnostics;
using Test.Utilities;
using Xunit;
namespace System.Runtime.Analyzers.UnitTests
{
public class SpecifyStringComparisonTests : DiagnosticAnalyzerTestBase
{
protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new SpecifyStringComparisonAnalyzer();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new SpecifyStringComparisonAnalyzer();
}
[Fact]
public void CA1307_StringCompareTests_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class StringComparisonTests
{
public int StringCompare()
{
string strA = """";
string strB = """";
var x1 = String.Compare(strA, strB);
var x2 = String.Compare(strA, strB, true);
var x3 = String.Compare(strA, 0, strB, 0, 1);
var x4 = String.Compare(strA, 0, strB, 0, 1, true);
return 0;
}
}",
GetCA1307CSharpResultsAt(11, 18, "string.Compare(string, string)",
"StringComparisonTests.StringCompare()",
"string.Compare(string, string, System.StringComparison)"),
GetCA1307CSharpResultsAt(12, 18, "string.Compare(string, string, bool)",
"StringComparisonTests.StringCompare()",
"string.Compare(string, string, System.StringComparison)"),
GetCA1307CSharpResultsAt(13, 18, "string.Compare(string, int, string, int, int)",
"StringComparisonTests.StringCompare()",
"string.Compare(string, int, string, int, int, System.StringComparison)"),
GetCA1307CSharpResultsAt(14, 18, "string.Compare(string, int, string, int, int, bool)",
"StringComparisonTests.StringCompare()",
"string.Compare(string, int, string, int, int, System.StringComparison)"));
}
[Fact]
public void CA1307_StringWithTests_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class StringComparisonTests
{
public bool StringWith()
{
string strA = """";
string strB = """";
var x = strA.EndsWith(strB);
return strA.StartsWith(strB);
}
}",
GetCA1307CSharpResultsAt(11, 17, "string.EndsWith(string)",
"StringComparisonTests.StringWith()",
"string.EndsWith(string, System.StringComparison)"),
GetCA1307CSharpResultsAt(12, 16, "string.StartsWith(string)",
"StringComparisonTests.StringWith()",
"string.StartsWith(string, System.StringComparison)"));
}
[Fact]
public void CA1307_StringIndexOfTests_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class StringComparisonTests
{
public int StringIndexOf()
{
string strA = """";
var x1 = strA.IndexOf("""");
var x2 = strA.IndexOf("""", 0);
return strA.IndexOf("""", 0, 1);
}
}",
GetCA1307CSharpResultsAt(10, 18, "string.IndexOf(string)",
"StringComparisonTests.StringIndexOf()",
"string.IndexOf(string, System.StringComparison)"),
GetCA1307CSharpResultsAt(11, 18, "string.IndexOf(string, int)",
"StringComparisonTests.StringIndexOf()",
"string.IndexOf(string, int, System.StringComparison)"),
GetCA1307CSharpResultsAt(12, 16, "string.IndexOf(string, int, int)",
"StringComparisonTests.StringIndexOf()",
"string.IndexOf(string, int, int, System.StringComparison)"));
}
[Fact]
public void CA1307_StringCompareToTests_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class StringComparisonTests
{
public int StringCompareTo()
{
string strA = """";
string strB = """";
var x1 = strA.CompareTo(strB);
return """".CompareTo(new object());
}
}",
GetCA1307CSharpResultsAt(11, 22, "string.CompareTo(string)",
"StringComparisonTests.StringCompareTo()",
"string.Compare(string, string, System.StringComparison)"),
GetCA1307CSharpResultsAt(12, 20, "string.CompareTo(object)",
"StringComparisonTests.StringCompareTo()",
"string.Compare(string, string, System.StringComparison)"));
}
[Fact]
public void CA1307_OverloadTests_CSharp()
{
VerifyCSharp(@"
using System;
using System.Globalization;
public class StringComparisonTests
{
public void NonString()
{
DoNothing("""");
DoNothing<string>(""""); // No diagnostics since this is generics
}
public void DoNothing(string str)
{
}
public void DoNothing<T>(string str)
{
}
public void DoNothing<T>(string str, StringComparison strCompare)
{
}
}",
GetCA1307CSharpResultsAt(9, 9, "StringComparisonTests.DoNothing(string)",
"StringComparisonTests.NonString()",
"StringComparisonTests.DoNothing<T>(string, System.StringComparison)"));
}
[Fact]
public void CA1307_StringCompareTests_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class StringComparisonTests
Public Function StringCompare() As Integer
Dim strA As String = """"
Dim strB As String = """"
Dim x1 = [String].Compare(strA, strB)
Dim x2 = [String].Compare(strA, strB, True)
Dim x3 = [String].Compare(strA, 0, strB, 0, 1)
Dim x4 = [String].Compare(strA, 0, strB, 0, 1, True)
Return 0
End Function
End Class",
GetCA1307BasicResultsAt(9, 18, "String.Compare(String, String)",
"StringComparisonTests.StringCompare()",
"String.Compare(String, String, System.StringComparison)"),
GetCA1307BasicResultsAt(10, 18, "String.Compare(String, String, Boolean)",
"StringComparisonTests.StringCompare()",
"String.Compare(String, String, System.StringComparison)"),
GetCA1307BasicResultsAt(11, 18, "String.Compare(String, Integer, String, Integer, Integer)",
"StringComparisonTests.StringCompare()",
"String.Compare(String, Integer, String, Integer, Integer, System.StringComparison)"),
GetCA1307BasicResultsAt(12, 18, "String.Compare(String, Integer, String, Integer, Integer, Boolean)",
"StringComparisonTests.StringCompare()",
"String.Compare(String, Integer, String, Integer, Integer, System.StringComparison)"));
}
[Fact]
public void CA1307_StringWithTests_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class StringComparisonTests
Public Function StringWith() As Boolean
Dim strA As String = """"
Dim strB As String = """"
Dim x = strA.EndsWith(strB)
Return strA.StartsWith(strB)
End Function
End Class",
GetCA1307BasicResultsAt(9, 17, "String.EndsWith(String)",
"StringComparisonTests.StringWith()",
"String.EndsWith(String, System.StringComparison)"),
GetCA1307BasicResultsAt(10, 16, "String.StartsWith(String)",
"StringComparisonTests.StringWith()",
"String.StartsWith(String, System.StringComparison)"));
}
[Fact]
public void CA1307_StringIndexOfTests_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class StringComparisonTests
Public Function StringIndexOf() As Integer
Dim strA As String = """"
Dim x1 = strA.IndexOf("""")
Dim x2 = strA.IndexOf("""", 0)
Return strA.IndexOf("""", 0, 1)
End Function
End Class",
GetCA1307BasicResultsAt(8, 18, "String.IndexOf(String)",
"StringComparisonTests.StringIndexOf()",
"String.IndexOf(String, System.StringComparison)"),
GetCA1307BasicResultsAt(9, 18, "String.IndexOf(String, Integer)",
"StringComparisonTests.StringIndexOf()",
"String.IndexOf(String, Integer, System.StringComparison)"),
GetCA1307BasicResultsAt(10, 16, "String.IndexOf(String, Integer, Integer)",
"StringComparisonTests.StringIndexOf()",
"String.IndexOf(String, Integer, Integer, System.StringComparison)"));
}
[Fact]
public void CA1307_StringCompareToTests_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class StringComparisonTests
Public Function StringCompareTo() As Integer
Dim strA As String = """"
Dim strB As String = """"
Dim x1 = strA.CompareTo(strB)
Return """".CompareTo(New Object())
End Function
End Class",
GetCA1307BasicResultsAt(9, 18, "String.CompareTo(String)",
"StringComparisonTests.StringCompareTo()",
"String.Compare(String, String, System.StringComparison)"),
GetCA1307BasicResultsAt(10, 16, "String.CompareTo(Object)",
"StringComparisonTests.StringCompareTo()",
"String.Compare(String, String, System.StringComparison)"));
}
[Fact]
public void CA1307_OverloadTests_VisualBasic()
{
VerifyBasic(@"
Imports System
Imports System.Globalization
Public Class StringComparisonTests
Public Sub NonString()
DoNothing("")
' No diagnostics since this is generics
DoNothing(Of String)("")
End Sub
Public Sub DoNothing(str As String)
End Sub
Public Sub DoNothing(Of T)(str As String)
End Sub
Public Sub DoNothing(Of T)(str As String, strCompare As StringComparison)
End Sub
End Class",
GetCA1307BasicResultsAt(7, 9, "StringComparisonTests.DoNothing(String)",
"StringComparisonTests.NonString()",
"StringComparisonTests.DoNothing(Of T)(String, System.StringComparison)"));
}
private DiagnosticResult GetCA1307CSharpResultsAt(int line, int column, string arg1, string arg2, string arg3)
{
return GetCSharpResultAt(
line,
column,
SpecifyStringComparisonAnalyzer.Rule,
arg1,
arg2,
arg3);
}
private DiagnosticResult GetCA1307BasicResultsAt(int line, int column, string arg1, string arg2, string arg3)
{
return GetBasicResultAt(
line,
column,
SpecifyStringComparisonAnalyzer.Rule,
arg1,
arg2,
arg3);
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using fyiReporting.RdlDesign.Resources;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Summary description for StyleCtl.
/// </summary>
internal class InteractivityCtl : System.Windows.Forms.UserControl, IProperty
{
private List<XmlNode> _ReportItems;
private DesignXmlDraw _Draw;
private List<DrillParameter> _DrillParameters;
// flags for controlling whether syntax changed for a particular property
private bool fBookmark, fAction, fHidden, fToggle;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox grpBoxVisibility;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox tbBookmark;
private System.Windows.Forms.RadioButton rbHyperlink;
private System.Windows.Forms.RadioButton rbBookmarkLink;
private System.Windows.Forms.RadioButton rbDrillthrough;
private System.Windows.Forms.TextBox tbHyperlink;
private System.Windows.Forms.TextBox tbBookmarkLink;
private System.Windows.Forms.TextBox tbDrillthrough;
private System.Windows.Forms.Button bParameters;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox tbHidden;
private System.Windows.Forms.ComboBox cbToggle;
private System.Windows.Forms.RadioButton rbNoAction;
private System.Windows.Forms.Button bDrillthrough;
private System.Windows.Forms.Button bHidden;
private System.Windows.Forms.Button bBookmarkLink;
private System.Windows.Forms.Button bHyperlink;
private System.Windows.Forms.Button bBookmark;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal InteractivityCtl(DesignXmlDraw dxDraw, List<XmlNode> reportItems)
{
_ReportItems = reportItems;
_Draw = dxDraw;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues(_ReportItems[0]);
}
private void InitValues(XmlNode node)
{
tbBookmark.Text = _Draw.GetElementValue(node, "Bookmark", "");
// Handle Action definition
XmlNode aNode = _Draw.GetNamedChildNode(node, "Action");
if (aNode == null)
rbNoAction.Checked = true;
else
{
XmlNode vLink = _Draw.GetNamedChildNode(aNode, "Hyperlink");
if (vLink != null)
{ // Hyperlink specified
rbHyperlink.Checked = true;
tbHyperlink.Text = vLink.InnerText;
}
else
{
vLink = _Draw.GetNamedChildNode(aNode, "Drillthrough");
if (vLink != null)
{ // Drillthrough specified
rbDrillthrough.Checked = true;
tbDrillthrough.Text = _Draw.GetElementValue(vLink, "ReportName", "");
_DrillParameters = new List<DrillParameter>();
XmlNode pNodes = _Draw.GetNamedChildNode(vLink, "Parameters");
if (pNodes != null)
{
foreach (XmlNode pNode in pNodes.ChildNodes)
{
if (pNode.Name != "Parameter")
continue;
string name = _Draw.GetElementAttribute(pNode, "Name", "");
string pvalue = _Draw.GetElementValue(pNode, "Value", "");
string omit = _Draw.GetElementValue(pNode, "Omit", "false");
DrillParameter dp = new DrillParameter(name, pvalue, omit);
_DrillParameters.Add(dp);
}
}
}
else
{
vLink = _Draw.GetNamedChildNode(aNode, "BookmarkLink");
if (vLink != null)
{ // BookmarkLink specified
rbBookmarkLink.Checked = true;
this.tbBookmarkLink.Text = vLink.InnerText;
}
}
}
}
// Handle Visiblity definition
XmlNode visNode = _Draw.GetNamedChildNode(node, "Visibility");
if (visNode != null)
{
XmlNode hNode = _Draw.GetNamedChildNode(node, "Visibility");
this.tbHidden.Text = _Draw.GetElementValue(visNode, "Hidden", "");
this.cbToggle.Text = _Draw.GetElementValue(visNode, "ToggleItem", "");
}
IEnumerable list = _Draw.GetReportItems("//Textbox");
if (list != null)
{
foreach (XmlNode tNode in list)
{
XmlAttribute name = tNode.Attributes["Name"];
if (name != null && name.Value != null && name.Value.Length > 0)
cbToggle.Items.Add(name.Value);
}
}
// nothing has changed now
fBookmark = fAction = fHidden = fToggle = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region 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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(InteractivityCtl));
this.grpBoxVisibility = new System.Windows.Forms.GroupBox();
this.bHidden = new System.Windows.Forms.Button();
this.cbToggle = new System.Windows.Forms.ComboBox();
this.tbHidden = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.bBookmarkLink = new System.Windows.Forms.Button();
this.bHyperlink = new System.Windows.Forms.Button();
this.rbNoAction = new System.Windows.Forms.RadioButton();
this.bParameters = new System.Windows.Forms.Button();
this.bDrillthrough = new System.Windows.Forms.Button();
this.tbDrillthrough = new System.Windows.Forms.TextBox();
this.tbBookmarkLink = new System.Windows.Forms.TextBox();
this.tbHyperlink = new System.Windows.Forms.TextBox();
this.rbDrillthrough = new System.Windows.Forms.RadioButton();
this.rbBookmarkLink = new System.Windows.Forms.RadioButton();
this.rbHyperlink = new System.Windows.Forms.RadioButton();
this.label1 = new System.Windows.Forms.Label();
this.tbBookmark = new System.Windows.Forms.TextBox();
this.bBookmark = new System.Windows.Forms.Button();
this.grpBoxVisibility.SuspendLayout();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// grpBoxVisibility
//
resources.ApplyResources(this.grpBoxVisibility, "grpBoxVisibility");
this.grpBoxVisibility.Controls.Add(this.bHidden);
this.grpBoxVisibility.Controls.Add(this.cbToggle);
this.grpBoxVisibility.Controls.Add(this.tbHidden);
this.grpBoxVisibility.Controls.Add(this.label3);
this.grpBoxVisibility.Controls.Add(this.label2);
this.grpBoxVisibility.Name = "grpBoxVisibility";
this.grpBoxVisibility.TabStop = false;
//
// bHidden
//
resources.ApplyResources(this.bHidden, "bHidden");
this.bHidden.Name = "bHidden";
this.bHidden.Tag = "visibility";
this.bHidden.Click += new System.EventHandler(this.bExpr_Click);
//
// cbToggle
//
resources.ApplyResources(this.cbToggle, "cbToggle");
this.cbToggle.Name = "cbToggle";
this.cbToggle.SelectedIndexChanged += new System.EventHandler(this.cbToggle_SelectedIndexChanged);
this.cbToggle.TextChanged += new System.EventHandler(this.cbToggle_SelectedIndexChanged);
//
// tbHidden
//
resources.ApplyResources(this.tbHidden, "tbHidden");
this.tbHidden.Name = "tbHidden";
this.tbHidden.TextChanged += new System.EventHandler(this.tbHidden_TextChanged);
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.label3.Name = "label3";
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// groupBox1
//
resources.ApplyResources(this.groupBox1, "groupBox1");
this.groupBox1.Controls.Add(this.bBookmarkLink);
this.groupBox1.Controls.Add(this.bHyperlink);
this.groupBox1.Controls.Add(this.rbNoAction);
this.groupBox1.Controls.Add(this.bParameters);
this.groupBox1.Controls.Add(this.bDrillthrough);
this.groupBox1.Controls.Add(this.tbDrillthrough);
this.groupBox1.Controls.Add(this.tbBookmarkLink);
this.groupBox1.Controls.Add(this.tbHyperlink);
this.groupBox1.Controls.Add(this.rbDrillthrough);
this.groupBox1.Controls.Add(this.rbBookmarkLink);
this.groupBox1.Controls.Add(this.rbHyperlink);
this.groupBox1.Name = "groupBox1";
this.groupBox1.TabStop = false;
//
// bBookmarkLink
//
resources.ApplyResources(this.bBookmarkLink, "bBookmarkLink");
this.bBookmarkLink.Name = "bBookmarkLink";
this.bBookmarkLink.Tag = "bookmarklink";
this.bBookmarkLink.Click += new System.EventHandler(this.bExpr_Click);
//
// bHyperlink
//
resources.ApplyResources(this.bHyperlink, "bHyperlink");
this.bHyperlink.Name = "bHyperlink";
this.bHyperlink.Tag = "hyperlink";
this.bHyperlink.Click += new System.EventHandler(this.bExpr_Click);
//
// rbNoAction
//
resources.ApplyResources(this.rbNoAction, "rbNoAction");
this.rbNoAction.Name = "rbNoAction";
this.rbNoAction.CheckedChanged += new System.EventHandler(this.rbAction_CheckedChanged);
//
// bParameters
//
resources.ApplyResources(this.bParameters, "bParameters");
this.bParameters.Name = "bParameters";
this.bParameters.Click += new System.EventHandler(this.bParameters_Click);
//
// bDrillthrough
//
resources.ApplyResources(this.bDrillthrough, "bDrillthrough");
this.bDrillthrough.Name = "bDrillthrough";
this.bDrillthrough.Click += new System.EventHandler(this.bDrillthrough_Click);
//
// tbDrillthrough
//
resources.ApplyResources(this.tbDrillthrough, "tbDrillthrough");
this.tbDrillthrough.Name = "tbDrillthrough";
this.tbDrillthrough.TextChanged += new System.EventHandler(this.tbAction_TextChanged);
//
// tbBookmarkLink
//
resources.ApplyResources(this.tbBookmarkLink, "tbBookmarkLink");
this.tbBookmarkLink.Name = "tbBookmarkLink";
this.tbBookmarkLink.TextChanged += new System.EventHandler(this.tbAction_TextChanged);
//
// tbHyperlink
//
resources.ApplyResources(this.tbHyperlink, "tbHyperlink");
this.tbHyperlink.Name = "tbHyperlink";
this.tbHyperlink.TextChanged += new System.EventHandler(this.tbAction_TextChanged);
//
// rbDrillthrough
//
resources.ApplyResources(this.rbDrillthrough, "rbDrillthrough");
this.rbDrillthrough.Name = "rbDrillthrough";
this.rbDrillthrough.CheckedChanged += new System.EventHandler(this.rbAction_CheckedChanged);
//
// rbBookmarkLink
//
resources.ApplyResources(this.rbBookmarkLink, "rbBookmarkLink");
this.rbBookmarkLink.Name = "rbBookmarkLink";
this.rbBookmarkLink.CheckedChanged += new System.EventHandler(this.rbAction_CheckedChanged);
//
// rbHyperlink
//
resources.ApplyResources(this.rbHyperlink, "rbHyperlink");
this.rbHyperlink.Name = "rbHyperlink";
this.rbHyperlink.CheckedChanged += new System.EventHandler(this.rbAction_CheckedChanged);
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// tbBookmark
//
resources.ApplyResources(this.tbBookmark, "tbBookmark");
this.tbBookmark.Name = "tbBookmark";
//
// bBookmark
//
resources.ApplyResources(this.bBookmark, "bBookmark");
this.bBookmark.Name = "bBookmark";
this.bBookmark.Tag = "bookmark";
this.bBookmark.Click += new System.EventHandler(this.bExpr_Click);
//
// InteractivityCtl
//
resources.ApplyResources(this, "$this");
this.Controls.Add(this.bBookmark);
this.Controls.Add(this.tbBookmark);
this.Controls.Add(this.label1);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.grpBoxVisibility);
this.Name = "InteractivityCtl";
this.grpBoxVisibility.ResumeLayout(false);
this.grpBoxVisibility.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public bool IsValid()
{
return true;
}
public void Apply()
{
// take information in control and apply to all the style nodes
// Only change information that has been marked as modified;
// this way when group is selected it is possible to change just
// the items you want and keep the rest the same.
foreach (XmlNode riNode in this._ReportItems)
ApplyChanges(riNode);
// nothing has changed now
fBookmark = fAction = fHidden = fToggle = false;
}
private void ApplyChanges(XmlNode rNode)
{
if (fBookmark)
_Draw.SetElement(rNode, "Bookmark", tbBookmark.Text);
if (fHidden || fToggle)
{
XmlNode visNode = _Draw.SetElement(rNode, "Visibility", null);
if (fHidden)
_Draw.SetElement(visNode, "Hidden", tbHidden.Text);
if (fToggle)
_Draw.SetElement(visNode, "ToggleItem", this.cbToggle.Text);
}
if (fAction)
{
XmlNode aNode;
if (this.rbHyperlink.Checked)
{
aNode = _Draw.SetElement(rNode, "Action", null);
_Draw.RemoveElement(aNode, "Drillthrough");
_Draw.RemoveElement(aNode, "BookmarkLink");
_Draw.SetElement(aNode, "Hyperlink", tbHyperlink.Text);
}
else if (this.rbDrillthrough.Checked)
{
aNode = _Draw.SetElement(rNode, "Action", null);
_Draw.RemoveElement(aNode, "Hyperlink");
_Draw.RemoveElement(aNode, "BookmarkLink");
XmlNode dNode = _Draw.SetElement(aNode, "Drillthrough", null);
_Draw.SetElement(dNode, "ReportName", tbDrillthrough.Text);
// Now do parameters
_Draw.RemoveElement(dNode, "Parameters"); // Get rid of prior values
if (this._DrillParameters != null && _DrillParameters.Count > 0)
{
XmlNode pNodes = _Draw.SetElement(dNode, "Parameters", null);
foreach (DrillParameter dp in _DrillParameters)
{
XmlNode p = _Draw.SetElement(pNodes, "Parameter", null);
_Draw.SetElementAttribute(p, "Name", dp.ParameterName);
_Draw.SetElement(p, "Value", dp.ParameterValue);
if (dp.ParameterOmit != null && dp.ParameterOmit.Length > 0)
_Draw.SetElement(p, "Omit", dp.ParameterOmit);
}
}
}
else if (this.rbBookmarkLink.Checked)
{
aNode = _Draw.SetElement(rNode, "Action", null);
_Draw.RemoveElement(aNode, "Drillthrough");
_Draw.RemoveElement(aNode, "Hyperlink");
_Draw.SetElement(aNode, "BookmarkLink", tbBookmarkLink.Text);
}
else // assume no action
{
_Draw.RemoveElement(rNode, "Action");
}
}
}
private void tbBookmark_TextChanged(object sender, System.EventArgs e)
{
fBookmark = true;
}
private void rbAction_CheckedChanged(object sender, System.EventArgs e)
{
if (this.rbHyperlink.Checked)
{
tbHyperlink.Enabled = bHyperlink.Enabled = true;
tbBookmarkLink.Enabled = bBookmarkLink.Enabled = false;
tbDrillthrough.Enabled = false;
bDrillthrough.Enabled = false;
bParameters.Enabled = false;
}
else if (this.rbDrillthrough.Checked)
{
tbHyperlink.Enabled = bHyperlink.Enabled = false;
tbBookmarkLink.Enabled = bBookmarkLink.Enabled = false;
tbDrillthrough.Enabled = true;
bDrillthrough.Enabled = true;
bParameters.Enabled = true;
}
else if (this.rbBookmarkLink.Checked)
{
tbHyperlink.Enabled = bHyperlink.Enabled = false;
tbBookmarkLink.Enabled = bBookmarkLink.Enabled = true;
tbDrillthrough.Enabled = false;
bDrillthrough.Enabled = false;
bParameters.Enabled = false;
}
else // assume no action
{
tbHyperlink.Enabled = bHyperlink.Enabled = false;
tbBookmarkLink.Enabled = bBookmarkLink.Enabled = false;
tbDrillthrough.Enabled = false;
bDrillthrough.Enabled = false;
bParameters.Enabled = false;
}
fAction = true;
}
private void tbAction_TextChanged(object sender, System.EventArgs e)
{
fAction = true;
}
private void tbHidden_TextChanged(object sender, System.EventArgs e)
{
fHidden = true;
}
private void cbToggle_SelectedIndexChanged(object sender, System.EventArgs e)
{
fToggle = true;
}
private void bDrillthrough_Click(object sender, System.EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = Strings.InteractivityCtl_bDrillthrough_Click_ReportFilesFilter;
ofd.FilterIndex = 1;
ofd.FileName = "*.rdl";
ofd.Title = Strings.InteractivityCtl_bDrillthrough_Click_ReportFilesTitle;
ofd.DefaultExt = "rdl";
ofd.AddExtension = true;
try
{
if (ofd.ShowDialog() == DialogResult.OK)
{
string file = Path.GetFileNameWithoutExtension(ofd.FileName);
tbDrillthrough.Text = file;
}
}
finally
{
ofd.Dispose();
}
}
private void bParameters_Click(object sender, System.EventArgs e)
{
DrillParametersDialog dpd = new DrillParametersDialog(this.tbDrillthrough.Text, _DrillParameters);
try
{
if (dpd.ShowDialog(this) != DialogResult.OK)
return;
tbDrillthrough.Text = dpd.DrillthroughReport;
_DrillParameters = dpd.DrillParameters;
fAction = true;
}
finally
{
dpd.Dispose();
}
}
private void bExpr_Click(object sender, System.EventArgs e)
{
Button b = sender as Button;
if (b == null)
return;
Control c = null;
switch (b.Tag as string)
{
case "bookmark":
c = tbBookmark;
break;
case "bookmarklink":
c = tbBookmarkLink;
break;
case "hyperlink":
c = tbHyperlink;
break;
case "visibility":
c = tbHidden;
break;
}
if (c == null)
return;
XmlNode sNode = _ReportItems[0];
DialogExprEditor ee = new DialogExprEditor(_Draw, c.Text, sNode);
try
{
DialogResult dr = ee.ShowDialog();
if (dr == DialogResult.OK)
{
c.Text = ee.Expression;
if ((string)(b.Tag) == "bookmark")
fBookmark = true;
else
fAction = true;
}
}
finally
{
ee.Dispose();
}
return;
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace DocuSign.eSign.Model
{
/// <summary>
/// SettingsMetadata
/// </summary>
[DataContract]
public partial class SettingsMetadata : IEquatable<SettingsMetadata>, IValidatableObject
{
public SettingsMetadata()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="SettingsMetadata" /> class.
/// </summary>
/// <param name="Is21CFRPart11">When set to **true**, indicates that this module is enabled on the account..</param>
/// <param name="Options">.</param>
/// <param name="Rights">.</param>
/// <param name="UiHint">.</param>
/// <param name="UiOrder">.</param>
/// <param name="UiType">.</param>
public SettingsMetadata(string Is21CFRPart11 = default(string), List<string> Options = default(List<string>), string Rights = default(string), string UiHint = default(string), string UiOrder = default(string), string UiType = default(string))
{
this.Is21CFRPart11 = Is21CFRPart11;
this.Options = Options;
this.Rights = Rights;
this.UiHint = UiHint;
this.UiOrder = UiOrder;
this.UiType = UiType;
}
/// <summary>
/// When set to **true**, indicates that this module is enabled on the account.
/// </summary>
/// <value>When set to **true**, indicates that this module is enabled on the account.</value>
[DataMember(Name="is21CFRPart11", EmitDefaultValue=false)]
public string Is21CFRPart11 { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="options", EmitDefaultValue=false)]
public List<string> Options { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="rights", EmitDefaultValue=false)]
public string Rights { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="uiHint", EmitDefaultValue=false)]
public string UiHint { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="uiOrder", EmitDefaultValue=false)]
public string UiOrder { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="uiType", EmitDefaultValue=false)]
public string UiType { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class SettingsMetadata {\n");
sb.Append(" Is21CFRPart11: ").Append(Is21CFRPart11).Append("\n");
sb.Append(" Options: ").Append(Options).Append("\n");
sb.Append(" Rights: ").Append(Rights).Append("\n");
sb.Append(" UiHint: ").Append(UiHint).Append("\n");
sb.Append(" UiOrder: ").Append(UiOrder).Append("\n");
sb.Append(" UiType: ").Append(UiType).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as SettingsMetadata);
}
/// <summary>
/// Returns true if SettingsMetadata instances are equal
/// </summary>
/// <param name="other">Instance of SettingsMetadata to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(SettingsMetadata other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Is21CFRPart11 == other.Is21CFRPart11 ||
this.Is21CFRPart11 != null &&
this.Is21CFRPart11.Equals(other.Is21CFRPart11)
) &&
(
this.Options == other.Options ||
this.Options != null &&
this.Options.SequenceEqual(other.Options)
) &&
(
this.Rights == other.Rights ||
this.Rights != null &&
this.Rights.Equals(other.Rights)
) &&
(
this.UiHint == other.UiHint ||
this.UiHint != null &&
this.UiHint.Equals(other.UiHint)
) &&
(
this.UiOrder == other.UiOrder ||
this.UiOrder != null &&
this.UiOrder.Equals(other.UiOrder)
) &&
(
this.UiType == other.UiType ||
this.UiType != null &&
this.UiType.Equals(other.UiType)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Is21CFRPart11 != null)
hash = hash * 59 + this.Is21CFRPart11.GetHashCode();
if (this.Options != null)
hash = hash * 59 + this.Options.GetHashCode();
if (this.Rights != null)
hash = hash * 59 + this.Rights.GetHashCode();
if (this.UiHint != null)
hash = hash * 59 + this.UiHint.GetHashCode();
if (this.UiOrder != null)
hash = hash * 59 + this.UiOrder.GetHashCode();
if (this.UiType != null)
hash = hash * 59 + this.UiType.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
//
// AudioCdRipper.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Threading;
using System.Runtime.InteropServices;
using Mono.Unix;
using Hyena;
using Banshee.Base;
using Banshee.Collection;
using Banshee.ServiceStack;
using Banshee.MediaEngine;
using Banshee.MediaProfiles;
using Banshee.Configuration.Schema;
namespace Banshee.GStreamer
{
public class AudioCdRipper : IAudioCdRipper
{
private HandleRef handle;
private string encoder_pipeline;
private string output_extension;
private string output_path;
private TrackInfo current_track;
private RipperProgressHandler progress_handler;
private RipperMimeTypeHandler mimetype_handler;
private RipperFinishedHandler finished_handler;
private RipperErrorHandler error_handler;
public event AudioCdRipperProgressHandler Progress;
public event AudioCdRipperTrackFinishedHandler TrackFinished;
public event AudioCdRipperErrorHandler Error;
public void Begin (string device, bool enableErrorCorrection)
{
try {
Profile profile = null;
ProfileConfiguration config = ServiceManager.MediaProfileManager.GetActiveProfileConfiguration ("cd-importing");
if (config != null) {
profile = config.Profile;
} else {
profile = ServiceManager.MediaProfileManager.GetProfileForMimeType ("audio/vorbis")
?? ServiceManager.MediaProfileManager.GetProfileForMimeType ("audio/flac");
if (profile != null) {
Log.InformationFormat ("Using default/fallback encoding profile: {0}", profile.Name);
ProfileConfiguration.SaveActiveProfile (profile, "cd-importing");
}
}
if (profile != null) {
encoder_pipeline = profile.Pipeline.GetProcessById ("gstreamer");
output_extension = profile.OutputFileExtension;
}
if (String.IsNullOrEmpty (encoder_pipeline)) {
throw new ApplicationException ();
}
Hyena.Log.InformationFormat ("Ripping using encoder profile `{0}' with pipeline: {1}", profile.Name, encoder_pipeline);
} catch (Exception e) {
throw new ApplicationException (Catalog.GetString ("Could not find an encoder for ripping."), e);
}
try {
int paranoia_mode = enableErrorCorrection ? 255 : 0;
handle = new HandleRef (this, br_new (device, paranoia_mode, encoder_pipeline));
progress_handler = new RipperProgressHandler (OnNativeProgress);
br_set_progress_callback (handle, progress_handler);
mimetype_handler = new RipperMimeTypeHandler (OnNativeMimeType);
br_set_mimetype_callback (handle, mimetype_handler);
finished_handler = new RipperFinishedHandler (OnNativeFinished);
br_set_finished_callback (handle, finished_handler);
error_handler = new RipperErrorHandler (OnNativeError);
br_set_error_callback (handle, error_handler);
} catch (Exception e) {
throw new ApplicationException (Catalog.GetString ("Could not create CD ripping driver."), e);
}
}
public void Finish ()
{
if (output_path != null) {
Banshee.IO.File.Delete (new SafeUri (output_path));
}
TrackReset ();
encoder_pipeline = null;
output_extension = null;
br_destroy (handle);
handle = new HandleRef (this, IntPtr.Zero);
}
public void Cancel ()
{
Finish ();
}
private void TrackReset ()
{
current_track = null;
output_path = null;
}
public void RipTrack (int trackIndex, TrackInfo track, SafeUri outputUri, out bool taggingSupported)
{
TrackReset ();
current_track = track;
using (TagList tags = new TagList (track)) {
output_path = String.Format ("{0}.{1}", outputUri.LocalPath, output_extension);
// Avoid overwriting an existing file
int i = 1;
while (Banshee.IO.File.Exists (new SafeUri (output_path))) {
output_path = String.Format ("{0} ({1}).{2}", outputUri.LocalPath, i++, output_extension);
}
Log.DebugFormat ("GStreamer ripping track {0} to {1}", trackIndex, output_path);
br_rip_track (handle, trackIndex + 1, output_path, tags.Handle, out taggingSupported);
}
}
protected virtual void OnProgress (TrackInfo track, TimeSpan ellapsedTime)
{
AudioCdRipperProgressHandler handler = Progress;
if (handler != null) {
handler (this, new AudioCdRipperProgressArgs (track, ellapsedTime, track.Duration));
}
}
protected virtual void OnTrackFinished (TrackInfo track, SafeUri outputUri)
{
AudioCdRipperTrackFinishedHandler handler = TrackFinished;
if (handler != null) {
handler (this, new AudioCdRipperTrackFinishedArgs (track, outputUri));
}
}
protected virtual void OnError (TrackInfo track, string message)
{
AudioCdRipperErrorHandler handler = Error;
if (handler != null) {
handler (this, new AudioCdRipperErrorArgs (track, message));
}
}
private void OnNativeProgress (IntPtr ripper, int mseconds)
{
OnProgress (current_track, TimeSpan.FromMilliseconds (mseconds));
}
private void OnNativeMimeType (IntPtr ripper, IntPtr mimetype)
{
if (mimetype != IntPtr.Zero && current_track != null) {
string type = GLib.Marshaller.Utf8PtrToString (mimetype);
if (type != null) {
string [] split = type.Split (';', '.', ' ', '\t');
if (split != null && split.Length > 0) {
current_track.MimeType = split[0].Trim ();
} else {
current_track.MimeType = type.Trim ();
}
}
}
}
private void OnNativeFinished (IntPtr ripper)
{
SafeUri uri = new SafeUri (output_path);
TrackInfo track = current_track;
TrackReset ();
OnTrackFinished (track, uri);
}
private void OnNativeError (IntPtr ripper, IntPtr error, IntPtr debug)
{
string error_message = GLib.Marshaller.Utf8PtrToString (error);
if (debug != IntPtr.Zero) {
string debug_string = GLib.Marshaller.Utf8PtrToString (debug);
if (!String.IsNullOrEmpty (debug_string)) {
error_message = String.Format ("{0}: {1}", error_message, debug_string);
}
}
OnError (current_track, error_message);
}
private delegate void RipperProgressHandler (IntPtr ripper, int mseconds);
private delegate void RipperMimeTypeHandler (IntPtr ripper, IntPtr mimetype);
private delegate void RipperFinishedHandler (IntPtr ripper);
private delegate void RipperErrorHandler (IntPtr ripper, IntPtr error, IntPtr debug);
[DllImport (PlayerEngine.LibBansheeLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr br_new (string device, int paranoia_mode, string encoder_pipeline);
[DllImport (PlayerEngine.LibBansheeLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern void br_destroy (HandleRef handle);
[DllImport (PlayerEngine.LibBansheeLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern void br_rip_track (HandleRef handle, int track_number, string output_path,
HandleRef tag_list, out bool tagging_supported);
[DllImport (PlayerEngine.LibBansheeLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern void br_set_progress_callback (HandleRef handle, RipperProgressHandler callback);
[DllImport (PlayerEngine.LibBansheeLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern void br_set_mimetype_callback (HandleRef handle, RipperMimeTypeHandler callback);
[DllImport (PlayerEngine.LibBansheeLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern void br_set_finished_callback (HandleRef handle, RipperFinishedHandler callback);
[DllImport (PlayerEngine.LibBansheeLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern void br_set_error_callback (HandleRef handle, RipperErrorHandler callback);
}
}
| |
using Signum.Engine;
using Signum.Engine.Engine;
using Signum.Engine.Linq;
using Signum.Engine.Maps;
using Signum.Engine.PostgresCatalog;
using Signum.Engine.SchemaInfoTables;
using Signum.Entities;
using Signum.Utilities;
using Signum.Utilities.ExpressionTrees;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace Signum.Engine
{
public static class Administrator
{
public static void TotalGeneration()
{
foreach (var db in Schema.Current.DatabaseNames())
{
Connector.Current.CleanDatabase(db);
SafeConsole.WriteColor(ConsoleColor.DarkGray, '.');
}
SqlPreCommandConcat totalScript = (SqlPreCommandConcat)Schema.Current.GenerationScipt()!;
foreach (SqlPreCommand command in totalScript.Commands)
{
command.ExecuteLeaves();
SafeConsole.WriteColor(ConsoleColor.DarkGray, '.');
}
}
public static string GenerateViewCodes(params string[] tableNames) => tableNames.ToString(tn => GenerateViewCode(tn), "\r\n\r\n");
public static string GenerateViewCode(string tableName) => GenerateViewCode(ObjectName.Parse(tableName, Schema.Current.Settings.IsPostgres));
public static string GenerateViewCode(ObjectName tableName)
{
using (OverrideDatabaseInSysViews(tableName.Schema.Database))
{
var columns =
(from t in Database.View<SysTables>()
where t.name == tableName.Name && t.Schema().name == tableName.Schema.Name
from c in t.Columns()
select new DiffColumn
{
Name = c.name,
DbType = new AbstractDbType(SysTablesSchema.ToSqlDbType(c.Type()!.name)),
UserTypeName = null,
PrimaryKey = t.Indices().Any(i => i.is_primary_key && i.IndexColumns().Any(ic => ic.column_id == c.column_id)),
Nullable = c.is_nullable,
}).ToList();
StringBuilder sb = new StringBuilder();
sb.AppendLine($@"[TableName(""{tableName.ToString()}"")]");
sb.AppendLine($"public class {tableName.Name} : IView");
sb.AppendLine(@"{");
foreach (var c in columns)
{
sb.Append(GenerateColumnCode(c).Indent(4));
}
sb.AppendLine(@"}");
return sb.ToString();
}
}
private static string GenerateColumnCode(DiffColumn c)
{
var type = CodeGeneration.CodeGenerator.Entities.GetValueType(c);
StringBuilder sb = new StringBuilder();
if (c.PrimaryKey)
sb.AppendLine("[ViewPrimaryKey]");
sb.AppendLine($"public {type.TypeName()}{(c.Nullable ? "?" : "")} {c.Name};");
return sb.ToString();
}
public static SqlPreCommand? TotalGenerationScript()
{
return Schema.Current.GenerationScipt();
}
public static SqlPreCommand? TotalSynchronizeScript(bool interactive = true, bool schemaOnly = false)
{
var command = Schema.Current.SynchronizationScript(interactive, schemaOnly);
if (command == null)
return null;
return SqlPreCommand.Combine(Spacing.Double,
new SqlPreCommandSimple(SynchronizerMessage.StartOfSyncScriptGeneratedOn0.NiceToString().FormatWith(DateTime.Now)),
Connector.Current.SqlBuilder.UseDatabase(),
command,
new SqlPreCommandSimple(SynchronizerMessage.EndOfSyncScript.NiceToString()));
}
public static void CreateTemporaryTable<T>()
where T : IView
{
if (!Transaction.HasTransaction)
throw new InvalidOperationException("You need to be inside of a transaction to create a Temporary table");
var view = Schema.Current.View<T>();
if (!view.Name.IsTemporal)
throw new InvalidOperationException($"Temporary tables should start with # (i.e. #myTable). Consider using {nameof(TableNameAttribute)}");
Connector.Current.SqlBuilder.CreateTableSql(view).ExecuteLeaves();
}
public static IDisposable TemporaryTable<T>() where T : IView
{
CreateTemporaryTable<T>();
return new Disposable(() => DropTemporaryTable<T>());
}
public static void DropTemporaryTable<T>()
where T : IView
{
if (!Transaction.HasTransaction)
throw new InvalidOperationException("You need to be inside of a transaction to create a Temporary table");
var view = Schema.Current.View<T>();
if (!view.Name.IsTemporal)
throw new InvalidOperationException($"Temporary tables should start with # (i.e. #myTable). Consider using {nameof(TableNameAttribute)}");
Connector.Current.SqlBuilder.DropTable(view.Name).ExecuteNonQuery();
}
public static void CreateTemporaryIndex<T>(Expression<Func<T, object>> fields, bool unique = false)
where T : IView
{
var view = Schema.Current.View<T>();
IColumn[] columns = IndexKeyColumns.Split(view, fields);
var index = unique ?
new UniqueTableIndex(view, columns) :
new TableIndex(view, columns);
Connector.Current.SqlBuilder.CreateIndex(index, checkUnique: null).ExecuteLeaves();
}
internal static readonly ThreadVariable<Func<ObjectName, ObjectName>?> registeredViewNameReplacer = Statics.ThreadVariable<Func<ObjectName, ObjectName>?>("overrideDatabase");
public static IDisposable OverrideViewNameReplacer(Func<ObjectName, ObjectName> replacer)
{
var old = registeredViewNameReplacer.Value;
registeredViewNameReplacer.Value = old == null ? replacer : n =>
{
var rep = replacer(n);
if (rep != n)
return rep;
return old!(n);
};
return new Disposable(() => registeredViewNameReplacer.Value = old);
}
public static ObjectName ReplaceViewName(ObjectName name)
{
var replacer = registeredViewNameReplacer.Value;
return replacer == null ? name : replacer(name);
}
public static IDisposable OverrideDatabaseInSysViews(DatabaseName? database)
{
return OverrideViewNameReplacer(n => n.Schema.Name == "sys" ? n.OnDatabase(database) : n);
}
public static bool ExistsTable<T>()
where T : Entity
{
return ExistsTable(Schema.Current.Table<T>());
}
public static bool ExistsTable(Type type)
{
return ExistsTable(Schema.Current.Table(type));
}
public static bool ExistsTable(ITable table)
{
SchemaName schema = table.Name.Schema;
if (Schema.Current.Settings.IsPostgres)
{
return (from t in Database.View<PgClass>()
join ns in Database.View<PgNamespace>() on t.relnamespace equals ns.oid
where t.relname == table.Name.Name && ns.nspname == schema.Name
select t).Any();
}
if (schema.Database != null && schema.Database.Server != null && !Database.View<SysServers>().Any(ss => ss.name == schema.Database!.Server!.Name))
return false;
if (schema.Database != null && !Database.View<SysDatabases>().Any(ss => ss.name == schema.Database!.Name))
return false;
using (schema.Database == null ? null : Administrator.OverrideDatabaseInSysViews(schema.Database))
{
return (from t in Database.View<SysTables>()
join s in Database.View<SysSchemas>() on t.schema_id equals s.schema_id
where t.name == table.Name.Name && s.name == schema.Name
select t).Any();
}
}
public static List<T> TryRetrieveAll<T>(Replacements replacements)
where T : Entity
{
return TryRetrieveAll(typeof(T), replacements).Cast<T>().ToList();
}
public static List<Entity> TryRetrieveAll(Type type, Replacements replacements)
{
Table table = Schema.Current.Table(type);
using (Synchronizer.UseOldTableName(table, replacements))
using (ExecutionMode.DisableCache())
{
if (ExistsTable(table))
return Database.RetrieveAll(type);
return new List<Entity>();
}
}
public static IDisposable SaveDisableIdentity<T>()
where T : Entity
{
Table table = Schema.Current.Table<T>();
return DisableIdentity(table);
}
public static IDisposable? DisableIdentity<T, V>(Expression<Func<T, MList<V>>> mListField)
where T : Entity
{
TableMList table = ((FieldMList)Schema.Current.Field(mListField)).TableMList;
return DisableIdentity(table);
}
public static bool IsIdentityBehaviourDisabled(ITable table)
{
return identityBehaviourDisabled.Value?.Contains(table) == true;
}
static ThreadVariable<ImmutableStack<ITable>?> identityBehaviourDisabled = Statics.ThreadVariable<ImmutableStack<ITable>?>("identityBehaviourOverride");
public static IDisposable DisableIdentity(ITable table, bool behaviourOnly = false)
{
if (!table.IdentityBehaviour)
throw new InvalidOperationException("Identity is false already");
var sqlBuilder = Connector.Current.SqlBuilder;
var oldValue = identityBehaviourDisabled.Value ?? ImmutableStack<ITable>.Empty;
identityBehaviourDisabled.Value = oldValue.Push(table);
if (table.PrimaryKey.Default == null && !sqlBuilder.IsPostgres && !behaviourOnly)
sqlBuilder.SetIdentityInsert(table.Name, true).ExecuteNonQuery();
return new Disposable(() =>
{
identityBehaviourDisabled.Value = oldValue.IsEmpty ? null : oldValue;
if (table.PrimaryKey.Default == null && !sqlBuilder.IsPostgres && !behaviourOnly)
sqlBuilder.SetIdentityInsert(table.Name, false).ExecuteNonQuery();
});
}
public static void SaveDisableIdentity<T>(T entities)
where T : Entity
{
using (Transaction tr = new Transaction())
using (Administrator.SaveDisableIdentity<T>())
{
Database.Save(entities);
tr.Commit();
}
}
public static void SaveListDisableIdentity<T>(IEnumerable<T> entities)
where T : Entity
{
using (Transaction tr = new Transaction())
using (Administrator.SaveDisableIdentity<T>())
{
Database.SaveList(entities);
tr.Commit();
}
}
public static int UnsafeDeleteDuplicates<E, K>(this IQueryable<E> query, Expression<Func<E, K>> key, string? message = null)
where E : Entity
{
return (from e in query
where !query.GroupBy(key).Select(gr => gr.Min(a => a.id)).Contains(e.Id)
select e).UnsafeDelete(message);
}
public static int UnsafeDeleteMListDuplicates<E, V, K>(this IQueryable<MListElement<E,V>> query, Expression<Func<MListElement<E, V>, K>> key, string? message = null)
where E : Entity
{
return (from e in query
where !query.GroupBy(key).Select(gr => gr.Min(a => a.RowId)).Contains(e.RowId)
select e).UnsafeDeleteMList(message);
}
public static SqlPreCommandSimple QueryPreCommand<T>(IQueryable<T> query)
{
var prov = ((DbQueryProvider)query.Provider);
return prov.Translate(query.Expression, tr => tr.MainCommand);
}
public static SqlPreCommandSimple? UnsafeDeletePreCommand<T>(IQueryable<T> query)
where T : Entity
{
if (!Administrator.ExistsTable<T>() || !query.Any())
return null;
var prov = ((DbQueryProvider)query.Provider);
using (PrimaryKeyExpression.PreferVariableName())
return prov.Delete<SqlPreCommandSimple>(query, cm => cm, removeSelectRowCount: true);
}
public static SqlPreCommandSimple? UnsafeDeletePreCommandMList<E, V>(Expression<Func<E, MList<V>>> mListProperty, IQueryable<MListElement<E, V>> query)
where E : Entity
{
if (!Administrator.ExistsTable(Schema.Current.TableMList(mListProperty)) || !query.Any())
return null;
var prov = ((DbQueryProvider)query.Provider);
using (PrimaryKeyExpression.PreferVariableName())
return prov.Delete<SqlPreCommandSimple>(query, cm => cm, removeSelectRowCount: true);
}
public static SqlPreCommandSimple UnsafeUpdatePartPreCommand(IUpdateable update)
{
var prov = ((DbQueryProvider)update.Query.Provider);
return prov.Update(update, sql => sql, removeSelectRowCount: true);
}
public static void UpdateToStrings<T>() where T : Entity, new()
{
UpdateToStrings(Database.Query<T>());
}
public static void UpdateToStrings<T>(IQueryable<T> query) where T : Entity, new()
{
SafeConsole.WriteLineColor(ConsoleColor.Cyan, "Saving toStr for {0}".FormatWith(typeof(T).TypeName()));
if (!query.Any())
return;
query.Select(a => a.Id).IntervalsOf(100).ProgressForeach(inter => inter.ToString(), (interva) =>
{
var list = query.Where(a => interva.Contains(a.Id)).ToList();
foreach (var item in list)
{
if (item.ToString() != item.toStr)
item.InDB().UnsafeUpdate()
.Set(a => a.toStr, a => item.ToString())
.Execute();
}
});
}
public static void UpdateToStrings<T>(Expression<Func<T, string?>> expression) where T : Entity, new()
{
UpdateToStrings(Database.Query<T>(), expression);
}
public static void UpdateToStrings<T>(IQueryable<T> query, Expression<Func<T, string?>> expression) where T : Entity, new()
{
SafeConsole.WaitRows("UnsafeUpdate toStr for {0}".FormatWith(typeof(T).TypeName()), () =>
query.UnsafeUpdate().Set(a => a.toStr, expression).Execute());
}
public static void UpdateToString<T>(T entity) where T : Entity, new()
{
entity.InDB().UnsafeUpdate()
.Set(e => e.toStr, e => entity.ToString())
.Execute();
}
public static void UpdateToString<T>(T entity, Expression<Func<T, string?>> expression) where T : Entity, new()
{
entity.InDB().UnsafeUpdate()
.Set(e => e.toStr, expression)
.Execute();
}
public static IDisposable PrepareForBatchLoadScope<T>(bool disableForeignKeys = true, bool disableMultipleIndexes = true, bool disableUniqueIndexes = false) where T : Entity
{
Table table = Schema.Current.Table(typeof(T));
return table.PrepareForBathLoadScope(disableForeignKeys, disableMultipleIndexes, disableUniqueIndexes);
}
static IDisposable PrepareForBathLoadScope(this Table table, bool disableForeignKeys, bool disableMultipleIndexes, bool disableUniqueIndexes)
{
IDisposable disp = PrepareTableForBatchLoadScope(table, disableForeignKeys, disableMultipleIndexes, disableUniqueIndexes);
var list = table.TablesMList().Select(rt => PrepareTableForBatchLoadScope(rt, disableForeignKeys, disableMultipleIndexes, disableUniqueIndexes)).ToList();
return new Disposable(() =>
{
disp.Dispose();
foreach (var d in list)
d.Dispose();
});
}
public static IDisposable PrepareTableForBatchLoadScope(ITable table, bool disableForeignKeys, bool disableMultipleIndexes, bool disableUniqueIndexes)
{
var sqlBuilder = Connector.Current.SqlBuilder;
SafeConsole.WriteColor(ConsoleColor.Magenta, table.Name + ":");
Action onDispose = () => SafeConsole.WriteColor(ConsoleColor.Magenta, table.Name + ":");
if (disableForeignKeys)
{
SafeConsole.WriteColor(ConsoleColor.DarkMagenta, " NOCHECK Foreign Keys");
Executor.ExecuteNonQuery("ALTER TABLE {0} NOCHECK CONSTRAINT ALL".FormatWith(table.Name));
onDispose += () =>
{
SafeConsole.WriteColor(ConsoleColor.DarkMagenta, " RE-CHECK Foreign Keys");
Executor.ExecuteNonQuery("ALTER TABLE {0} WITH CHECK CHECK CONSTRAINT ALL".FormatWith(table.Name));
};
}
if (disableMultipleIndexes)
{
var multiIndexes = GetIndixesNames(table, unique: false);
if (multiIndexes.Any())
{
SafeConsole.WriteColor(ConsoleColor.DarkMagenta, " DISABLE Multiple Indexes");
multiIndexes.Select(i => sqlBuilder.DisableIndex(table.Name, i)).Combine(Spacing.Simple)!.ExecuteLeaves();
Executor.ExecuteNonQuery(multiIndexes.ToString(i => "ALTER INDEX [{0}] ON {1} DISABLE".FormatWith(i, table.Name), "\r\n"));
onDispose += () =>
{
SafeConsole.WriteColor(ConsoleColor.DarkMagenta, " REBUILD Multiple Indexes");
multiIndexes.Select(i => sqlBuilder.RebuildIndex(table.Name, i)).Combine(Spacing.Simple)!.ExecuteLeaves();
};
}
}
if (disableUniqueIndexes)
{
var uniqueIndexes = GetIndixesNames(table, unique: true);
if (uniqueIndexes.Any())
{
SafeConsole.WriteColor(ConsoleColor.DarkMagenta, " DISABLE Unique Indexes");
uniqueIndexes.Select(i => sqlBuilder.DisableIndex(table.Name, i)).Combine(Spacing.Simple)!.ExecuteLeaves();
onDispose += () =>
{
SafeConsole.WriteColor(ConsoleColor.DarkMagenta, " REBUILD Unique Indexes");
uniqueIndexes.Select(i => sqlBuilder.RebuildIndex(table.Name, i)).Combine(Spacing.Simple)!.ExecuteLeaves();
};
}
}
Console.WriteLine();
onDispose += () => Console.WriteLine();
return new Disposable(onDispose);
}
public static void TruncateTable<T>() where T : Entity => TruncateTable(typeof(T));
public static void TruncateTable(Type type)
{
var table = Schema.Current.Table(type);
using (Transaction tr = new Transaction())
{
table.TablesMList().ToList().ForEach(mlist =>
{
TruncateTableSystemVersioning(mlist);
});
using (DropAndCreateIncommingForeignKeys(table))
TruncateTableSystemVersioning(table);
tr.Commit();
}
}
public static void TruncateTableSystemVersioning(ITable table)
{
var sqlBuilder = Connector.Current.SqlBuilder;
if(table.SystemVersioned == null)
sqlBuilder.TruncateTable(table.Name).ExecuteLeaves();
else
{
sqlBuilder.AlterTableDisableSystemVersioning(table.Name).ExecuteLeaves();
sqlBuilder.TruncateTable(table.Name).ExecuteLeaves();
sqlBuilder.TruncateTable(table.SystemVersioned.TableName).ExecuteLeaves();
sqlBuilder.AlterTableEnableSystemVersioning(table).ExecuteLeaves();
}
}
public static IDisposable DropAndCreateIncommingForeignKeys(Table table)
{
var sqlBuilder = Connector.Current.SqlBuilder;
var isPostgres = Schema.Current.Settings.IsPostgres;
var foreignKeys = Administrator.OverrideDatabaseInSysViews(table.Name.Schema.Database).Using(_ =>
(from targetTable in Database.View<SysTables>()
where targetTable.name == table.Name.Name && targetTable.Schema().name == table.Name.Schema.Name
from ifk in targetTable.IncommingForeignKeys()
let parentTable = ifk.ParentTable()
select new
{
Name = ifk.name,
ParentTable = new ObjectName(new SchemaName(table.Name.Schema.Database, parentTable.Schema().name, isPostgres), parentTable.name, isPostgres),
ParentColumn = parentTable.Columns().SingleEx(c => c.column_id == ifk.ForeignKeyColumns().SingleEx().parent_column_id).name,
}).ToList());
foreignKeys.ForEach(fk => sqlBuilder.AlterTableDropConstraint(fk.ParentTable!, fk.Name! /*CSBUG*/).ExecuteLeaves());
return new Disposable(() =>
{
foreignKeys.ToList().ForEach(fk => sqlBuilder.AlterTableAddConstraintForeignKey(fk.ParentTable!, fk.ParentColumn!, table.Name, table.PrimaryKey.Name)!.ExecuteLeaves());
});
}
public static IDisposable DisableUniqueIndex(UniqueTableIndex index)
{
var sqlBuilder = Connector.Current.SqlBuilder;
SafeConsole.WriteLineColor(ConsoleColor.DarkMagenta, " DISABLE Unique Index " + index.IndexName);
sqlBuilder.DisableIndex(index.Table.Name, index.IndexName).ExecuteLeaves();
return new Disposable(() =>
{
SafeConsole.WriteLineColor(ConsoleColor.DarkMagenta, " REBUILD Unique Index " + index.IndexName);
sqlBuilder.RebuildIndex(index.Table.Name, index.IndexName).ExecuteLeaves();
});
}
public static List<string> GetIndixesNames(this ITable table, bool unique)
{
using (OverrideDatabaseInSysViews(table.Name.Schema.Database))
{
return (from s in Database.View<SysSchemas>()
where s.name == table.Name.Schema.Name
from t in s.Tables()
where t.name == table.Name.Name
from i in t.Indices()
where i.is_unique == unique && !i.is_primary_key
select i.name).ToList();
}
}
public static void DropUniqueIndexes<T>() where T : Entity
{
var sqlBuilder = Connector.Current.SqlBuilder;
var table = Schema.Current.Table<T>();
var indexesNames = Administrator.GetIndixesNames(table, unique: true);
if (indexesNames.HasItems())
indexesNames.Select(n => sqlBuilder.DropIndex(table.Name, n)).Combine(Spacing.Simple)!.ExecuteLeaves();
}
public static void MoveAllForeignKeys<T>(Lite<T> fromEntity, Lite<T> toEntity, Func<ITable, IColumn, bool>? shouldMove = null)
where T : Entity
{
using (Transaction tr = new Transaction())
{
MoveAllForeignKeysPrivate<T>(fromEntity, toEntity, shouldMove).Select(a => a.UpdateScript).Combine(Spacing.Double)!.ExecuteLeaves();
tr.Commit();
}
}
public static SqlPreCommand? MoveAllForeignKeysScript<T>(Lite<T> fromEntity, Lite<T> toEntity, Func<ITable, IColumn, bool>? shouldMove = null)
where T : Entity
{
return MoveAllForeignKeysPrivate<T>(fromEntity, toEntity, shouldMove).Select(a => a.UpdateScript).Combine(Spacing.Double);
}
public static void MoveAllForeignKeysConsole<T>(Lite<T> fromEntity, Lite<T> toEntity, Func<ITable, IColumn, bool>? shouldMove = null)
where T : Entity
{
var tuples = MoveAllForeignKeysPrivate<T>(fromEntity, toEntity, shouldMove);
foreach (var t in tuples)
{
SafeConsole.WaitRows("{0}.{1}".FormatWith(t.ColumnTable.Table.Name.Name, t.ColumnTable.Column.Name), () => t.UpdateScript.ExecuteNonQuery());
}
}
class ColumnTableScript
{
public ColumnTable ColumnTable;
public SqlPreCommandSimple UpdateScript;
public ColumnTableScript(ColumnTable columnTable, SqlPreCommandSimple updateScript)
{
ColumnTable = columnTable;
UpdateScript = updateScript;
}
}
static List<ColumnTableScript> MoveAllForeignKeysPrivate<T>(Lite<T> fromEntity, Lite<T> toEntity, Func<ITable, IColumn, bool>? shouldMove)
where T : Entity
{
if (fromEntity.GetType() != toEntity.GetType())
throw new ArgumentException("fromEntity and toEntity should have the same type");
if (fromEntity.Is(toEntity))
throw new ArgumentException("fromEntity and toEntity should not be the same ");
Schema s = Schema.Current;
Table refTable = s.Table(typeof(T));
List<ColumnTable> columns = GetColumnTables(s, refTable);
if (shouldMove != null)
columns = columns.Where(p => shouldMove!(p.Table, p.Column)).ToList();
var isPostgres = Schema.Current.Settings.IsPostgres;
var pb = Connector.Current.ParameterBuilder;
return columns.Select(ct => new ColumnTableScript(ct, new SqlPreCommandSimple("UPDATE {0}\r\nSET {1} = @toEntity\r\nWHERE {1} = @fromEntity".FormatWith(ct.Table.Name, ct.Column.Name.SqlEscape(isPostgres)), new List<DbParameter>
{
pb.CreateReferenceParameter("@fromEntity", fromEntity.Id, ct.Column),
pb.CreateReferenceParameter("@toEntity", toEntity.Id, ct.Column),
}))).ToList();
}
class ColumnTable
{
public ITable Table;
public IColumn Column;
public ColumnTable(ITable table, IColumn column)
{
Table = table;
Column = column;
}
}
static ConcurrentDictionary<Table, List<ColumnTable>> columns = new ConcurrentDictionary<Table, List<ColumnTable>>();
static List<ColumnTable> GetColumnTables(Schema schema, Table refTable)
{
return columns.GetOrAdd(refTable, rt =>
{
return (from t in schema.GetDatabaseTables()
from c in t.Columns.Values
where c.ReferenceTable == rt
select new ColumnTable(t,c))
.ToList();
});
}
public static T GetSetTicks<T>(this T entity) where T : Entity
{
entity.Ticks = entity.InDB(e => e.Ticks);
return entity;
}
public static SqlPreCommand DeleteWhereScript(Table table, IColumn column, PrimaryKey id)
{
if (table.TablesMList().Any())
throw new InvalidOperationException($"DeleteWhereScript can not be used for {table.Type.Name} because contains MLists");
if(id.VariableName.HasText())
return new SqlPreCommandSimple("DELETE FROM {0} WHERE {1} = {2};".FormatWith(table.Name, column.Name, id.VariableName));
var param = Connector.Current.ParameterBuilder.CreateReferenceParameter("@id", id, column);
return new SqlPreCommandSimple("DELETE FROM {0} WHERE {1} = {2}:".FormatWith(table.Name, column.Name, param.ParameterName), new List<DbParameter> { param });
}
public static SqlPreCommand DeleteWhereScript<T, R>(Expression<Func<T, R>> field, R value)
where T : Entity
where R : Entity
{
var table = Schema.Current.Table<T>();
var column = (IColumn)Schema.Current.Field(field);
return DeleteWhereScript(table, column, value.Id);
}
}
}
| |
// Copyright 2014, 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: Chris Seeley (https://github.com/Narwalter)
using Google.Api.Ads.Common.Lib;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Google.Api.Ads.Dfp.Lib {
/// <summary>
/// Lists all the services available through this library.
/// </summary>
public partial class DfpService : AdsService {
/// <summary>
/// All the services available in v201408.
/// </summary>
public class v201408 {
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/ActivityGroupService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ActivityGroupService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/ActivityService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ActivityService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/AdRuleService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature AdRuleService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/BaseRateService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature BaseRateService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/ContactService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ContactService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/AudienceSegmentService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature AudienceSegmentService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/CompanyService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature CompanyService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/ContentService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ContentService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/ContentMetadataKeyHierarchyService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ContentMetadataKeyHierarchyService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/CreativeService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CreativeService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/CreativeSetService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CreativeSetService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/CreativeTemplateService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CreativeTemplateService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/CreativeWrapperService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CreativeWrapperService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/CustomFieldService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CustomFieldService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/CustomTargetingService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CustomTargetingService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/ExchangeRateService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ExchangeRateService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/ForecastService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ForecastService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/InventoryService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature InventoryService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/LabelService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LabelService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/LineItemTemplateService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LineItemTemplateService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/LineItemService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LineItemService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/LineItemCreativeAssociationService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LineItemCreativeAssociationService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/LiveStreamEventService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LiveStreamEventService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/NetworkService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature NetworkService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/OrderService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature OrderService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/PlacementService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature PlacementService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/PremiumRateService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature PremiumRateService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/ProductService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature ProductService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/ProductTemplateService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature ProductTemplateService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/ProposalService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature ProposalService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/ProposalLineItemService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature ProposalLineItemService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/PublisherQueryLanguageService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature PublisherQueryLanguageService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/RateCardService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature RateCardService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/ReconciliationOrderReportService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ReconciliationOrderReportService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/ReconciliationReportService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ReconciliationReportService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/ReconciliationReportRowService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ReconciliationReportRowService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/ReportService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ReportService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/SuggestedAdUnitService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature SuggestedAdUnitService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/TeamService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature TeamService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/UserService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature UserService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/UserTeamAssociationService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature UserTeamAssociationService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201408/WorkflowRequestService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature WorkflowRequestService;
/// <summary>
/// Factory type for v201408 services.
/// </summary>
public static readonly Type factoryType = typeof(DfpServiceFactory);
/// <summary>
/// Static constructor to initialize the service constants.
/// </summary>
static v201408() {
ActivityGroupService = DfpService.MakeServiceSignature("v201408", "ActivityGroupService");
ActivityService = DfpService.MakeServiceSignature("v201408", "ActivityService");
AdRuleService = DfpService.MakeServiceSignature("v201408", "AdRuleService");
BaseRateService = DfpService.MakeServiceSignature("v201408", "BaseRateService");
ContactService = DfpService.MakeServiceSignature("v201408", "ContactService");
AudienceSegmentService = DfpService.MakeServiceSignature("v201408",
"AudienceSegmentService");
CompanyService = DfpService.MakeServiceSignature("v201408", "CompanyService");
ContentService = DfpService.MakeServiceSignature("v201408", "ContentService");
ContentMetadataKeyHierarchyService = DfpService.MakeServiceSignature("v201408",
"ContentMetadataKeyHierarchyService");
CreativeService = DfpService.MakeServiceSignature("v201408", "CreativeService");
CreativeSetService = DfpService.MakeServiceSignature("v201408", "CreativeSetService");
CreativeTemplateService = DfpService.MakeServiceSignature("v201408",
"CreativeTemplateService");
CreativeWrapperService = DfpService.MakeServiceSignature("v201408",
"CreativeWrapperService");
CustomTargetingService = DfpService.MakeServiceSignature("v201408",
"CustomTargetingService");
CustomFieldService = DfpService.MakeServiceSignature("v201408",
"CustomFieldService");
ExchangeRateService = DfpService.MakeServiceSignature("v201408", "ExchangeRateService");
ForecastService = DfpService.MakeServiceSignature("v201408", "ForecastService");
InventoryService = DfpService.MakeServiceSignature("v201408", "InventoryService");
LabelService = DfpService.MakeServiceSignature("v201408", "LabelService");
LineItemTemplateService = DfpService.MakeServiceSignature("v201408",
"LineItemTemplateService");
LineItemService = DfpService.MakeServiceSignature("v201408", "LineItemService");
LineItemCreativeAssociationService =
DfpService.MakeServiceSignature("v201408", "LineItemCreativeAssociationService");
LiveStreamEventService = DfpService.MakeServiceSignature("v201408",
"LiveStreamEventService");
NetworkService = DfpService.MakeServiceSignature("v201408", "NetworkService");
OrderService = DfpService.MakeServiceSignature("v201408", "OrderService");
PlacementService = DfpService.MakeServiceSignature("v201408", "PlacementService");
PremiumRateService = DfpService.MakeServiceSignature("v201408", "PremiumRateService");
ProductService = DfpService.MakeServiceSignature("v201408", "ProductService");
ProductTemplateService = DfpService.MakeServiceSignature("v201408",
"ProductTemplateService");
ProposalService = DfpService.MakeServiceSignature("v201408", "ProposalService");
ProposalLineItemService = DfpService.MakeServiceSignature("v201408",
"ProposalLineItemService");
PublisherQueryLanguageService = DfpService.MakeServiceSignature("v201408",
"PublisherQueryLanguageService");
RateCardService = DfpService.MakeServiceSignature("v201408", "RateCardService");
ReconciliationOrderReportService = DfpService.MakeServiceSignature("v201408",
"ReconciliationOrderReportService");
ReconciliationReportService = DfpService.MakeServiceSignature("v201408",
"ReconciliationReportService");
ReconciliationReportRowService = DfpService.MakeServiceSignature("v201408",
"ReconciliationReportRowService");
ReportService = DfpService.MakeServiceSignature("v201408", "ReportService");
SuggestedAdUnitService = DfpService.MakeServiceSignature("v201408",
"SuggestedAdUnitService");
TeamService = DfpService.MakeServiceSignature("v201408", "TeamService");
UserService = DfpService.MakeServiceSignature("v201408", "UserService");
UserTeamAssociationService = DfpService.MakeServiceSignature("v201408",
"UserTeamAssociationService");
WorkflowRequestService = DfpService.MakeServiceSignature("v201408",
"WorkflowRequestService");
}
}
}
}
| |
// 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.Text;
using System.Threading.Tasks;
using System.IO.Pipelines.Text.Primitives;
using Xunit;
using System.Text.Formatting;
namespace System.IO.Pipelines.Tests
{
public class WritableBufferFacts
{
[Fact]
public async Task CanWriteNothingToBuffer()
{
using (var memoryPool = new MemoryPool())
{
var pipe = new Pipe(memoryPool);
var buffer = pipe.Writer.Alloc();
buffer.Advance(0); // doing nothing, the hard way
await buffer.FlushAsync();
}
}
[Fact]
public void ThrowsOnAdvanceWithNoMemory()
{
using (var memoryPool = new MemoryPool())
{
var pipe = new Pipe(memoryPool);
var buffer = pipe.Writer.Alloc();
var exception = Assert.Throws<InvalidOperationException>(() => buffer.Advance(1));
Assert.Equal("Can't advance without buffer allocated", exception.Message);
}
}
[Fact]
public void ThrowsOnAdvanceOverMemorySize()
{
using (var memoryPool = new MemoryPool())
{
var pipe = new Pipe(memoryPool);
var buffer = pipe.Writer.Alloc(1);
var exception = Assert.Throws<InvalidOperationException>(() => buffer.Advance(buffer.Buffer.Length + 1));
Assert.Equal("Can't advance past buffer size", exception.Message);
}
}
[Theory]
[InlineData(1, "1")]
[InlineData(20, "20")]
[InlineData(300, "300")]
[InlineData(4000, "4000")]
[InlineData(500000, "500000")]
[InlineData(60000000000000000, "60000000000000000")]
public async Task CanWriteUInt64ToBuffer(ulong value, string valueAsString)
{
using (var memoryPool = new MemoryPool())
{
var pipe = new Pipe(memoryPool);
var buffer = pipe.Writer.Alloc();
buffer.Append(value, SymbolTable.InvariantUtf8);
await buffer.FlushAsync();
var result = await pipe.Reader.ReadAsync();
var inputBuffer = result.Buffer;
Assert.Equal(valueAsString, inputBuffer.GetUtf8String());
}
}
[Theory]
[InlineData(5)]
[InlineData(50)]
[InlineData(500)]
[InlineData(5000)]
[InlineData(50000)]
public async Task WriteLargeDataBinary(int length)
{
byte[] data = new byte[length];
new Random(length).NextBytes(data);
using (var memoryPool = new MemoryPool())
{
var pipe = new Pipe(memoryPool);
var output = pipe.Writer.Alloc();
output.Write(data);
var foo = output.Buffer.IsEmpty; // trying to see if .Memory breaks
await output.FlushAsync();
pipe.Writer.Complete();
int offset = 0;
while (true)
{
var result = await pipe.Reader.ReadAsync();
var input = result.Buffer;
if (input.Length == 0) break;
Assert.True(input.EqualsTo(new Span<byte>(data, offset, input.Length)));
offset += input.Length;
pipe.Advance(input.End);
}
Assert.Equal(data.Length, offset);
}
}
[Theory]
[InlineData(5)]
[InlineData(50)]
[InlineData(500)]
[InlineData(5000)]
[InlineData(50000)]
public async Task WriteLargeDataTextUtf8(int length)
{
string data = new string('#', length);
FillRandomStringData(data, length);
using (var memoryPool = new MemoryPool())
{
var pipe = new Pipe(memoryPool);
var output = pipe.Writer.Alloc();
output.Append(data, SymbolTable.InvariantUtf8);
var foo = output.Buffer.IsEmpty; // trying to see if .Memory breaks
await output.FlushAsync();
pipe.Writer.Complete();
int offset = 0;
while (true)
{
var result = await pipe.Reader.ReadAsync();
var input = result.Buffer;
if (input.Length == 0) break;
string s = ReadableBufferExtensions.GetUtf8String(input);
Assert.Equal(data.Substring(offset, input.Length), s);
offset += input.Length;
pipe.Advance(input.End);
}
Assert.Equal(data.Length, offset);
}
}
[Theory]
[InlineData(5)]
[InlineData(50)]
[InlineData(500)]
[InlineData(5000)]
[InlineData(50000)]
public async Task WriteLargeDataTextAscii(int length)
{
string data = new string('#', length);
FillRandomStringData(data, length);
using (var memoryPool = new MemoryPool())
{
var pipe = new Pipe(memoryPool);
var output = pipe.Writer.Alloc();
output.Append(data, SymbolTable.InvariantUtf8);
var foo = output.Buffer.IsEmpty; // trying to see if .Memory breaks
await output.FlushAsync();
pipe.Writer.Complete();
int offset = 0;
while (true)
{
var result = await pipe.Reader.ReadAsync();
var input = result.Buffer;
if (input.Length == 0) break;
string s = ReadableBufferExtensions.GetAsciiString(input);
Assert.Equal(data.Substring(offset, input.Length), s);
offset += input.Length;
pipe.Advance(input.End);
}
Assert.Equal(data.Length, offset);
}
}
private unsafe void FillRandomStringData(string data, int seed)
{
Random rand = new Random(seed);
fixed (char* c = data)
{
for (int i = 0; i < data.Length; i++)
{
c[i] = (char)(rand.Next(127) + 1); // want range 1-127
}
}
}
[Fact]
public void CanReReadDataThatHasNotBeenCommitted_SmallData()
{
using (var memoryPool = new MemoryPool())
{
var pipe = new Pipe(memoryPool);
var output = pipe.Writer.Alloc();
Assert.True(output.AsReadableBuffer().IsEmpty);
Assert.Equal(0, output.AsReadableBuffer().Length);
output.Append("hello world", SymbolTable.InvariantUtf8);
var readable = output.AsReadableBuffer();
// check that looks about right
Assert.False(readable.IsEmpty);
Assert.Equal(11, readable.Length);
Assert.True(readable.EqualsTo(Encoding.UTF8.GetBytes("hello world")));
Assert.True(readable.Slice(1, 3).EqualsTo(Encoding.UTF8.GetBytes("ell")));
// check it all works after we write more
output.Append("more data", SymbolTable.InvariantUtf8);
// note that the snapshotted readable should not have changed by this
Assert.False(readable.IsEmpty);
Assert.Equal(11, readable.Length);
Assert.True(readable.EqualsTo(Encoding.UTF8.GetBytes("hello world")));
Assert.True(readable.Slice(1, 3).EqualsTo(Encoding.UTF8.GetBytes("ell")));
// if we fetch it again, we can see everything
readable = output.AsReadableBuffer();
Assert.False(readable.IsEmpty);
Assert.Equal(20, readable.Length);
Assert.True(readable.EqualsTo(Encoding.UTF8.GetBytes("hello worldmore data")));
}
}
[Fact]
public void CanReReadDataThatHasNotBeenCommitted_LargeData()
{
using (var memoryPool = new MemoryPool())
{
var pipe = new Pipe(memoryPool);
var output = pipe.Writer.Alloc();
byte[] predictablyGibberish = new byte[512];
const int SEED = 1235412;
Random random = new Random(SEED);
for (int i = 0; i < 50; i++)
{
for (int j = 0; j < predictablyGibberish.Length; j++)
{
// doing it this way to be 100% sure about repeating the PRNG order
predictablyGibberish[j] = (byte)random.Next(0, 256);
}
output.Write(predictablyGibberish);
}
var readable = output.AsReadableBuffer();
Assert.False(readable.IsSingleSpan);
Assert.False(readable.IsEmpty);
Assert.Equal(50 * 512, readable.Length);
random = new Random(SEED);
int correctCount = 0;
foreach (var memory in readable)
{
var span = memory.Span;
for (int i = 0; i < span.Length; i++)
{
if (span[i] == (byte)random.Next(0, 256)) correctCount++;
}
}
Assert.Equal(50 * 512, correctCount);
}
}
[Fact]
public async Task CanAppendSelfWhileEmpty()
{ // not really an expectation; just an accepted caveat
using (var memoryPool = new MemoryPool())
{
var pipe = new Pipe(memoryPool);
var output = pipe.Writer.Alloc();
var readable = output.AsReadableBuffer();
output.Append(readable);
Assert.Equal(0, output.AsReadableBuffer().Length);
await output.FlushAsync();
}
}
[Fact]
public async Task CanAppendSelfWhileNotEmpty()
{
byte[] chunk = new byte[512];
new Random().NextBytes(chunk);
using (var memoryPool = new MemoryPool())
{
var pipe = new Pipe(memoryPool);
var output = pipe.Writer.Alloc();
for (int i = 0; i < 20; i++)
{
output.Write(chunk);
}
var readable = output.AsReadableBuffer();
Assert.Equal(512 * 20, readable.Length);
output.Append(readable);
Assert.Equal(512 * 20, readable.Length);
readable = output.AsReadableBuffer();
Assert.Equal(2 * 512 * 20, readable.Length);
await output.FlushAsync();
}
}
[Fact]
public void EnsureMoreThanPoolBlockSizeThrows()
{
using (var factory = new PipeFactory())
{
var pipe = factory.Create();
var buffer = pipe.Writer.Alloc();
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.Ensure(8192));
}
}
public static IEnumerable<object[]> HexNumbers
{
get
{
yield return new object[] { 0, "0" };
for (int i = 1; i < 50; i++)
{
yield return new object[] { i, i.ToString("x2").TrimStart('0') };
}
}
}
[Theory]
[MemberData(nameof(HexNumbers))]
public void WriteHex(int value, string hex)
{
using (var factory = new PipeFactory())
{
var pipe = factory.Create();
var buffer = pipe.Writer.Alloc();
buffer.Append(value, SymbolTable.InvariantUtf8, 'x');
Assert.Equal(hex, buffer.AsReadableBuffer().GetAsciiString());
}
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Framework;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.ArcMapUI;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS;
namespace DesktopAutomationCS
{
public partial class Form1 : Form
{
private IApplication m_application;
//Application removed event
private IAppROTEvents_Event m_appROTEvent;
private int m_appHWnd = 0;
//Retrieve the hWnd of the active popup/modal dialog of an owner window
[System.Runtime.InteropServices.DllImport("user32")]
private static extern int GetLastActivePopup(int hwndOwnder);
public Form1()
{
ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.EngineOrDesktop);
InitializeComponent();
//Preselect option
cboApps.SelectedIndex = 0;
}
private void btnStartApp_Click(object sender, EventArgs e)
{
IDocument doc = null;
try
{
this.Cursor = Cursors.WaitCursor;
switch (cboApps.SelectedItem.ToString())
{
case "ArcMap":
doc = new ESRI.ArcGIS.ArcMapUI.MxDocumentClass();
break;
case "ArcScene":
doc = new ESRI.ArcGIS.ArcScene.SxDocumentClass();
break;
case "ArcGlobe":
doc = new ESRI.ArcGIS.ArcGlobe.GMxDocumentClass();
break;
}
}
catch { } //Fail if you haven't installed the target application
finally
{
this.Cursor = Cursors.Default;
}
if (doc != null)
{
//Advanced (AppROT event): Handle manual shutdown, comment out if not needed
m_appROTEvent = new AppROTClass();
m_appROTEvent.AppRemoved += new IAppROTEvents_AppRemovedEventHandler(m_appROTEvent_AppRemoved);
//Get a reference of the application and make it visible
m_application = doc.Parent;
m_application.Visible = true;
m_appHWnd = m_application.hWnd;
//Enable/disable controls accordingly
txtShapeFilePath.Enabled = true;
btnShutdown.Enabled = true;
btnDrive.Enabled = ShouldEnableAddLayer;
cboApps.Enabled = btnStartApp.Enabled = false;
}
else
{
m_appROTEvent = null;
m_application = null;
txtShapeFilePath.Enabled = false;
btnShutdown.Enabled = btnDrive.Enabled = false;
cboApps.Enabled = btnStartApp.Enabled = true;
}
}
private void btnShutdown_Click(object sender, EventArgs e)
{
if (m_application != null)
{
//Try to close any modal dialogs by sending the Escape key
//It doesn't handle the followings:
//- VBA is up and has a modal dialog
//- Modal dialog doesn't close with the Escape key
Microsoft.VisualBasic.Interaction.AppActivate(m_application.Caption);
int nestModalHwnd = 0;
while ((nestModalHwnd = GetLastActivePopup(m_application.hWnd)) != m_application.hWnd)
{
SendKeys.SendWait("{ESC}");
}
//Manage document dirty flag - abandon changes
IDocumentDirty2 docDirtyFlag = (IDocumentDirty2)m_application.Document;
docDirtyFlag.SetClean();
//Stop listening before exiting
m_appROTEvent.AppRemoved -= new IAppROTEvents_AppRemovedEventHandler(m_appROTEvent_AppRemoved);
m_appROTEvent = null;
//Exit
m_application.Shutdown();
m_application = null;
//Reset UI for next automation
txtShapeFilePath.Enabled = false;
btnShutdown.Enabled = btnDrive.Enabled = false;
cboApps.Enabled = btnStartApp.Enabled = true;
}
}
private void btnDrive_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
try
{
IObjectFactory objFactory = m_application as IObjectFactory;
//Use reflection to get ClsID of ShapefileWorkspaceFactory
Type shpWkspFactType = typeof(ShapefileWorkspaceFactoryClass);
string typeClsID = shpWkspFactType.GUID.ToString("B");
string shapeFile = System.IO.Path.GetFileNameWithoutExtension(txtShapeFilePath.Text);
string fileFolder = System.IO.Path.GetDirectoryName(txtShapeFilePath.Text);
IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)objFactory.Create(typeClsID);
IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(fileFolder, 0); //(@"C:\data\test", 0);
//Create the layer
IFeatureLayer featureLayer = (IFeatureLayer)objFactory.Create("esriCarto.FeatureLayer");
featureLayer.FeatureClass = featureWorkspace.OpenFeatureClass(shapeFile); // ("worldgrid");
featureLayer.Name = featureLayer.FeatureClass.AliasName;
//Add the layer to document
IBasicDocument document = (IBasicDocument)m_application.Document;
document.AddLayer(featureLayer);
document.UpdateContents();
}
catch { } //Or make sure it is a valid shp file first
this.Cursor = Cursors.Default;
}
private void txtShapeFilePath_TextChanged(object sender, EventArgs e)
{
btnDrive.Enabled = ShouldEnableAddLayer;
}
private bool ShouldEnableAddLayer
{
get
{
//Only allow .shp file
if (System.IO.File.Exists(txtShapeFilePath.Text))
{
return (System.IO.Path.GetExtension(txtShapeFilePath.Text).ToLower() == ".shp");
}
else
{
return false;
}
}
}
#region "Handle the case when the application is shutdown by user manually"
void m_appROTEvent_AppRemoved(AppRef pApp)
{
//Application manually shuts down. Stop listening
if (pApp.hWnd == m_appHWnd) //compare by hwnd
{
m_appROTEvent.AppRemoved -= new IAppROTEvents_AppRemovedEventHandler(m_appROTEvent_AppRemoved);
m_appROTEvent = null;
m_application = null;
m_appHWnd = 0;
//Reset UI has to be in the form UI thread of this application,
//not the AppROT thread;
if (this.InvokeRequired) //i.e. not on the right thread
{
this.BeginInvoke(new IAppROTEvents_AppRemovedEventHandler(AppRemovedResetUI), pApp);
}
else
{
AppRemovedResetUI(pApp); //call directly
}
}
}
void AppRemovedResetUI(AppRef pApp)
{
txtShapeFilePath.Enabled = false;
btnShutdown.Enabled = btnDrive.Enabled = false;
cboApps.Enabled = btnStartApp.Enabled = true;
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
//Clean up
if (m_appROTEvent != null)
{
m_appROTEvent.AppRemoved -= new IAppROTEvents_AppRemovedEventHandler(m_appROTEvent_AppRemoved);
m_appROTEvent = null;
}
}
#endregion
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 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.
// ***********************************************************************
#if PARALLEL
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Threading;
using NUnit.Framework.Interfaces;
namespace NUnit.Framework.Internal.Execution
{
/// <summary>
/// Summary description for EventQueueTests.
/// </summary>
[TestFixture]
public class EventQueueTests
{
private static readonly Event[] events =
{
new TestStartedEvent(null),
new TestOutputEvent(null),
new TestStartedEvent(null),
new TestFinishedEvent(null),
new TestStartedEvent(null),
new TestOutputEvent(null),
new TestFinishedEvent(null),
new TestFinishedEvent(null),
};
private static void EnqueueEvents(EventQueue q)
{
foreach (Event e in events)
q.Enqueue(e);
}
private static void SendEvents(ITestListener listener)
{
foreach (Event e in events)
e.Send(listener);
}
private static void VerifyQueue(EventQueue q)
{
for (int index = 0; index < events.Length; index++)
{
Event e = q.Dequeue(false);
Assert.AreEqual(events[index].GetType(), e.GetType(), string.Format("Event {0}", index));
}
}
private static void StartPump(EventPump pump, int waitTime)
{
pump.Start();
WaitForPumpToStart(pump, waitTime);
}
private static void StopPump(EventPump pump, int waitTime)
{
pump.Stop();
WaitForPumpToStop(pump, waitTime);
}
private static void WaitForPumpToStart(EventPump pump, int waitTime)
{
while (waitTime > 0 && pump.PumpState != EventPumpState.Pumping)
{
Thread.Sleep(100);
waitTime -= 100;
}
}
private static void WaitForPumpToStop(EventPump pump, int waitTime)
{
while (waitTime > 0 && pump.PumpState != EventPumpState.Stopped)
{
Thread.Sleep(100);
waitTime -= 100;
}
}
#region EventQueue Tests
[Test]
public void QueueEvents()
{
EventQueue q = new EventQueue();
EnqueueEvents(q);
VerifyQueue(q);
}
[Test]
public void DequeueEmpty()
{
EventQueue q = new EventQueue();
Assert.IsNull(q.Dequeue(false));
}
[TestFixture]
public class DequeueBlocking_StopTest : ProducerConsumerTest
{
private EventQueue q;
private volatile int receivedEvents;
[Test]
[Timeout(1000)]
public void DequeueBlocking_Stop()
{
this.q = new EventQueue();
this.receivedEvents = 0;
this.RunProducerConsumer();
Assert.AreEqual(events.Length + 1, this.receivedEvents);
}
protected override void Producer()
{
EnqueueEvents(this.q);
while (this.receivedEvents < events.Length)
Thread.Sleep(30);
this.q.Stop();
}
protected override void Consumer()
{
Event e;
do
{
e = this.q.Dequeue(true);
this.receivedEvents++;
Thread.MemoryBarrier();
}
while (e != null);
}
}
[TestFixture]
public class SetWaitHandle_Enqueue_AsynchronousTest : ProducerConsumerTest
{
private EventQueue q;
private volatile bool afterEnqueue;
[Test]
[Timeout(1000)]
public void SetWaitHandle_Enqueue_Asynchronous()
{
using (AutoResetEvent waitHandle = new AutoResetEvent(false))
{
this.q = new EventQueue();
this.afterEnqueue = false;
this.RunProducerConsumer();
}
}
protected override void Producer()
{
Event asynchronousEvent = new TestStartedEvent(new TestSuite("Dummy"));
this.q.Enqueue(asynchronousEvent);
this.afterEnqueue = true;
Thread.MemoryBarrier();
}
protected override void Consumer()
{
this.q.Dequeue(true);
Thread.Sleep(30);
Assert.IsTrue(this.afterEnqueue);
}
}
#endregion
#region QueuingEventListener Tests
[Test]
public void SendEvents()
{
QueuingEventListener el = new QueuingEventListener();
SendEvents(el);
VerifyQueue(el.Events);
}
#endregion
#region EventPump Tests
[Test]
public void StartAndStopPumpOnEmptyQueue()
{
using (EventPump pump = new EventPump(TestListener.NULL, new EventQueue()))
{
pump.Name = "StartAndStopPumpOnEmptyQueue";
StartPump(pump, 1000);
Assert.That(pump.PumpState, Is.EqualTo(EventPumpState.Pumping));
StopPump(pump, 1000);
Assert.That(pump.PumpState, Is.EqualTo(EventPumpState.Stopped));
}
}
[Test]
[Timeout(3000)]
public void PumpEvents()
{
EventQueue q = new EventQueue();
QueuingEventListener el = new QueuingEventListener();
using (EventPump pump = new EventPump(el, q))
{
pump.Name = "PumpEvents";
Assert.That(pump.PumpState, Is.EqualTo(EventPumpState.Stopped));
StartPump(pump, 1000);
Assert.That(pump.PumpState, Is.EqualTo(EventPumpState.Pumping));
EnqueueEvents(q);
StopPump(pump, 1000);
Assert.That(pump.PumpState, Is.EqualTo(EventPumpState.Stopped));
}
VerifyQueue(el.Events);
}
[Test]
[Timeout(1000)]
public void PumpSynchronousAndAsynchronousEvents()
{
EventQueue q = new EventQueue();
using (EventPump pump = new EventPump(TestListener.NULL, q))
{
pump.Name = "PumpSynchronousAndAsynchronousEvents";
pump.Start();
int numberOfAsynchronousEvents = 0;
int sumOfAsynchronousQueueLength = 0;
const int Repetitions = 2;
for (int i = 0; i < Repetitions; i++)
{
foreach (Event e in events)
{
q.Enqueue(e);
sumOfAsynchronousQueueLength += q.Count;
numberOfAsynchronousEvents++;
}
}
Console.WriteLine("Average queue length: {0}", (float)sumOfAsynchronousQueueLength / numberOfAsynchronousEvents);
}
}
#endregion
public abstract class ProducerConsumerTest
{
private volatile Exception myConsumerException;
protected void RunProducerConsumer()
{
this.myConsumerException = null;
Thread consumerThread = new Thread(new ThreadStart(this.ConsumerThreadWrapper));
try
{
consumerThread.Start();
this.Producer();
bool consumerStopped = consumerThread.Join(1000);
Assert.IsTrue(consumerStopped);
}
finally
{
ThreadUtility.Kill(consumerThread);
}
Assert.IsNull(this.myConsumerException);
}
protected abstract void Producer();
protected abstract void Consumer();
private void ConsumerThreadWrapper()
{
try
{
this.Consumer();
}
catch (System.Threading.ThreadAbortException)
{
Thread.ResetAbort();
}
catch (Exception ex)
{
this.myConsumerException = ex;
}
}
}
private class EventProducer
{
public readonly Thread ProducerThread;
public int SentEventsCount;
public int MaxQueueLength;
public Exception Exception;
private readonly EventQueue queue;
private readonly bool delay;
public EventProducer(EventQueue q, int id, bool delay)
{
this.queue = q;
this.ProducerThread = new Thread(new ThreadStart(this.Produce));
this.ProducerThread.Name = this.GetType().FullName + id;
this.delay = delay;
}
private void Produce()
{
try
{
Event e = new TestStartedEvent(new TestSuite("Dummy"));
DateTime start = DateTime.Now;
while (DateTime.Now - start <= TimeSpan.FromSeconds(3))
{
this.queue.Enqueue(e);
this.SentEventsCount++;
this.MaxQueueLength = Math.Max(this.queue.Count, this.MaxQueueLength);
// without Sleep or with just a Sleep(0), the EventPump thread does not keep up and the queue gets very long
if (this.delay)
Thread.Sleep(1);
}
}
catch (Exception ex)
{
this.Exception = ex;
}
}
}
}
}
#endif
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Compiler;
namespace Microsoft.Ddue.Tools.Reflection {
public class WhidbeyNamer : ApiNamer {
public override string GetMemberName(Member member) {
using (TextWriter writer = new StringWriter()) {
switch (member.NodeType) {
case NodeType.Field:
writer.Write("F:");
WriteField((Field)member, writer);
break;
case NodeType.Property:
writer.Write("P:");
WriteProperty((Property)member, writer);
break;
case NodeType.Method:
writer.Write("M:");
WriteMethod((Method)member, writer);
break;
case NodeType.InstanceInitializer:
writer.Write("M:");
WriteConstructor((InstanceInitializer)member, writer);
break;
case NodeType.StaticInitializer:
writer.Write("M:");
WriteStaticConstructor((StaticInitializer)member, writer);
break;
case NodeType.Event:
writer.Write("E:");
WriteEvent((Event)member, writer);
break;
}
return (writer.ToString());
}
}
public override string GetNamespaceName(Namespace space) {
using (TextWriter writer = new StringWriter()) {
writer.Write("N:");
WriteNamespace(space, writer);
return (writer.ToString());
}
}
public override string GetTypeName(TypeNode type) {
using (TextWriter writer = new StringWriter()) {
writer.Write("T:");
WriteType(type, writer);
return (writer.ToString());
}
}
private static string GetName(Member entity) {
using (TextWriter writer = new StringWriter()) {
TypeNode type = entity as TypeNode;
if (type != null) {
writer.Write("T:");
WriteType(type, writer);
return (writer.ToString());
}
switch (entity.NodeType) {
case NodeType.Namespace:
writer.Write("N:");
WriteNamespace(entity as Namespace, writer);
break;
case NodeType.Field:
writer.Write("F:");
WriteField(entity as Field, writer);
break;
case NodeType.Property:
writer.Write("P:");
WriteProperty(entity as Property, writer);
break;
case NodeType.Method:
writer.Write("M:");
WriteMethod(entity as Method, writer);
break;
case NodeType.InstanceInitializer:
writer.Write("M:");
WriteConstructor(entity as InstanceInitializer, writer);
break;
case NodeType.StaticInitializer:
writer.Write("M:");
WriteStaticConstructor(entity as StaticInitializer, writer);
break;
case NodeType.Event:
writer.Write("E:");
WriteEvent(entity as Event, writer);
break;
}
return (writer.ToString());
}
}
private static void WriteConstructor(InstanceInitializer constructor, TextWriter writer) {
WriteType(constructor.DeclaringType, writer);
writer.Write(".#ctor");
WriteParameters(constructor.Parameters, writer);
}
private static void WriteEvent(Event trigger, TextWriter writer) {
WriteType(trigger.DeclaringType, writer);
writer.Write(".{0}", trigger.Name.Name);
}
private static void WriteField(Field field, TextWriter writer) {
WriteType(field.DeclaringType, writer);
writer.Write(".{0}", field.Name.Name);
}
private static void WriteMethod(Method method, TextWriter writer) {
string name = method.Name.Name;
WriteType(method.DeclaringType, writer);
writer.Write(".{0}", name);
if (method.IsGeneric) {
TypeNodeList genericParameters = method.TemplateParameters;
if (genericParameters != null) {
writer.Write("``{0}", genericParameters.Count);
}
}
WriteParameters(method.Parameters, writer);
// add ~ for conversion operators
if ((name == "op_Implicit") || (name == "op_Explicit")) {
writer.Write("~");
WriteType(method.ReturnType, writer);
}
}
// The actual logic to construct names
private static void WriteNamespace(Namespace space, TextWriter writer) {
writer.Write(space.Name);
}
private static void WriteParameters(ParameterList parameters, TextWriter writer) {
if ((parameters == null) || (parameters.Count == 0)) return;
writer.Write("(");
for (int i = 0; i < parameters.Count; i++) {
if (i > 0) writer.Write(",");
WriteType(parameters[i].Type, writer);
}
writer.Write(")");
}
private static void WriteProperty(Property property, TextWriter writer) {
WriteType(property.DeclaringType, writer);
writer.Write(".{0}", property.Name.Name);
ParameterList parameters = property.Parameters;
WriteParameters(parameters, writer);
}
private static void WriteStaticConstructor(StaticInitializer constructor, TextWriter writer) {
WriteType(constructor.DeclaringType, writer);
writer.Write(".#cctor");
WriteParameters(constructor.Parameters, writer);
}
private static void WriteType(TypeNode type, TextWriter writer) {
switch (type.NodeType) {
case NodeType.ArrayType:
ArrayType array = type as ArrayType;
WriteType(array.ElementType, writer);
writer.Write("[");
for (int i = 1; i < array.Rank; i++) writer.Write(",");
writer.Write("]");
break;
case NodeType.Reference:
Reference reference = type as Reference;
TypeNode referencedType = reference.ElementType;
WriteType(referencedType, writer);
// DocStudio fails to add @ to template parameters or arrays of template
// parameters, so we have to mirror this bizarre behavior here
bool writeAt = true;
if (referencedType.IsTemplateParameter) writeAt = false;
if (referencedType.NodeType == NodeType.ArrayType) {
ArrayType referencedArray = referencedType as ArrayType;
if (referencedArray.ElementType.IsTemplateParameter) writeAt = false;
}
if (writeAt) writer.Write("@");
break;
case NodeType.Pointer:
Pointer pointer = type as Pointer;
WriteType(pointer.ElementType, writer);
writer.Write("*");
break;
case NodeType.OptionalModifier:
TypeModifier optionalModifierClause = type as TypeModifier;
WriteType(optionalModifierClause.ModifiedType, writer);
writer.Write("!");
WriteType(optionalModifierClause.Modifier, writer);
break;
case NodeType.RequiredModifier:
TypeModifier requiredModifierClause = type as TypeModifier;
WriteType(requiredModifierClause.ModifiedType, writer);
writer.Write("|");
WriteType(requiredModifierClause.Modifier, writer);
break;
default:
if (type.IsTemplateParameter) {
ITypeParameter gtp = (ITypeParameter)type;
if (gtp.DeclaringMember is TypeNode) {
writer.Write("`");
} else if (gtp.DeclaringMember is Method) {
writer.Write("``");
} else {
throw new InvalidOperationException("Generic parameter not on type or method.");
}
writer.Write(gtp.ParameterListIndex);
} else {
// namespace
TypeNode declaringType = type.DeclaringType;
if (declaringType != null) {
// names of nested types begin with outer type name
WriteType(declaringType, writer);
writer.Write(".");
} else {
// otherwise just prepend the namespace
string space = type.Namespace.Name;
if (space != null && space.Length > 0) {
writer.Write(space);
writer.Write(".");
}
}
// name
writer.Write(type.GetUnmangledNameWithoutTypeParameters());
// generic parameters
if (type.IsGeneric) {
// number of parameters
TypeNodeList parameters = type.TemplateParameters;
if (parameters != null) {
writer.Write("`{0}", parameters.Count);
}
// arguments
TypeNodeList arguments = type.TemplateArguments;
if ((arguments != null) && (arguments.Count > 0)) {
writer.Write("{");
for (int i = 0; i < arguments.Count; i++) {
TypeNode argument = arguments[i];
if (i > 0) writer.Write(",");
WriteType(arguments[i], writer);
}
writer.Write("}");
}
}
}
break;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace ClosedXML.Excel
{
[DebuggerDisplay("{Name}")]
internal class XLPivotTable : IXLPivotTable
{
public Guid Guid { get; private set; }
public XLPivotTable()
{
this.Guid = Guid.NewGuid();
Fields = new XLPivotFields(this);
ReportFilters = new XLPivotFields(this);
ColumnLabels = new XLPivotFields(this);
RowLabels = new XLPivotFields(this);
Values = new XLPivotValues(this);
Theme = XLPivotTableTheme.PivotStyleLight16;
SetExcelDefaults();
}
public IXLCell TargetCell { get; set; }
public IXLRange SourceRange { get; set; }
public IEnumerable<string> SourceRangeFieldsAvailable
{
get { return this.SourceRange.FirstRow().Cells().Select(c => c.GetString()); }
}
public IXLPivotFields Fields { get; private set; }
public IXLPivotFields ReportFilters { get; private set; }
public IXLPivotFields ColumnLabels { get; private set; }
public IXLPivotFields RowLabels { get; private set; }
public IXLPivotValues Values { get; private set; }
public XLPivotTableTheme Theme { get; set; }
public IXLPivotTable SetTheme(XLPivotTableTheme value) { Theme = value; return this; }
public String Name { get; set; }
public IXLPivotTable SetName(String value) { Name = value; return this; }
public String Title { get; set; }
public IXLPivotTable SetTitle(String value) { Title = value; return this; }
public String Description { get; set; }
public IXLPivotTable SetDescription(String value) { Description = value; return this; }
public String ColumnHeaderCaption { get; set; }
public IXLPivotTable SetColumnHeaderCaption(String value)
{
ColumnHeaderCaption = value;
return this;
}
public String RowHeaderCaption { get; set; }
public IXLPivotTable SetRowHeaderCaption(String value)
{
RowHeaderCaption = value;
return this;
}
public Boolean MergeAndCenterWithLabels { get; set; }
public IXLPivotTable SetMergeAndCenterWithLabels() { MergeAndCenterWithLabels = true; return this; }
public IXLPivotTable SetMergeAndCenterWithLabels(Boolean value) { MergeAndCenterWithLabels = value; return this; }
public Int32 RowLabelIndent { get; set; }
public IXLPivotTable SetRowLabelIndent(Int32 value) { RowLabelIndent = value; return this; }
public XLFilterAreaOrder FilterAreaOrder { get; set; }
public IXLPivotTable SetFilterAreaOrder(XLFilterAreaOrder value) { FilterAreaOrder = value; return this; }
public Int32 FilterFieldsPageWrap { get; set; }
public IXLPivotTable SetFilterFieldsPageWrap(Int32 value) { FilterFieldsPageWrap = value; return this; }
public String ErrorValueReplacement { get; set; }
public IXLPivotTable SetErrorValueReplacement(String value) { ErrorValueReplacement = value; return this; }
public String EmptyCellReplacement { get; set; }
public IXLPivotTable SetEmptyCellReplacement(String value) { EmptyCellReplacement = value; return this; }
public Boolean AutofitColumns { get; set; }
public IXLPivotTable SetAutofitColumns() { AutofitColumns = true; return this; }
public IXLPivotTable SetAutofitColumns(Boolean value) { AutofitColumns = value; return this; }
public Boolean PreserveCellFormatting { get; set; }
public IXLPivotTable SetPreserveCellFormatting() { PreserveCellFormatting = true; return this; }
public IXLPivotTable SetPreserveCellFormatting(Boolean value) { PreserveCellFormatting = value; return this; }
public Boolean ShowGrandTotalsRows { get; set; }
public IXLPivotTable SetShowGrandTotalsRows() { ShowGrandTotalsRows = true; return this; }
public IXLPivotTable SetShowGrandTotalsRows(Boolean value) { ShowGrandTotalsRows = value; return this; }
public Boolean ShowGrandTotalsColumns { get; set; }
public IXLPivotTable SetShowGrandTotalsColumns() { ShowGrandTotalsColumns = true; return this; }
public IXLPivotTable SetShowGrandTotalsColumns(Boolean value) { ShowGrandTotalsColumns = value; return this; }
public Boolean FilteredItemsInSubtotals { get; set; }
public IXLPivotTable SetFilteredItemsInSubtotals() { FilteredItemsInSubtotals = true; return this; }
public IXLPivotTable SetFilteredItemsInSubtotals(Boolean value) { FilteredItemsInSubtotals = value; return this; }
public Boolean AllowMultipleFilters { get; set; }
public IXLPivotTable SetAllowMultipleFilters() { AllowMultipleFilters = true; return this; }
public IXLPivotTable SetAllowMultipleFilters(Boolean value) { AllowMultipleFilters = value; return this; }
public Boolean UseCustomListsForSorting { get; set; }
public IXLPivotTable SetUseCustomListsForSorting() { UseCustomListsForSorting = true; return this; }
public IXLPivotTable SetUseCustomListsForSorting(Boolean value) { UseCustomListsForSorting = value; return this; }
public Boolean ShowExpandCollapseButtons { get; set; }
public IXLPivotTable SetShowExpandCollapseButtons() { ShowExpandCollapseButtons = true; return this; }
public IXLPivotTable SetShowExpandCollapseButtons(Boolean value) { ShowExpandCollapseButtons = value; return this; }
public Boolean ShowContextualTooltips { get; set; }
public IXLPivotTable SetShowContextualTooltips() { ShowContextualTooltips = true; return this; }
public IXLPivotTable SetShowContextualTooltips(Boolean value) { ShowContextualTooltips = value; return this; }
public Boolean ShowPropertiesInTooltips { get; set; }
public IXLPivotTable SetShowPropertiesInTooltips() { ShowPropertiesInTooltips = true; return this; }
public IXLPivotTable SetShowPropertiesInTooltips(Boolean value) { ShowPropertiesInTooltips = value; return this; }
public Boolean DisplayCaptionsAndDropdowns { get; set; }
public IXLPivotTable SetDisplayCaptionsAndDropdowns() { DisplayCaptionsAndDropdowns = true; return this; }
public IXLPivotTable SetDisplayCaptionsAndDropdowns(Boolean value) { DisplayCaptionsAndDropdowns = value; return this; }
public Boolean ClassicPivotTableLayout { get; set; }
public IXLPivotTable SetClassicPivotTableLayout() { ClassicPivotTableLayout = true; return this; }
public IXLPivotTable SetClassicPivotTableLayout(Boolean value) { ClassicPivotTableLayout = value; return this; }
public Boolean ShowValuesRow { get; set; }
public IXLPivotTable SetShowValuesRow() { ShowValuesRow = true; return this; }
public IXLPivotTable SetShowValuesRow(Boolean value) { ShowValuesRow = value; return this; }
public Boolean ShowEmptyItemsOnRows { get; set; }
public IXLPivotTable SetShowEmptyItemsOnRows() { ShowEmptyItemsOnRows = true; return this; }
public IXLPivotTable SetShowEmptyItemsOnRows(Boolean value) { ShowEmptyItemsOnRows = value; return this; }
public Boolean ShowEmptyItemsOnColumns { get; set; }
public IXLPivotTable SetShowEmptyItemsOnColumns() { ShowEmptyItemsOnColumns = true; return this; }
public IXLPivotTable SetShowEmptyItemsOnColumns(Boolean value) { ShowEmptyItemsOnColumns = value; return this; }
public Boolean DisplayItemLabels { get; set; }
public IXLPivotTable SetDisplayItemLabels() { DisplayItemLabels = true; return this; }
public IXLPivotTable SetDisplayItemLabels(Boolean value) { DisplayItemLabels = value; return this; }
public Boolean SortFieldsAtoZ { get; set; }
public IXLPivotTable SetSortFieldsAtoZ() { SortFieldsAtoZ = true; return this; }
public IXLPivotTable SetSortFieldsAtoZ(Boolean value) { SortFieldsAtoZ = value; return this; }
public Boolean PrintExpandCollapsedButtons { get; set; }
public IXLPivotTable SetPrintExpandCollapsedButtons() { PrintExpandCollapsedButtons = true; return this; }
public IXLPivotTable SetPrintExpandCollapsedButtons(Boolean value) { PrintExpandCollapsedButtons = value; return this; }
public Boolean RepeatRowLabels { get; set; }
public IXLPivotTable SetRepeatRowLabels() { RepeatRowLabels = true; return this; }
public IXLPivotTable SetRepeatRowLabels(Boolean value) { RepeatRowLabels = value; return this; }
public Boolean PrintTitles { get; set; }
public IXLPivotTable SetPrintTitles() { PrintTitles = true; return this; }
public IXLPivotTable SetPrintTitles(Boolean value) { PrintTitles = value; return this; }
public Boolean SaveSourceData { get; set; }
public IXLPivotTable SetSaveSourceData() { SaveSourceData = true; return this; }
public IXLPivotTable SetSaveSourceData(Boolean value) { SaveSourceData = value; return this; }
public Boolean EnableShowDetails { get; set; }
public IXLPivotTable SetEnableShowDetails() { EnableShowDetails = true; return this; }
public IXLPivotTable SetEnableShowDetails(Boolean value) { EnableShowDetails = value; return this; }
public Boolean RefreshDataOnOpen { get; set; }
public IXLPivotTable SetRefreshDataOnOpen() { RefreshDataOnOpen = true; return this; }
public IXLPivotTable SetRefreshDataOnOpen(Boolean value) { RefreshDataOnOpen = value; return this; }
public XLItemsToRetain ItemsToRetainPerField { get; set; }
public IXLPivotTable SetItemsToRetainPerField(XLItemsToRetain value) { ItemsToRetainPerField = value; return this; }
public Boolean EnableCellEditing { get; set; }
public IXLPivotTable SetEnableCellEditing() { EnableCellEditing = true; return this; }
public IXLPivotTable SetEnableCellEditing(Boolean value) { EnableCellEditing = value; return this; }
public Boolean ShowRowHeaders { get; set; }
public IXLPivotTable SetShowRowHeaders() { ShowRowHeaders = true; return this; }
public IXLPivotTable SetShowRowHeaders(Boolean value) { ShowRowHeaders = value; return this; }
public Boolean ShowColumnHeaders { get; set; }
public IXLPivotTable SetShowColumnHeaders() { ShowColumnHeaders = true; return this; }
public IXLPivotTable SetShowColumnHeaders(Boolean value) { ShowColumnHeaders = value; return this; }
public Boolean ShowRowStripes { get; set; }
public IXLPivotTable SetShowRowStripes() { ShowRowStripes = true; return this; }
public IXLPivotTable SetShowRowStripes(Boolean value) { ShowRowStripes = value; return this; }
public Boolean ShowColumnStripes { get; set; }
public IXLPivotTable SetShowColumnStripes() { ShowColumnStripes = true; return this; }
public IXLPivotTable SetShowColumnStripes(Boolean value) { ShowColumnStripes = value; return this; }
public XLPivotSubtotals Subtotals { get; set; }
public IXLPivotTable SetSubtotals(XLPivotSubtotals value) { Subtotals = value; return this; }
public XLPivotLayout Layout
{
set { Fields.ForEach(f => f.SetLayout(value)); }
}
public IXLPivotTable SetLayout(XLPivotLayout value) { Layout = value; return this; }
public Boolean InsertBlankLines
{
set { Fields.ForEach(f => f.SetInsertBlankLines(value)); }
}
public IXLPivotTable SetInsertBlankLines() { InsertBlankLines = true; return this; }
public IXLPivotTable SetInsertBlankLines(Boolean value) { InsertBlankLines = value; return this; }
internal String RelId { get; set; }
internal String CacheDefinitionRelId { get; set; }
internal String WorkbookCacheRelId { get; set; }
private void SetExcelDefaults()
{
EmptyCellReplacement = String.Empty;
AutofitColumns = true;
PreserveCellFormatting = true;
ShowGrandTotalsColumns = true;
ShowGrandTotalsRows = true;
UseCustomListsForSorting = true;
ShowExpandCollapseButtons = true;
ShowContextualTooltips = true;
DisplayCaptionsAndDropdowns = true;
RepeatRowLabels = true;
SaveSourceData = true;
EnableShowDetails = true;
ShowColumnHeaders = true;
ShowRowHeaders = true;
}
}
}
| |
/**
* 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;
using Thrift.Collections;
using Thrift.Protocol;
using Thrift.Transport;
namespace Thrift.Server
{
/// <summary>
/// Server that uses C# threads (as opposed to the ThreadPool) when handling requests.
/// </summary>
public class TThreadedServer : TServer
{
private const int DEFAULT_MAX_THREADS = 100;
private volatile bool stop = false;
private readonly int maxThreads;
private Queue<TTransport> clientQueue;
private THashSet<Thread> clientThreads;
private object clientLock;
private Thread workerThread;
public int ClientThreadsCount
{
get { return clientThreads.Count; }
}
public TThreadedServer(TProcessor processor, TServerTransport serverTransport)
: this(new TSingletonProcessorFactory(processor), serverTransport,
new TTransportFactory(), new TTransportFactory(),
new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(),
DEFAULT_MAX_THREADS, DefaultLogDelegate)
{
}
public TThreadedServer(TProcessor processor, TServerTransport serverTransport, LogDelegate logDelegate)
: this(new TSingletonProcessorFactory(processor), serverTransport,
new TTransportFactory(), new TTransportFactory(),
new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(),
DEFAULT_MAX_THREADS, logDelegate)
{
}
public TThreadedServer(TProcessor processor,
TServerTransport serverTransport,
TTransportFactory transportFactory,
TProtocolFactory protocolFactory)
: this(new TSingletonProcessorFactory(processor), serverTransport,
transportFactory, transportFactory,
protocolFactory, protocolFactory,
DEFAULT_MAX_THREADS, DefaultLogDelegate)
{
}
public TThreadedServer(TProcessorFactory processorFactory,
TServerTransport serverTransport,
TTransportFactory transportFactory,
TProtocolFactory protocolFactory)
: this(processorFactory, serverTransport,
transportFactory, transportFactory,
protocolFactory, protocolFactory,
DEFAULT_MAX_THREADS, DefaultLogDelegate)
{
}
public TThreadedServer(TProcessorFactory processorFactory,
TServerTransport serverTransport,
TTransportFactory inputTransportFactory,
TTransportFactory outputTransportFactory,
TProtocolFactory inputProtocolFactory,
TProtocolFactory outputProtocolFactory,
int maxThreads, LogDelegate logDel)
: base(processorFactory, serverTransport, inputTransportFactory, outputTransportFactory,
inputProtocolFactory, outputProtocolFactory, logDel)
{
this.maxThreads = maxThreads;
clientQueue = new Queue<TTransport>();
clientLock = new object();
clientThreads = new THashSet<Thread>();
}
/// <summary>
/// Use new Thread for each new client connection. block until numConnections < maxThreads.
/// </summary>
public override void Serve()
{
try
{
//start worker thread
workerThread = new Thread(new ThreadStart(Execute));
workerThread.Start();
serverTransport.Listen();
}
catch (TTransportException ttx)
{
logDelegate("Error, could not listen on ServerTransport: " + ttx);
return;
}
//Fire the preServe server event when server is up but before any client connections
if (serverEventHandler != null)
serverEventHandler.preServe();
while (!stop)
{
int failureCount = 0;
try
{
TTransport client = serverTransport.Accept();
lock (clientLock)
{
clientQueue.Enqueue(client);
Monitor.Pulse(clientLock);
}
}
catch (TTransportException ttx)
{
if (!stop || ttx.Type != TTransportException.ExceptionType.Interrupted)
{
++failureCount;
logDelegate(ttx.ToString());
}
}
}
if (stop)
{
try
{
serverTransport.Close();
}
catch (TTransportException ttx)
{
logDelegate("TServeTransport failed on close: " + ttx.Message);
}
stop = false;
}
}
/// <summary>
/// Loops on processing a client forever
/// </summary>
private void Execute()
{
while (!stop)
{
TTransport client;
Thread t;
lock (clientLock)
{
//don't dequeue if too many connections
while (clientThreads.Count >= maxThreads)
{
Monitor.Wait(clientLock);
}
while (clientQueue.Count == 0)
{
Monitor.Wait(clientLock);
}
client = clientQueue.Dequeue();
t = new Thread(new ParameterizedThreadStart(ClientWorker));
clientThreads.Add(t);
}
//start processing requests from client on new thread
t.Start(client);
}
}
private void ClientWorker(object context)
{
using (TTransport client = (TTransport)context)
{
TProcessor processor = processorFactory.GetProcessor(client);
TTransport inputTransport = null;
TTransport outputTransport = null;
TProtocol inputProtocol = null;
TProtocol outputProtocol = null;
object connectionContext = null;
try
{
try
{
inputTransport = inputTransportFactory.GetTransport(client);
outputTransport = outputTransportFactory.GetTransport(client);
inputProtocol = inputProtocolFactory.GetProtocol(inputTransport);
outputProtocol = outputProtocolFactory.GetProtocol(outputTransport);
//Recover event handler (if any) and fire createContext server event when a client connects
if (serverEventHandler != null)
connectionContext = serverEventHandler.createContext(inputProtocol, outputProtocol);
//Process client requests until client disconnects
while (!stop)
{
if (!inputTransport.Peek())
break;
//Fire processContext server event
//N.B. This is the pattern implemented in C++ and the event fires provisionally.
//That is to say it may be many minutes between the event firing and the client request
//actually arriving or the client may hang up without ever makeing a request.
if (serverEventHandler != null)
serverEventHandler.processContext(connectionContext, inputTransport);
//Process client request (blocks until transport is readable)
if (!processor.Process(inputProtocol, outputProtocol))
break;
}
}
catch (TTransportException)
{
//Usually a client disconnect, expected
}
catch (Exception x)
{
//Unexpected
logDelegate("Error: " + x);
}
//Fire deleteContext server event after client disconnects
if (serverEventHandler != null)
serverEventHandler.deleteContext(connectionContext, inputProtocol, outputProtocol);
lock (clientLock)
{
clientThreads.Remove(Thread.CurrentThread);
Monitor.Pulse(clientLock);
}
}
finally
{
//Close transports
if (inputTransport != null)
inputTransport.Close();
if (outputTransport != null)
outputTransport.Close();
// disposable stuff should be disposed
if (inputProtocol != null)
inputProtocol.Dispose();
if (outputProtocol != null)
outputProtocol.Dispose();
}
}
}
public override void Stop()
{
stop = true;
serverTransport.Close();
//clean up all the threads myself
workerThread.Abort();
foreach (Thread t in clientThreads)
{
t.Abort();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
namespace Andi.Libs.IniParser.Model
{
/// <summary>
/// <para>Represents a collection of Keydata.</para>
/// </summary>
public class KeyDataCollection : ICloneable, IEnumerable<KeyData>
{
#region Initialization
/// <summary>
/// Initializes a new instance of the <see cref="KeyDataCollection"/> class.
/// </summary>
public KeyDataCollection()
{
_keyData = new Dictionary<string, KeyData>();
}
/// <summary>
/// Initializes a new instance of the <see cref="KeyDataCollection"/> class
/// from a previous instance of <see cref="KeyDataCollection"/>.
/// </summary>
/// <remarks>
/// Data is deeply copied
/// </remarks>
/// <param name="ori">
/// The instance of the <see cref="KeyDataCollection"/> class
/// used to create the new instance.</param>
public KeyDataCollection(KeyDataCollection ori) : this()
{
foreach ( KeyData key in ori)
_keyData.Add(key.KeyName, key);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the value of a concrete key.
/// </summary>
/// <remarks>
/// If we try to assign the value of a key which doesn't exists,
/// a new key is added with the name and the value is assigned to it.
/// </remarks>
/// <param name="keyName">Name of the key</param>
/// <returns>
/// The string with key's value or null
/// if the key was not found.
/// </returns>
public string this[string keyName]
{
get
{
if (_keyData.ContainsKey(keyName))
return _keyData[keyName].Value;
return null;
}
set
{
if (!_keyData.ContainsKey(keyName))
{
this.AddKey(keyName);
}
_keyData[keyName].Value = value;
}
}
/// <summary>
/// Return the number of keys in the collection
/// </summary>
/// <value>An integer with the number of keys in the collection.</value>
public int Count
{
get { return _keyData.Count; }
}
#endregion
#region Operations
/// <summary>
/// Adds a new key with the specified name and empty value and comments
/// </summary>
/// <remarks>
/// A valid key name is a string with NO blank spaces.
/// </remarks>
/// <param name="keyName">New key to be added.</param>
/// <returns>
/// <c>true</c> if a new empty key was added
/// <c>false</c> otherwise.
/// </returns>
/// <exception cref="ArgumentException">If the key name is not valid.</exception>
public bool AddKey(string keyName)
{
if ( !_keyData.ContainsKey(keyName) )
{
_keyData.Add(keyName, new KeyData(keyName));
return true;
}
return false;
}
/// <summary>
/// Adds a new key with the specified name and value and comments
/// </summary>
/// <remarks>
/// A valid key name is a string with NO blank spaces.
/// </remarks>
/// <param name="keyName">New key to be added.</param>
/// <param name="keyData">KeyData instance.</param>
/// <returns>
/// <c>true</c> if a new empty key was added
/// <c>false</c> otherwise.
/// </returns>
/// <exception cref="ArgumentException">If the key name is not valid.</exception>
public bool AddKey(string keyName, KeyData keyData)
{
if (AddKey(keyName))
{
_keyData[keyName] = keyData;
return true;
}
return false;
}
/// <summary>
/// Adds a new key with the specified name and value and comments
/// </summary>
/// <remarks>
/// A valid key name is a string with NO blank spaces.
/// </remarks>
/// <param name="keyName">New key to be added.</param>
/// <param name="keyValue">Value associated to the kyy.</param>
/// <returns>
/// <c>true</c> if a new empty key was added
/// <c>false</c> otherwise.
/// </returns>
/// <exception cref="ArgumentException">If the key name is not valid.</exception>
public bool AddKey(string keyName, string keyValue)
{
if (AddKey(keyName))
{
_keyData[keyName].Value = keyValue;
return true;
}
return false;
}
/// <summary>
/// Gets if a specifyed key name exists in the collection.
/// </summary>
/// <param name="keyName">Key name to search</param>
/// <returns><c>true</c> if a key with the specified name exists in the collectoin
/// <c>false</c> otherwise</returns>
public bool ContainsKey(string keyName)
{
return _keyData.ContainsKey(keyName);
}
/// <summary>
/// Retrieves the data for a specified key given its name
/// </summary>
/// <param name="keyName">Name of the key to retrieve.</param>
/// <returns>
/// A <see cref="KeyData"/> instance holding
/// the key information or <c>null</c> if the key wasn't found.
/// </returns>
public KeyData GetKeyData(string keyName)
{
if (_keyData.ContainsKey(keyName))
return _keyData[keyName];
return null;
}
public void Merge(KeyDataCollection keyDataToMerge)
{
foreach(var keyData in keyDataToMerge)
{
AddKey(keyData.KeyName);
GetKeyData(keyData.KeyName).Comments.AddRange(keyData.Comments);
this[keyData.KeyName] = keyData.Value;
}
}
/// <summary>
/// Deletes all keys in this collection.
/// </summary>
public void RemoveAllKeys()
{
_keyData.Clear();
}
/// <summary>
/// Deletes a previously existing key, including its associated data.
/// </summary>
/// <param name="keyName">The key to be removed.</param>
/// <returns>
/// <c>true</c> if a key with the specified name was removed
/// <c>false</c> otherwise.
/// </returns>
public bool RemoveKey(string keyName)
{
return _keyData.Remove(keyName);
}
/// <summary>
/// Sets the key data associated to a specified key.
/// </summary>
/// <param name="data">The new <see cref="KeyData"/> for the key.</param>
public void SetKeyData(KeyData data)
{
if (data != null)
{
if (_keyData.ContainsKey(data.KeyName))
RemoveKey(data.KeyName);
AddKey(data.KeyName, data);
}
}
#endregion
#region IEnumerable<KeyData> Members
/// <summary>
/// Allows iteration througt the collection.
/// </summary>
/// <returns>A strong-typed IEnumerator </returns>
public IEnumerator<KeyData> GetEnumerator()
{
foreach ( string key in _keyData.Keys )
yield return _keyData[key];
}
#region IEnumerable Members
/// <summary>
/// Implementation needed
/// </summary>
/// <returns>A weak-typed IEnumerator.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return _keyData.GetEnumerator();
}
#endregion
#endregion
#region ICloneable Members
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>
/// A new object that is a copy of this instance.
/// </returns>
public object Clone()
{
return new KeyDataCollection(this);
}
#endregion
#region Non-public Members
/// <summary>
/// Collection of KeyData for a given section
/// </summary>
private readonly Dictionary<string, KeyData> _keyData;
#endregion
}
}
| |
namespace java.io
{
[global::MonoJavaBridge.JavaClass()]
public partial class ObjectInputStream : java.io.InputStream, ObjectInput, ObjectStreamConstants
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected ObjectInputStream(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass(typeof(global::java.io.ObjectInputStream.GetField_))]
public abstract partial class GetField : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected GetField(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public abstract global::java.lang.Object get(java.lang.String arg0, java.lang.Object arg1);
private static global::MonoJavaBridge.MethodId _m1;
public abstract float get(java.lang.String arg0, float arg1);
private static global::MonoJavaBridge.MethodId _m2;
public abstract double get(java.lang.String arg0, double arg1);
private static global::MonoJavaBridge.MethodId _m3;
public abstract bool get(java.lang.String arg0, bool arg1);
private static global::MonoJavaBridge.MethodId _m4;
public abstract byte get(java.lang.String arg0, byte arg1);
private static global::MonoJavaBridge.MethodId _m5;
public abstract char get(java.lang.String arg0, char arg1);
private static global::MonoJavaBridge.MethodId _m6;
public abstract short get(java.lang.String arg0, short arg1);
private static global::MonoJavaBridge.MethodId _m7;
public abstract int get(java.lang.String arg0, int arg1);
private static global::MonoJavaBridge.MethodId _m8;
public abstract long get(java.lang.String arg0, long arg1);
private static global::MonoJavaBridge.MethodId _m9;
public abstract bool defaulted(java.lang.String arg0);
private static global::MonoJavaBridge.MethodId _m10;
public abstract global::java.io.ObjectStreamClass getObjectStreamClass();
private static global::MonoJavaBridge.MethodId _m11;
public GetField() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.io.ObjectInputStream.GetField._m11.native == global::System.IntPtr.Zero)
global::java.io.ObjectInputStream.GetField._m11 = @__env.GetMethodIDNoThrow(global::java.io.ObjectInputStream.GetField.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.io.ObjectInputStream.GetField.staticClass, global::java.io.ObjectInputStream.GetField._m11);
Init(@__env, handle);
}
static GetField()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.io.ObjectInputStream.GetField.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/io/ObjectInputStream$GetField"));
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::java.io.ObjectInputStream.GetField))]
internal sealed partial class GetField_ : java.io.ObjectInputStream.GetField
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal GetField_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public override global::java.lang.Object get(java.lang.String arg0, java.lang.Object arg1)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.io.ObjectInputStream.GetField_.staticClass, "get", "(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;", ref global::java.io.ObjectInputStream.GetField_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m1;
public override float get(java.lang.String arg0, float arg1)
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::java.io.ObjectInputStream.GetField_.staticClass, "get", "(Ljava/lang/String;F)F", ref global::java.io.ObjectInputStream.GetField_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m2;
public override double get(java.lang.String arg0, double arg1)
{
return global::MonoJavaBridge.JavaBridge.CallDoubleMethod(this, global::java.io.ObjectInputStream.GetField_.staticClass, "get", "(Ljava/lang/String;D)D", ref global::java.io.ObjectInputStream.GetField_._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m3;
public override bool get(java.lang.String arg0, bool arg1)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.io.ObjectInputStream.GetField_.staticClass, "get", "(Ljava/lang/String;Z)Z", ref global::java.io.ObjectInputStream.GetField_._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m4;
public override byte get(java.lang.String arg0, byte arg1)
{
return global::MonoJavaBridge.JavaBridge.CallByteMethod(this, global::java.io.ObjectInputStream.GetField_.staticClass, "get", "(Ljava/lang/String;B)B", ref global::java.io.ObjectInputStream.GetField_._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m5;
public override char get(java.lang.String arg0, char arg1)
{
return global::MonoJavaBridge.JavaBridge.CallCharMethod(this, global::java.io.ObjectInputStream.GetField_.staticClass, "get", "(Ljava/lang/String;C)C", ref global::java.io.ObjectInputStream.GetField_._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m6;
public override short get(java.lang.String arg0, short arg1)
{
return global::MonoJavaBridge.JavaBridge.CallShortMethod(this, global::java.io.ObjectInputStream.GetField_.staticClass, "get", "(Ljava/lang/String;S)S", ref global::java.io.ObjectInputStream.GetField_._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m7;
public override int get(java.lang.String arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.io.ObjectInputStream.GetField_.staticClass, "get", "(Ljava/lang/String;I)I", ref global::java.io.ObjectInputStream.GetField_._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m8;
public override long get(java.lang.String arg0, long arg1)
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.io.ObjectInputStream.GetField_.staticClass, "get", "(Ljava/lang/String;J)J", ref global::java.io.ObjectInputStream.GetField_._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m9;
public override bool defaulted(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.io.ObjectInputStream.GetField_.staticClass, "defaulted", "(Ljava/lang/String;)Z", ref global::java.io.ObjectInputStream.GetField_._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m10;
public override global::java.io.ObjectStreamClass getObjectStreamClass()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.io.ObjectInputStream.GetField_.staticClass, "getObjectStreamClass", "()Ljava/io/ObjectStreamClass;", ref global::java.io.ObjectInputStream.GetField_._m10) as java.io.ObjectStreamClass;
}
static GetField_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.io.ObjectInputStream.GetField_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/io/ObjectInputStream$GetField"));
}
}
private static global::MonoJavaBridge.MethodId _m0;
protected virtual global::java.lang.Class resolveClass(java.io.ObjectStreamClass arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.Class>(this, global::java.io.ObjectInputStream.staticClass, "resolveClass", "(Ljava/io/ObjectStreamClass;)Ljava/lang/Class;", ref global::java.io.ObjectInputStream._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Class;
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual global::java.lang.String readLine()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.io.ObjectInputStream.staticClass, "readLine", "()Ljava/lang/String;", ref global::java.io.ObjectInputStream._m1) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m2;
public override void close()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectInputStream.staticClass, "close", "()V", ref global::java.io.ObjectInputStream._m2);
}
private static global::MonoJavaBridge.MethodId _m3;
public virtual global::java.lang.Object readObject()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.io.ObjectInputStream.staticClass, "readObject", "()Ljava/lang/Object;", ref global::java.io.ObjectInputStream._m3) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual void defaultReadObject()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectInputStream.staticClass, "defaultReadObject", "()V", ref global::java.io.ObjectInputStream._m4);
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual int readInt()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.io.ObjectInputStream.staticClass, "readInt", "()I", ref global::java.io.ObjectInputStream._m5);
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual global::java.io.ObjectInputStream.GetField readFields()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.io.ObjectInputStream.staticClass, "readFields", "()Ljava/io/ObjectInputStream$GetField;", ref global::java.io.ObjectInputStream._m6) as java.io.ObjectInputStream.GetField;
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual char readChar()
{
return global::MonoJavaBridge.JavaBridge.CallCharMethod(this, global::java.io.ObjectInputStream.staticClass, "readChar", "()C", ref global::java.io.ObjectInputStream._m7);
}
private static global::MonoJavaBridge.MethodId _m8;
public override int read()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.io.ObjectInputStream.staticClass, "read", "()I", ref global::java.io.ObjectInputStream._m8);
}
private static global::MonoJavaBridge.MethodId _m9;
public override int read(byte[] arg0, int arg1, int arg2)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.io.ObjectInputStream.staticClass, "read", "([BII)I", ref global::java.io.ObjectInputStream._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m10;
public override int available()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.io.ObjectInputStream.staticClass, "available", "()I", ref global::java.io.ObjectInputStream._m10);
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual global::java.lang.String readUTF()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.io.ObjectInputStream.staticClass, "readUTF", "()Ljava/lang/String;", ref global::java.io.ObjectInputStream._m11) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual void readFully(byte[] arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectInputStream.staticClass, "readFully", "([BII)V", ref global::java.io.ObjectInputStream._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m13;
public virtual void readFully(byte[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectInputStream.staticClass, "readFully", "([B)V", ref global::java.io.ObjectInputStream._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m14;
public virtual long readLong()
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.io.ObjectInputStream.staticClass, "readLong", "()J", ref global::java.io.ObjectInputStream._m14);
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual byte readByte()
{
return global::MonoJavaBridge.JavaBridge.CallByteMethod(this, global::java.io.ObjectInputStream.staticClass, "readByte", "()B", ref global::java.io.ObjectInputStream._m15);
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual short readShort()
{
return global::MonoJavaBridge.JavaBridge.CallShortMethod(this, global::java.io.ObjectInputStream.staticClass, "readShort", "()S", ref global::java.io.ObjectInputStream._m16);
}
private static global::MonoJavaBridge.MethodId _m17;
public virtual float readFloat()
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::java.io.ObjectInputStream.staticClass, "readFloat", "()F", ref global::java.io.ObjectInputStream._m17);
}
private static global::MonoJavaBridge.MethodId _m18;
public virtual int skipBytes(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.io.ObjectInputStream.staticClass, "skipBytes", "(I)I", ref global::java.io.ObjectInputStream._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m19;
public virtual bool readBoolean()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.io.ObjectInputStream.staticClass, "readBoolean", "()Z", ref global::java.io.ObjectInputStream._m19);
}
private static global::MonoJavaBridge.MethodId _m20;
public virtual int readUnsignedByte()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.io.ObjectInputStream.staticClass, "readUnsignedByte", "()I", ref global::java.io.ObjectInputStream._m20);
}
private static global::MonoJavaBridge.MethodId _m21;
public virtual int readUnsignedShort()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.io.ObjectInputStream.staticClass, "readUnsignedShort", "()I", ref global::java.io.ObjectInputStream._m21);
}
private static global::MonoJavaBridge.MethodId _m22;
public virtual double readDouble()
{
return global::MonoJavaBridge.JavaBridge.CallDoubleMethod(this, global::java.io.ObjectInputStream.staticClass, "readDouble", "()D", ref global::java.io.ObjectInputStream._m22);
}
private static global::MonoJavaBridge.MethodId _m23;
protected virtual global::java.lang.Object readObjectOverride()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.io.ObjectInputStream.staticClass, "readObjectOverride", "()Ljava/lang/Object;", ref global::java.io.ObjectInputStream._m23) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m24;
public virtual global::java.lang.Object readUnshared()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.io.ObjectInputStream.staticClass, "readUnshared", "()Ljava/lang/Object;", ref global::java.io.ObjectInputStream._m24) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m25;
public virtual void registerValidation(java.io.ObjectInputValidation arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectInputStream.staticClass, "registerValidation", "(Ljava/io/ObjectInputValidation;I)V", ref global::java.io.ObjectInputStream._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m26;
protected virtual global::java.lang.Class resolveProxyClass(java.lang.String[] arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.Class>(this, global::java.io.ObjectInputStream.staticClass, "resolveProxyClass", "([Ljava/lang/String;)Ljava/lang/Class;", ref global::java.io.ObjectInputStream._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Class;
}
private static global::MonoJavaBridge.MethodId _m27;
protected virtual global::java.lang.Object resolveObject(java.lang.Object arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.io.ObjectInputStream.staticClass, "resolveObject", "(Ljava/lang/Object;)Ljava/lang/Object;", ref global::java.io.ObjectInputStream._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m28;
protected virtual bool enableResolveObject(bool arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.io.ObjectInputStream.staticClass, "enableResolveObject", "(Z)Z", ref global::java.io.ObjectInputStream._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m29;
protected virtual void readStreamHeader()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectInputStream.staticClass, "readStreamHeader", "()V", ref global::java.io.ObjectInputStream._m29);
}
private static global::MonoJavaBridge.MethodId _m30;
protected virtual global::java.io.ObjectStreamClass readClassDescriptor()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.io.ObjectInputStream.staticClass, "readClassDescriptor", "()Ljava/io/ObjectStreamClass;", ref global::java.io.ObjectInputStream._m30) as java.io.ObjectStreamClass;
}
private static global::MonoJavaBridge.MethodId _m31;
public ObjectInputStream(java.io.InputStream arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.io.ObjectInputStream._m31.native == global::System.IntPtr.Zero)
global::java.io.ObjectInputStream._m31 = @__env.GetMethodIDNoThrow(global::java.io.ObjectInputStream.staticClass, "<init>", "(Ljava/io/InputStream;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.io.ObjectInputStream.staticClass, global::java.io.ObjectInputStream._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m32;
protected ObjectInputStream() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.io.ObjectInputStream._m32.native == global::System.IntPtr.Zero)
global::java.io.ObjectInputStream._m32 = @__env.GetMethodIDNoThrow(global::java.io.ObjectInputStream.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.io.ObjectInputStream.staticClass, global::java.io.ObjectInputStream._m32);
Init(@__env, handle);
}
static ObjectInputStream()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.io.ObjectInputStream.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/io/ObjectInputStream"));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Formatters
{
public class SystemTextJsonOutputFormatterTest : JsonOutputFormatterTestBase
{
protected override TextOutputFormatter GetOutputFormatter()
{
return SystemTextJsonOutputFormatter.CreateFormatter(new JsonOptions());
}
[Fact]
public async Task WriteResponseBodyAsync_AllowsConfiguringPreserveReferenceHandling()
{
// Arrange
var formatter = GetOutputFormatter();
((SystemTextJsonOutputFormatter)formatter).SerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
var expectedContent = "{\"$id\":\"1\",\"name\":\"Person\",\"child\":{\"$id\":\"2\",\"name\":\"Child\",\"child\":null,\"parent\":{\"$ref\":\"1\"}},\"parent\":null}";
var person = new Person
{
Name = "Person",
Child = new Person { Name = "Child", },
};
person.Child.Parent = person;
var mediaType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
var encoding = CreateOrGetSupportedEncoding(formatter, "utf-8", isDefaultEncoding: true);
var body = new MemoryStream();
var actionContext = GetActionContext(mediaType, body);
var outputFormatterContext = new OutputFormatterWriteContext(
actionContext.HttpContext,
new TestHttpResponseStreamWriterFactory().CreateWriter,
typeof(Person),
person)
{
ContentType = new StringSegment(mediaType.ToString()),
};
// Act
await formatter.WriteResponseBodyAsync(outputFormatterContext, Encoding.GetEncoding("utf-8"));
// Assert
var actualContent = encoding.GetString(body.ToArray());
Assert.Equal(expectedContent, actualContent);
}
[Fact]
public async Task WriteResponseBodyAsync_WithNonUtf8Encoding_FormattingErrorsAreThrown()
{
// Arrange
var formatter = GetOutputFormatter();
var mediaType = MediaTypeHeaderValue.Parse("application/json; charset=utf-16");
var encoding = CreateOrGetSupportedEncoding(formatter, "utf-16", isDefaultEncoding: true);
var body = new MemoryStream();
var actionContext = GetActionContext(mediaType, body);
var outputFormatterContext = new OutputFormatterWriteContext(
actionContext.HttpContext,
new TestHttpResponseStreamWriterFactory().CreateWriter,
typeof(Person),
new ThrowingFormatterModel())
{
ContentType = new StringSegment(mediaType.ToString()),
};
// Act & Assert
await Assert.ThrowsAsync<TimeZoneNotFoundException>(() => formatter.WriteResponseBodyAsync(outputFormatterContext, Encoding.GetEncoding("utf-16")));
}
[Fact]
public async Task WriteResponseBodyAsync_ForLargeAsyncEnumerable()
{
// Arrange
var expected = new MemoryStream();
await JsonSerializer.SerializeAsync(expected, LargeAsync(), new JsonSerializerOptions(JsonSerializerDefaults.Web));
var formatter = GetOutputFormatter();
var mediaType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
var encoding = CreateOrGetSupportedEncoding(formatter, "utf-8", isDefaultEncoding: true);
var body = new MemoryStream();
var actionContext = GetActionContext(mediaType, body);
var asyncEnumerable = LargeAsync();
var outputFormatterContext = new OutputFormatterWriteContext(
actionContext.HttpContext,
new TestHttpResponseStreamWriterFactory().CreateWriter,
asyncEnumerable.GetType(),
asyncEnumerable)
{
ContentType = new StringSegment(mediaType.ToString()),
};
// Act
await formatter.WriteResponseBodyAsync(outputFormatterContext, Encoding.GetEncoding("utf-8"));
// Assert
Assert.Equal(expected.ToArray(), body.ToArray());
}
[Fact]
public async Task WriteResponseBodyAsync_AsyncEnumerableConnectionCloses()
{
// Arrange
var formatter = GetOutputFormatter();
var mediaType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
var body = new MemoryStream();
var actionContext = GetActionContext(mediaType, body);
var cts = new CancellationTokenSource();
actionContext.HttpContext.RequestAborted = cts.Token;
var asyncEnumerable = AsyncEnumerableClosedConnection();
var outputFormatterContext = new OutputFormatterWriteContext(
actionContext.HttpContext,
new TestHttpResponseStreamWriterFactory().CreateWriter,
asyncEnumerable.GetType(),
asyncEnumerable)
{
ContentType = new StringSegment(mediaType.ToString()),
};
var iterated = false;
// Act
await formatter.WriteResponseBodyAsync(outputFormatterContext, Encoding.GetEncoding("utf-8"));
// Assert
// System.Text.Json might write the '[' before cancellation is observed
Assert.InRange(body.ToArray().Length, 0, 1);
Assert.False(iterated);
async IAsyncEnumerable<int> AsyncEnumerableClosedConnection([EnumeratorCancellation] CancellationToken cancellationToken = default)
{
await Task.Yield();
cts.Cancel();
// MvcOptions.MaxIAsyncEnumerableBufferLimit is 8192. Pick some value larger than that.
foreach (var i in Enumerable.Range(0, 9000))
{
if (cancellationToken.IsCancellationRequested)
{
yield break;
}
iterated = true;
yield return i;
}
}
}
private class Person
{
public string Name { get; set; }
public Person Child { get; set; }
public Person Parent { get; set; }
}
[JsonConverter(typeof(ThrowingFormatterPersonConverter))]
private class ThrowingFormatterModel
{
}
private class ThrowingFormatterPersonConverter : JsonConverter<ThrowingFormatterModel>
{
public override ThrowingFormatterModel Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, ThrowingFormatterModel value, JsonSerializerOptions options)
{
throw new TimeZoneNotFoundException();
}
}
private static async IAsyncEnumerable<int> LargeAsync()
{
await Task.Yield();
// MvcOptions.MaxIAsyncEnumerableBufferLimit is 8192. Pick some value larger than that.
foreach (var i in Enumerable.Range(0, 9000))
{
yield return i;
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="DataConversionGenerator.cs" company="NJsonSchema">
// Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md</license>
// <author>Rico Suter, mail@rsuter.com</author>
//-----------------------------------------------------------------------
using System;
namespace NJsonSchema.CodeGeneration.TypeScript
{
/// <summary>Generates data conversion code.</summary>
public class DataConversionGenerator
{
/// <summary>Generates the code to convert a data object to the target class instances.</summary>
/// <returns>The generated code.</returns>
public static string RenderConvertToJavaScriptCode(DataConversionParameters parameters)
{
var model = CreateModel(parameters);
var template = parameters.Settings.TemplateFactory.CreateTemplate("TypeScript", "ConvertToJavaScript", model);
return template.Render();
}
/// <summary>Generates the code to convert a data object to the target class instances.</summary>
/// <returns>The generated code.</returns>
public static string RenderConvertToClassCode(DataConversionParameters parameters)
{
var model = CreateModel(parameters);
var template = parameters.Settings.TemplateFactory.CreateTemplate("TypeScript", "ConvertToClass", model);
return template.Render();
}
private static object CreateModel(DataConversionParameters parameters)
{
var type = parameters.Resolver.Resolve(parameters.Schema, parameters.IsPropertyNullable, parameters.TypeNameHint);
var valueGenerator = parameters.Settings.ValueGenerator;
var typeSchema = parameters.Schema.ActualTypeSchema;
var dictionaryValueType = parameters.Resolver.TryResolve(typeSchema.AdditionalPropertiesSchema, parameters.TypeNameHint) ?? "any";
var dictionaryValueDefaultValue = typeSchema.AdditionalPropertiesSchema != null
? valueGenerator.GetDefaultValue(typeSchema.AdditionalPropertiesSchema,
typeSchema.AdditionalPropertiesSchema.IsNullable(parameters.Settings.SchemaType), dictionaryValueType, parameters.TypeNameHint,
parameters.Settings.GenerateDefaultValues, parameters.Resolver)
: null;
return new
{
NullValue = parameters.NullValue.ToString().ToLowerInvariant(),
Variable = parameters.Variable,
Value = parameters.Value,
HasDefaultValue = valueGenerator.GetDefaultValue(parameters.Schema,
parameters.IsPropertyNullable, type, parameters.TypeNameHint, parameters.Settings.GenerateDefaultValues, parameters.Resolver) != null,
DefaultValue = valueGenerator.GetDefaultValue(parameters.Schema,
parameters.IsPropertyNullable, type, parameters.TypeNameHint, parameters.Settings.GenerateDefaultValues, parameters.Resolver),
Type = type,
CheckNewableObject = parameters.CheckNewableObject,
IsNewableObject = IsNewableObject(parameters.Schema, parameters),
IsDate = IsDate(typeSchema.Format, parameters.Settings.DateTimeType),
IsDateTime = IsDateTime(typeSchema.Format, parameters.Settings.DateTimeType),
IsDictionary = typeSchema.IsDictionary,
DictionaryValueType = dictionaryValueType,
DictionaryValueDefaultValue = dictionaryValueDefaultValue,
HasDictionaryValueDefaultValue = dictionaryValueDefaultValue != null,
IsDictionaryValueNewableObject = typeSchema.AdditionalPropertiesSchema != null && IsNewableObject(typeSchema.AdditionalPropertiesSchema, parameters),
IsDictionaryValueDate = IsDate(typeSchema.AdditionalPropertiesSchema?.ActualSchema?.Format, parameters.Settings.DateTimeType),
IsDictionaryValueDateTime = IsDateTime(typeSchema.AdditionalPropertiesSchema?.ActualSchema?.Format, parameters.Settings.DateTimeType),
IsDictionaryValueNewableArray = typeSchema.AdditionalPropertiesSchema?.ActualSchema?.IsArray == true &&
IsNewableObject(typeSchema.AdditionalPropertiesSchema.Item, parameters),
DictionaryValueArrayItemType = typeSchema.AdditionalPropertiesSchema?.ActualSchema?.IsArray == true ?
parameters.Resolver.TryResolve(typeSchema.AdditionalPropertiesSchema.Item, "Anonymous") ?? "any" : "any",
IsArray = typeSchema.IsArray,
ArrayItemType = parameters.Resolver.TryResolve(typeSchema.Item, parameters.TypeNameHint) ?? "any",
IsArrayItemNewableObject = typeSchema.Item != null && IsNewableObject(typeSchema.Item, parameters),
IsArrayItemDate = IsDate(typeSchema.Item?.Format, parameters.Settings.DateTimeType),
IsArrayItemDateTime = IsDateTime(typeSchema.Item?.Format, parameters.Settings.DateTimeType),
RequiresStrictPropertyInitialization = parameters.Settings.TypeScriptVersion >= 2.7m,
//StringToDateCode is used for date and date-time formats
UseJsDate = parameters.Settings.DateTimeType == TypeScriptDateTimeType.Date,
StringToDateCode = GetStringToDateTime(parameters, typeSchema),
DateToStringCode = GetDateToString(parameters, typeSchema),
DateTimeToStringCode = GetDateTimeToString(parameters, typeSchema),
HandleReferences = parameters.Settings.HandleReferences
};
}
private static string GetStringToDateTime(DataConversionParameters parameters, JsonSchema typeSchema)
{
switch (parameters.Settings.DateTimeType)
{
case TypeScriptDateTimeType.Date:
return "new Date";
case TypeScriptDateTimeType.MomentJS:
case TypeScriptDateTimeType.OffsetMomentJS:
if (typeSchema.Format is JsonFormatStrings.Duration or JsonFormatStrings.TimeSpan)
{
return "moment.duration";
}
if (parameters.Settings.DateTimeType == TypeScriptDateTimeType.OffsetMomentJS)
{
return "moment.parseZone";
}
return "moment";
case TypeScriptDateTimeType.String:
return "";
case TypeScriptDateTimeType.Luxon:
if (typeSchema.Format is JsonFormatStrings.Duration or JsonFormatStrings.TimeSpan)
{
return "Duration.fromISO";
}
return "DateTime.fromISO";
case TypeScriptDateTimeType.DayJS:
return "dayjs";
default:
throw new ArgumentOutOfRangeException();
}
}
private static string GetDateToString(DataConversionParameters parameters, JsonSchema typeSchema)
{
switch (parameters.Settings.DateTimeType)
{
case TypeScriptDateTimeType.Date:
case TypeScriptDateTimeType.String:
return "";
case TypeScriptDateTimeType.MomentJS:
case TypeScriptDateTimeType.OffsetMomentJS:
case TypeScriptDateTimeType.DayJS:
return "format('YYYY-MM-DD')";
case TypeScriptDateTimeType.Luxon:
return "toFormat('yyyy-MM-dd')";
default:
throw new ArgumentOutOfRangeException();
}
}
private static string GetDateTimeToString(DataConversionParameters parameters, JsonSchema typeSchema)
{
switch (parameters.Settings.DateTimeType)
{
case TypeScriptDateTimeType.Date:
return "toISOString()";
case TypeScriptDateTimeType.MomentJS:
case TypeScriptDateTimeType.OffsetMomentJS:
if (typeSchema.Format is JsonFormatStrings.Duration or JsonFormatStrings.TimeSpan)
{
return "format('d.hh:mm:ss.SS', { trim: false })";
}
if (parameters.Settings.DateTimeType == TypeScriptDateTimeType.OffsetMomentJS)
{
return "toISOString(true)";
}
return "toISOString()";
case TypeScriptDateTimeType.String:
return "";
case TypeScriptDateTimeType.Luxon:
return "toString()";
case TypeScriptDateTimeType.DayJS:
if (typeSchema.Format is JsonFormatStrings.Duration or JsonFormatStrings.TimeSpan)
{
return "format('d.hh:mm:ss.SSS')";
}
return "toISOString()";
default:
throw new ArgumentOutOfRangeException();
}
}
private static bool IsDateTime(string format, TypeScriptDateTimeType type)
{
// TODO: Make this more generic (see TypeScriptTypeResolver.ResolveString)
if (type == TypeScriptDateTimeType.Date)
{
if (format == JsonFormatStrings.DateTime)
{
return true;
}
if (format == JsonFormatStrings.Time)
{
return false;
}
if (format is JsonFormatStrings.Duration or JsonFormatStrings.TimeSpan)
{
return false;
}
}
else if (type == TypeScriptDateTimeType.DayJS ||
type == TypeScriptDateTimeType.MomentJS ||
type == TypeScriptDateTimeType.OffsetMomentJS)
{
if (format == JsonFormatStrings.DateTime)
{
return true;
}
if (format == JsonFormatStrings.Time)
{
return true;
}
if (format is JsonFormatStrings.Duration or JsonFormatStrings.TimeSpan)
{
return true;
}
}
else if (type == TypeScriptDateTimeType.Luxon)
{
if (format == JsonFormatStrings.DateTime)
{
return true;
}
if (format == JsonFormatStrings.Time)
{
return true;
}
if (format is JsonFormatStrings.Duration or JsonFormatStrings.TimeSpan)
{
return true;
}
}
return false;
}
private static bool IsDate(string format, TypeScriptDateTimeType type)
{
// TODO: Make this more generic (see TypeScriptTypeResolver.ResolveString)
if (type == TypeScriptDateTimeType.Date)
{
if (format == JsonFormatStrings.Date)
{
return true;
}
}
else if (type == TypeScriptDateTimeType.DayJS ||
type == TypeScriptDateTimeType.MomentJS ||
type == TypeScriptDateTimeType.OffsetMomentJS)
{
if (format == JsonFormatStrings.Date)
{
return true;
}
}
else if (type == TypeScriptDateTimeType.Luxon)
{
if (format == JsonFormatStrings.Date)
{
return true;
}
}
return false;
}
private static bool IsNewableObject(JsonSchema schema, DataConversionParameters parameters)
{
if (schema.ActualTypeSchema.IsEnumeration)
{
return false;
}
return parameters.Resolver.GeneratesType(schema);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
#if CORECLR
using System.Runtime.Loader;
#endif
using System.Reflection;
using System.IO;
class InstanceFieldTest : MyClass
{
public int Value;
}
class InstanceFieldTest2 : InstanceFieldTest
{
public int Value2;
}
[StructLayout(LayoutKind.Sequential)]
class InstanceFieldTestWithLayout : MyClassWithLayout
{
public int Value;
}
class GrowingBase
{
MyGrowingStruct s;
}
class InheritingFromGrowingBase : GrowingBase
{
public int x;
}
static class OpenClosedDelegateExtension
{
public static string OpenClosedDelegateTarget(this string x, string foo)
{
return x + ", " + foo;
}
}
class Program
{
static void TestVirtualMethodCalls()
{
var o = new MyClass();
Assert.AreEqual(o.VirtualMethod(), "Virtual method result");
var iface = (IMyInterface)o;
Assert.AreEqual(iface.InterfaceMethod(" "), "Interface result");
Assert.AreEqual(MyClass.TestInterfaceMethod(iface, "+"), "Interface+result");
}
static void TestMovedVirtualMethods()
{
var o = new MyChildClass();
Assert.AreEqual(o.MovedToBaseClass(), "MovedToBaseClass");
Assert.AreEqual(o.ChangedToVirtual(), "ChangedToVirtual");
if (!LLILCJitEnabled)
{
o = null;
try
{
o.MovedToBaseClass();
}
catch (NullReferenceException)
{
try
{
o.ChangedToVirtual();
}
catch (NullReferenceException)
{
return;
}
}
Assert.AreEqual("NullReferenceException", "thrown");
}
}
static void TestConstrainedMethodCalls()
{
using (MyStruct s = new MyStruct())
{
((Object)s).ToString();
}
}
static void TestConstrainedMethodCalls_Unsupported()
{
MyStruct s = new MyStruct();
s.ToString();
}
static void TestInterop()
{
// Verify both intra-module and inter-module PInvoke interop
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
MyClass.GetTickCount();
}
else
{
MyClass.GetCurrentThreadId();
}
MyClass.TestInterop();
}
static void TestStaticFields()
{
MyClass.StaticObjectField = 894;
MyClass.StaticLongField = 4392854;
MyClass.StaticNullableGuidField = new Guid("0D7E505F-E767-4FEF-AEEC-3243A3005673");
MyClass.ThreadStaticStringField = "Hello";
MyClass.ThreadStaticIntField = 735;
MyClass.ThreadStaticDateTimeField = new DateTime(2011, 1, 1);
MyClass.TestStaticFields();
#if false // TODO: Enable once LDFTN is supported
Task.Run(() => {
MyClass.ThreadStaticStringField = "Garbage";
MyClass.ThreadStaticIntField = 0xBAAD;
MyClass.ThreadStaticDateTimeField = DateTime.Now;
}).Wait();
#endif
Assert.AreEqual(MyClass.StaticObjectField, 894 + 12345678 /* + 1234 */);
Assert.AreEqual(MyClass.StaticLongField, (long)(4392854 * 456 /* * 45 */));
Assert.AreEqual(MyClass.StaticNullableGuidField, null);
Assert.AreEqual(MyClass.ThreadStaticStringField, "HelloWorld");
Assert.AreEqual(MyClass.ThreadStaticIntField, 735/78);
Assert.AreEqual(MyClass.ThreadStaticDateTimeField, new DateTime(2011, 1, 1) + new TimeSpan(123));
}
static void TestPreInitializedArray()
{
var a = new int[] { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512 };
int sum = 0;
foreach (var e in a) sum += e;
Assert.AreEqual(sum, 1023);
}
static void TestMultiDimmArray()
{
var a = new int[2,3,4];
a[0,1,2] = a[0,0,0] + a[1,1,1];
a.ToString();
}
static void TestGenericVirtualMethod()
{
var o = new MyGeneric<String, Object>();
Assert.AreEqual(o.GenericVirtualMethod<Program, IEnumerable<String>>(),
"System.StringSystem.ObjectProgramSystem.Collections.Generic.IEnumerable`1[System.String]");
}
static void TestMovedGenericVirtualMethod()
{
var o = new MyChildGeneric<Object>();
Assert.AreEqual(o.MovedToBaseClass<WeakReference>(), typeof(List<WeakReference>).ToString());
Assert.AreEqual(o.ChangedToVirtual<WeakReference>(), typeof(List<WeakReference>).ToString());
if (!LLILCJitEnabled)
{
o = null;
try
{
o.MovedToBaseClass<WeakReference>();
}
catch (NullReferenceException)
{
try
{
o.ChangedToVirtual<WeakReference>();
}
catch (NullReferenceException)
{
return;
}
}
Assert.AreEqual("NullReferenceException", "thrown");
}
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static void TestGenericNonVirtualMethod()
{
var c = new MyChildGeneric<string>();
Assert.AreEqual(CallGeneric(c), "MyGeneric.NonVirtualMethod");
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static string CallGeneric<T>(MyGeneric<T, T> g)
{
return g.NonVirtualMethod();
}
static void TestGenericOverStruct()
{
var o1 = new MyGeneric<String, MyGrowingStruct>();
Assert.AreEqual(o1.GenericVirtualMethod < MyChangingStruct, IEnumerable<Program>>(),
"System.StringMyGrowingStructMyChangingStructSystem.Collections.Generic.IEnumerable`1[Program]");
var o2 = new MyChildGeneric<MyChangingStruct>();
Assert.AreEqual(o2.MovedToBaseClass<MyGrowingStruct>(), typeof(List<MyGrowingStruct>).ToString());
Assert.AreEqual(o2.ChangedToVirtual<MyGrowingStruct>(), typeof(List<MyGrowingStruct>).ToString());
}
static void TestInstanceFields()
{
var t = new InstanceFieldTest2();
t.Value = 123;
t.Value2 = 234;
t.InstanceField = 345;
Assert.AreEqual(typeof(InstanceFieldTest).GetRuntimeField("Value").GetValue(t), 123);
Assert.AreEqual(typeof(InstanceFieldTest2).GetRuntimeField("Value2").GetValue(t), 234);
Assert.AreEqual(typeof(MyClass).GetRuntimeField("InstanceField").GetValue(t), 345);
}
static void TestInstanceFieldsWithLayout()
{
var t = new InstanceFieldTestWithLayout();
t.Value = 123;
Assert.AreEqual(typeof(InstanceFieldTestWithLayout).GetRuntimeField("Value").GetValue(t), 123);
}
static void TestInheritingFromGrowingBase()
{
var o = new InheritingFromGrowingBase();
o.x = 6780;
Assert.AreEqual(typeof(InheritingFromGrowingBase).GetRuntimeField("x").GetValue(o), 6780);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static void TestGrowingStruct()
{
MyGrowingStruct s = MyGrowingStruct.Construct();
MyGrowingStruct.Check(ref s);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static void TestChangingStruct()
{
MyChangingStruct s = MyChangingStruct.Construct();
s.x++;
MyChangingStruct.Check(ref s);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static void TestChangingHFAStruct()
{
MyChangingHFAStruct s = MyChangingHFAStruct.Construct();
MyChangingHFAStruct.Check(s);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static void TestGetType()
{
new MyClass().GetType().ToString();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static void TestStaticBaseCSE()
{
// There should be just one call to CORINFO_HELP_READYTORUN_STATIC_BASE
// in the generated code.
s++;
s++;
Assert.AreEqual(s, 2);
s = 0;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static void TestIsInstCSE()
{
// There should be just one call to CORINFO_HELP_READYTORUN_ISINSTANCEOF
// in the generated code.
object o1 = (s < 1) ? (object)"foo" : (object)1;
Assert.AreEqual(o1 is string, true);
Assert.AreEqual(o1 is string, true);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static void TestCastClassCSE()
{
// There should be just one call to CORINFO_HELP_READYTORUN_CHKCAST
// in the generated code.
object o1 = (s < 1) ? (object)"foo" : (object)1;
string str1 = (string)o1;
string str2 = (string)o1;
Assert.AreEqual(str1, str2);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static void TestRangeCheckElimination()
{
// Range checks for array accesses should be eliminated by the compiler.
int[] array = new int[5];
array[2] = 2;
Assert.AreEqual(array[2], 2);
}
#if CORECLR
class MyLoadContext : AssemblyLoadContext
{
public MyLoadContext()
{
}
public void TestMultipleLoads()
{
Assembly a = LoadFromAssemblyPath(Path.Combine(Directory.GetCurrentDirectory(), "test.ni.dll"));
Assert.AreEqual(AssemblyLoadContext.GetLoadContext(a), this);
}
protected override Assembly Load(AssemblyName an)
{
throw new NotImplementedException();
}
}
static void TestMultipleLoads()
{
if (!LLILCJitEnabled) {
try
{
new MyLoadContext().TestMultipleLoads();
}
catch (FileLoadException e)
{
Assert.AreEqual(e.ToString().Contains("Native image cannot be loaded multiple times"), true);
return;
}
Assert.AreEqual("FileLoadException", "thrown");
}
}
#endif
static void TestFieldLayoutNGenMixAndMatch()
{
// This test is verifying consistent field layout when ReadyToRun images are combined with NGen images
// "ngen install /nodependencies main.exe" to exercise the interesting case
var o = new ByteChildClass(67);
Assert.AreEqual(o.ChildByte, (byte)67);
}
static void TestOpenClosedDelegate()
{
// This test is verifying the the fixups for open vs. closed delegate created against the same target
// method are encoded correctly.
Func<string, string, object> idOpen = OpenClosedDelegateExtension.OpenClosedDelegateTarget;
Assert.AreEqual(idOpen("World", "foo"), "World, foo");
Func<string, object> idClosed = "World".OpenClosedDelegateTarget;
Assert.AreEqual(idClosed("hey"), "World, hey");
}
static void RunAllTests()
{
TestVirtualMethodCalls();
TestMovedVirtualMethods();
TestConstrainedMethodCalls();
TestConstrainedMethodCalls_Unsupported();
TestInterop();
TestStaticFields();
TestPreInitializedArray();
TestMultiDimmArray();
TestGenericVirtualMethod();
TestMovedGenericVirtualMethod();
TestGenericNonVirtualMethod();
TestGenericOverStruct();
TestInstanceFields();
TestInstanceFieldsWithLayout();
TestInheritingFromGrowingBase();
TestGrowingStruct();
TestChangingStruct();
TestChangingHFAStruct();
TestGetType();
#if CORECLR
TestMultipleLoads();
#endif
TestFieldLayoutNGenMixAndMatch();
TestStaticBaseCSE();
TestIsInstCSE();
TestCastClassCSE();
TestRangeCheckElimination();
TestOpenClosedDelegate();
}
static int Main()
{
// Code compiled by LLILC jit can't catch exceptions yet so the tests
// don't throw them if LLILC jit is enabled. This should be removed once
// exception catching is supported by LLILC jit.
string AltJitName = System.Environment.GetEnvironmentVariable("complus_altjitname");
LLILCJitEnabled =
((AltJitName != null) && AltJitName.ToLower().StartsWith("llilcjit") &&
((System.Environment.GetEnvironmentVariable("complus_altjit") != null) ||
(System.Environment.GetEnvironmentVariable("complus_altjitngen") != null)));
// Run all tests 3x times to exercise both slow and fast paths work
for (int i = 0; i < 3; i++)
RunAllTests();
Console.WriteLine("PASSED");
return Assert.HasAssertFired ? 1 : 100;
}
static bool LLILCJitEnabled;
static int s;
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Diagnostics;
namespace Eto
{
/// <summary>
/// Base platform handler for widgets
/// </summary>
/// <remarks>
/// This is the base class for platform handlers.
/// It is used to help wire up events and provide base functionality of a widget.
///
/// If you are creating an InstanceWidget, you should use <see cref="WidgetHandler{T,W}"/>.
/// </remarks>
/// <example>
/// This example shows how to implement a platform handler for a widget called StaticWidget
/// <code><![CDATA[
/// // override the class and implement widget-specific interface
/// public MyStaticWidgetHandler : WidgetHandler<StaticWidget>, IStaticWidget
/// {
/// // implement IStaticWidget's properties and methods
/// }
/// ]]></code>
/// </example>
/// <seealso cref="WidgetHandler{T,W}"/>
/// <typeparam name="TWidget">Type of widget the handler is for</typeparam>
public abstract class WidgetHandler<TWidget> : Widget.IHandler, IDisposable
where TWidget: Widget
{
const string InstanceEventSuffix = ".Instance";
/// <summary>
/// Gets the widget that this platform handler is attached to
/// </summary>
public TWidget Widget { get; private set; }
static readonly object IDKey = new object();
/// <summary>
/// Gets or sets the ID of this widget
/// </summary>
public virtual string ID
{
get { return Widget.Properties.Get<string>(IDKey); }
set { Widget.Properties[IDKey] = value; }
}
/// <summary>
/// Gets a value indicating that the specified event is handled
/// </summary>
/// <param name="id">Identifier of the event</param>
/// <returns>True if the event is handled, otherwise false</returns>
public bool IsEventHandled(string id)
{
return Widget.Properties.ContainsKey(id) || EventLookup.IsDefault(Widget, id) || Widget.Properties.ContainsKey(id + InstanceEventSuffix);
}
/// <summary>
/// Gets the callback object for the control
/// </summary>
/// <remarks>
/// This object is typically a single static instance that is used by the platform handlers to call private or protected
/// methods on the widget, such as protected event methods e.g. protected virtual void OnClick(EventArgs e)
/// </remarks>
/// <value>The callback.</value>
protected object Callback { get { return ((ICallbackSource)Widget).Callback; } }
/// <summary>
/// Called to handle a specific event
/// </summary>
/// <remarks>
/// Most events are late bound by this method. Instead of wiring all events, this
/// will be called with an event string that is defined by the control.
///
/// This is called automatically when attaching to events, but must be called manually
/// when users of the control only override the event's On... method.
///
/// Override the <see cref="AttachEvent"/> to attach your events
/// </remarks>
/// <seealso cref="AttachEvent"/>
/// <param name="id">ID of the event to handle</param>
/// <param name="defaultEvent">True if the event is default (e.g. overridden or via an event handler subscription)</param>
public void HandleEvent(string id, bool defaultEvent = false)
{
if (defaultEvent)
{
if (!Widget.Properties.ContainsKey(id + InstanceEventSuffix))
AttachEvent(id);
}
else if (!Widget.Properties.ContainsKey(id) && !EventLookup.IsDefault(Widget, id))
{
var instanceId = id + InstanceEventSuffix;
if (Widget.Properties.ContainsKey(instanceId))
return;
Widget.Properties.Add(instanceId, true);
AttachEvent(id);
}
}
/// <summary>
/// Attaches the specified event to the platform-specific control
/// </summary>
/// <remarks>
/// Implementors should override this method to handle any events that the widget
/// supports. Ensure to call the base class' implementation if the event is not
/// one the specific widget supports, so the base class' events can be handled as well.
/// </remarks>
/// <param name="id">Identifier of the event</param>
public virtual void AttachEvent(string id)
{
#if DEBUG
// only throw for platforms that should be fully implemented, and only in debug
if (Widget.Platform.IsGtk || Widget.Platform.IsMac || Widget.Platform.IsWinForms || Widget.Platform.IsWpf)
throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Event {0} not supported by this control", id));
#endif
}
/// <summary>
/// Called to initialize this widget after it has been constructed
/// </summary>
/// <remarks>
/// Override this to initialize any of the platform objects. This is called
/// in the widget constructor, after all of the widget's constructor code has been called.
/// </remarks>
protected virtual void Initialize()
{
Style.OnStyleWidgetDefaults(this);
}
void Widget.IHandler.Initialize()
{
Initialize();
}
/// <summary>
/// Gets or sets the widget instance
/// </summary>
Widget Widget.IHandler.Widget
{
get { return Widget; }
set
{
Widget = (TWidget)value;
}
}
/// <summary>
/// Gets the native platform-specific handle for integration purposes
/// </summary>
/// <value>The native handle.</value>
public virtual IntPtr NativeHandle { get { return IntPtr.Zero; } }
#region IDisposable Members
/// <summary>
/// Disposes this object
/// </summary>
/// <remarks>
/// To handle disposal logic, use the <see cref="Dispose(bool)"/> method.
/// </remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
/// <summary>
/// Disposes the object
/// </summary>
/// <param name="disposing">True when disposed manually, false if disposed via the finalizer</param>
protected virtual void Dispose(bool disposing)
{
}
}
/// <summary>
/// Base platform handler for <see cref="Widget"/> objects that have a backing platform object
/// </summary>
/// <remarks>
/// This is the base class for platform handlers.
/// It is used to help wire up events and provide base functionality of a widget.
/// </remarks>
/// <example>
/// This example shows how to implement a platform handler for a widget
/// <code><![CDATA[
/// // override the class and implement widget-specific interface
/// public MyWidgetHandler : WidgetHandler<MyPlatformControl, MyWidget>, IMyWidget
/// {
/// // implement IStaticWidget's properties and methods
/// }
/// ]]></code>
/// </example>
/// <seealso cref="WidgetHandler{T,W}"/>
/// <typeparam name="TControl">Type of the platform-specific object</typeparam>
/// <typeparam name="TWidget">Type of widget the handler is for</typeparam>
public abstract class WidgetHandler<TControl, TWidget> : WidgetHandler<TWidget>, IControlObjectSource
where TWidget: Widget
{
/// <summary>
/// Initializes a new instance of the WidgetHandler class
/// </summary>
protected WidgetHandler()
{
}
/// <summary>
/// Gets a value indicating that control should automatically be disposed when this widget is disposed
/// </summary>
protected virtual bool DisposeControl { get { return true; } }
/// <summary>
/// Gets or sets the platform-specific control object
/// </summary>
public TControl Control { get; protected set; }
/// <summary>
/// Gets the platform-specific control object
/// </summary>
object IControlObjectSource.ControlObject { get { return Control; } }
/// <summary>
/// Disposes this widget and the associated control if <see cref="DisposeControl"/> is <c>true</c>
/// </summary>
/// <param name="disposing">True if <see cref="Dispose"/> was called manually, false if called from the finalizer</param>
protected override void Dispose(bool disposing)
{
if (disposing && DisposeControl)
{
//Console.WriteLine ("{0}: 1. Disposing control {1}, {2}", this.WidgetID, this.Control.GetType (), this.GetType ());
var control = Control as IDisposable;
if (control != null)
control.Dispose();
}
//Console.WriteLine ("{0}: 2. Disposed handler {1}", this.WidgetID, this.GetType ());
Control = default(TControl);
base.Dispose(disposing);
}
/// <summary>
/// Gets the platform-specific control object of the specified widget using this handler
/// </summary>
/// <remarks>
/// The widget must be using a handler that returns the same control.
///
/// This can be used very easily by platform code:
/// <code>
/// MyControl mycontrol;
/// var platformControl = MyControlHandler.GetControl(mycontrol);
/// </code>
///
/// Note that even if the specified handler is used, the control might not actually be using that
/// handler. This method will still work as long as the handler implements using the same base platform-specific control.
/// </remarks>
/// <param name="widget">The widget to get the platform-specific control from</param>
/// <returns>The platform-specific control used for the specified widget</returns>
public static TControl GetControl(TWidget widget)
{
var handler = (WidgetHandler<TControl, TWidget>)widget.Handler;
return handler.Control;
}
static readonly object connector_key = new object();
/// <summary>
/// Gets a weak connector class to hook up events to the underlying control
/// </summary>
/// <remarks>
/// Some frameworks (e.g. gtk, monomac, ios, android) keep track of references in a way that leak objects when
/// there is a circular reference between the control and the handler. This is the case when registering events
/// from the control to a method implemented in the handler.
/// This instance can be used to connect the objects together using a weak reference to the handler, allowing
/// controls to be garbage collected.
/// </remarks>
/// <value>The connector instance</value>
protected WeakConnector Connector
{
get
{
object connectorObject;
if (Widget.Properties.TryGetValue(connector_key, out connectorObject))
return (WeakConnector)connectorObject;
var connector = CreateConnector();
connector.Handler = this;
Widget.Properties[connector_key] = connector;
return connector;
}
}
/// <summary>
/// Creates the event connector for this control
/// </summary>
/// <remarks>
/// This creates the weak connector to use for event registration and other purposes.
/// </remarks>
/// <seealso cref="Connector"/>
protected virtual WeakConnector CreateConnector()
{
return new WeakConnector();
}
/// <summary>
/// Connector for events to keep a weak reference to allow controls to be garbage collected when no longer referenced
/// </summary>
/// <seealso cref="Connector"/>
protected class WeakConnector
{
WeakReference handler;
/// <summary>
/// Gets the handler that the connector is associated with
/// </summary>
/// <remarks>
/// This property is used to access the handler instance to trigger events.
/// </remarks>
/// <value>The handler.</value>
public WidgetHandler<TControl, TWidget> Handler { get { return (WidgetHandler<TControl, TWidget>)handler.Target; } internal set { handler = new WeakReference(value); } }
}
}
/// <summary>
/// Widget handler with type-specific callback
/// </summary>
/// <remarks>
/// This can be used by controls that have events to trigger using a callback class.
/// </remarks>
/// <example>
/// This is a full example showing a new control with a handler-triggered event and a property.
/// <code>
/// // in your eto-only dll:
/// public class MyEtoControl : Eto.Forms.Control
/// {
///
/// // define an event that is triggered by the handler
/// public const string MySomethingEvent = "MyEtoControl.MySomething";
///
/// public event EventHandler<EventArgs> MySomething
/// {
/// add { Properties.AddHandlerEvent(MySomethingEvent, value); }
/// remove { Properties.RemoveEvent(MySomethingEvent, value); }
/// }
///
/// // allow subclasses to override the event
/// protected virtual void OnMySomething(EventArgs e)
/// {
/// Properties.TriggerEvent(MySomethingEvent, this, e);
/// }
///
/// static MyEtoControl()
/// {
/// RegisterEvent<MyEtoControl>(c => c.OnMySomething(null), MySomethingEvent);
/// }
///
/// // defines the callback interface to trigger the event from handlers
/// public interface ICallback : Eto.Control.ICallback
/// {
/// void OnMySomething(MyEtoControl widget, EventArgs e);
/// }
///
/// // defines the callback implementation
/// protected class Callback : Eto.Control.Callback, ICallback
/// {
/// public void OnMySomething(MyEtoControl widget, EventArgs e)
/// {
/// widget.Platform.Invoke(() => widget.OnMySomething(e));
/// }
/// }
///
/// // create single instance of the callback, and tell Eto we want to use it
/// static readonly object callback = new Callback();
/// protected override object GetCallback() { return callback; }
///
/// // handler interface for other methods/properties
/// public interface IHandler : Eto.Control.IHandler
/// {
/// string MyProperty { get; set; }
/// }
///
/// new IHandler Handler { get { (IHandler)base.Handler; } }
///
/// public string MyProperty { get { return Handler.MyProperty; } set { Handler.MyProperty = value; } }
/// }
///
///
/// // in each platform-specific dll:
/// public class MyHandler : WidgetHandler<PlatformSpecificControl, MyEtoControl, MyEtoControl.ICallback> : MyEtoControl.IHandler
/// {
/// public MyHandler()
/// {
/// Control = new PlatformSpecificControl();
/// }
///
/// public string MyProperty { get; set; }
///
/// public override void AttachEvent(string id)
/// {
/// switch (id)
/// {
/// case MyEtoControl.MySomethingEvent:
/// Control.SomeEvent += (sender, e) => Callback.OnMySomething(EventArgs.Empty);
/// break;
///
/// default:
/// base.AttachEvent(id);
/// break;
/// }
/// }
/// }
/// </code>
/// </example>
/// <typeparam name="TControl">Type of the platform-specific object</typeparam>
/// <typeparam name="TWidget">Type of widget the handler is for</typeparam>
/// <typeparam name="TCallback">Type of the callback</typeparam>
public abstract class WidgetHandler<TControl, TWidget, TCallback> : WidgetHandler<TControl, TWidget>
where TWidget: Widget
{
/// <summary>
/// Gets the callback object for the control
/// </summary>
/// <remarks>
/// This object is typically a single static instance that is used by the platform handlers to call private or protected
/// methods on the widget, such as protected event methods e.g. protected virtual void OnClick(EventArgs e)
/// </remarks>
/// <value>The callback.</value>
public new TCallback Callback { get { return (TCallback)base.Callback; } }
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
public struct ValX0 { }
public struct ValY0 { }
public struct ValX1<T> { }
public struct ValY1<T> { }
public struct ValX2<T, U> { }
public struct ValY2<T, U> { }
public struct ValX3<T, U, V> { }
public struct ValY3<T, U, V> { }
public class RefX0 { }
public class RefY0 { }
public class RefX1<T> { }
public class RefY1<T> { }
public class RefX2<T, U> { }
public class RefY2<T, U> { }
public class RefX3<T, U, V> { }
public class RefY3<T, U, V> { }
public class GenException<T> : Exception { }
public class Gen<T>
{
public static bool ExceptionTest(bool throwException)
{
if (throwException)
{
throw new GenException<T>();
}
else
{
return true;
}
}
}
public class Test
{
public static int counter = 0;
public static bool result = true;
public static void Eval(bool exp)
{
if (!exp)
{
result = exp;
Console.WriteLine("Test Failed at location: " + counter);
}
counter++;
}
public static int Main()
{
int cLabel = 0;
while (cLabel < 50)
{
try
{
switch (cLabel)
{
case 0: cLabel++; Gen<int>.ExceptionTest(true); break;
case 1: cLabel++; Gen<double>.ExceptionTest(true); break;
case 2: cLabel++; Gen<string>.ExceptionTest(true); break;
case 3: cLabel++; Gen<object>.ExceptionTest(true); break;
case 4: cLabel++; Gen<Guid>.ExceptionTest(true); break;
case 5: cLabel++; Gen<int[]>.ExceptionTest(true); break;
case 6: cLabel++; Gen<double[,]>.ExceptionTest(true); break;
case 7: cLabel++; Gen<string[][][]>.ExceptionTest(true); break;
case 8: cLabel++; Gen<object[, , ,]>.ExceptionTest(true); break;
case 9: cLabel++; Gen<Guid[][, , ,][]>.ExceptionTest(true); break;
case 10: cLabel++; Gen<RefX1<int>[]>.ExceptionTest(true); break;
case 11: cLabel++; Gen<RefX1<double>[,]>.ExceptionTest(true); break;
case 12: cLabel++; Gen<RefX1<string>[][][]>.ExceptionTest(true); break;
case 13: cLabel++; Gen<RefX1<object>[, , ,]>.ExceptionTest(true); break;
case 14: cLabel++; Gen<RefX1<Guid>[][, , ,][]>.ExceptionTest(true); break;
case 15: cLabel++; Gen<RefX2<int, int>[]>.ExceptionTest(true); break;
case 16: cLabel++; Gen<RefX2<double, double>[,]>.ExceptionTest(true); break;
case 17: cLabel++; Gen<RefX2<string, string>[][][]>.ExceptionTest(true); break;
case 18: cLabel++; Gen<RefX2<object, object>[, , ,]>.ExceptionTest(true); break;
case 19: cLabel++; Gen<RefX2<Guid, Guid>[][, , ,][]>.ExceptionTest(true); break;
case 20: cLabel++; Gen<ValX1<int>[]>.ExceptionTest(true); break;
case 21: cLabel++; Gen<ValX1<double>[,]>.ExceptionTest(true); break;
case 22: cLabel++; Gen<ValX1<string>[][][]>.ExceptionTest(true); break;
case 23: cLabel++; Gen<ValX1<object>[, , ,]>.ExceptionTest(true); break;
case 24: cLabel++; Gen<ValX1<Guid>[][, , ,][]>.ExceptionTest(true); break;
case 25: cLabel++; Gen<ValX2<int, int>[]>.ExceptionTest(true); break;
case 26: cLabel++; Gen<ValX2<double, double>[,]>.ExceptionTest(true); break;
case 27: cLabel++; Gen<ValX2<string, string>[][][]>.ExceptionTest(true); break;
case 28: cLabel++; Gen<ValX2<object, object>[, , ,]>.ExceptionTest(true); break;
case 29: cLabel++; Gen<ValX2<Guid, Guid>[][, , ,][]>.ExceptionTest(true); break;
case 30: cLabel++; Gen<RefX1<int>>.ExceptionTest(true); break;
case 31: cLabel++; Gen<RefX1<ValX1<int>>>.ExceptionTest(true); break;
case 32: cLabel++; Gen<RefX2<int, string>>.ExceptionTest(true); break;
case 33: cLabel++; Gen<RefX3<int, string, Guid>>.ExceptionTest(true); break;
case 34: cLabel++; Gen<RefX1<RefX1<int>>>.ExceptionTest(true); break;
case 35: cLabel++; Gen<RefX1<RefX1<RefX1<string>>>>.ExceptionTest(true); break;
case 36: cLabel++; Gen<RefX1<RefX1<RefX1<RefX1<Guid>>>>>.ExceptionTest(true); break;
case 37: cLabel++; Gen<RefX1<RefX2<int, string>>>.ExceptionTest(true); break;
case 38: cLabel++; Gen<RefX2<RefX2<RefX1<int>, RefX3<int, string, RefX1<RefX2<int, string>>>>, RefX2<RefX1<int>, RefX3<int, string, RefX1<RefX2<int, string>>>>>>.ExceptionTest(true); break;
case 39: cLabel++; Gen<RefX3<RefX1<int[][, , ,]>, RefX2<object[, , ,][][], Guid[][][]>, RefX3<double[, , , , , , , , , ,], Guid[][][][, , , ,][, , , ,][][][], string[][][][][][][][][][][]>>>.ExceptionTest(true); break;
case 40: cLabel++; Gen<ValX1<int>>.ExceptionTest(true); break;
case 41: cLabel++; Gen<ValX1<RefX1<int>>>.ExceptionTest(true); break;
case 42: cLabel++; Gen<ValX2<int, string>>.ExceptionTest(true); break;
case 43: cLabel++; Gen<ValX3<int, string, Guid>>.ExceptionTest(true); break;
case 44: cLabel++; Gen<ValX1<ValX1<int>>>.ExceptionTest(true); break;
case 45: cLabel++; Gen<ValX1<ValX1<ValX1<string>>>>.ExceptionTest(true); break;
case 46: cLabel++; Gen<ValX1<ValX1<ValX1<ValX1<Guid>>>>>.ExceptionTest(true); break;
case 47: cLabel++; Gen<ValX1<ValX2<int, string>>>.ExceptionTest(true); break;
case 48: cLabel++; Gen<ValX2<ValX2<ValX1<int>, ValX3<int, string, ValX1<ValX2<int, string>>>>, ValX2<ValX1<int>, ValX3<int, string, ValX1<ValX2<int, string>>>>>>.ExceptionTest(true); break;
case 49: cLabel++; Gen<ValX3<ValX1<int[][, , ,]>, ValX2<object[, , ,][][], Guid[][][]>, ValX3<double[, , , , , , , , , ,], Guid[][][][, , , ,][, , , ,][][][], string[][][][][][][][][][][]>>>.ExceptionTest(true); break;
}
}
catch (GenException<int>) { Eval(cLabel == 1); }
catch (GenException<double>) { Eval(cLabel == 2); }
catch (GenException<string>) { Eval(cLabel == 3); }
catch (GenException<object>) { Eval(cLabel == 4); }
catch (GenException<Guid>) { Eval(cLabel == 5); }
catch (GenException<int[]>) { Eval(cLabel == 6); }
catch (GenException<double[,]>) { Eval(cLabel == 7); }
catch (GenException<string[][][]>) { Eval(cLabel == 8); }
catch (GenException<object[, , ,]>) { Eval(cLabel == 9); }
catch (GenException<Guid[][, , ,][]>) { Eval(cLabel == 10); }
catch (GenException<RefX1<int>[]>) { Eval(cLabel == 11); }
catch (GenException<RefX1<double>[,]>) { Eval(cLabel == 12); }
catch (GenException<RefX1<string>[][][]>) { Eval(cLabel == 13); }
catch (GenException<RefX1<object>[, , ,]>) { Eval(cLabel == 14); }
catch (GenException<RefX1<Guid>[][, , ,][]>) { Eval(cLabel == 15); }
catch (GenException<RefX2<int, int>[]>) { Eval(cLabel == 16); }
catch (GenException<RefX2<double, double>[,]>) { Eval(cLabel == 17); }
catch (GenException<RefX2<string, string>[][][]>) { Eval(cLabel == 18); }
catch (GenException<RefX2<object, object>[, , ,]>) { Eval(cLabel == 19); }
catch (GenException<RefX2<Guid, Guid>[][, , ,][]>) { Eval(cLabel == 20); }
catch (GenException<ValX1<int>[]>) { Eval(cLabel == 21); }
catch (GenException<ValX1<double>[,]>) { Eval(cLabel == 22); }
catch (GenException<ValX1<string>[][][]>) { Eval(cLabel == 23); }
catch (GenException<ValX1<object>[, , ,]>) { Eval(cLabel == 24); }
catch (GenException<ValX1<Guid>[][, , ,][]>) { Eval(cLabel == 25); }
catch (GenException<ValX2<int, int>[]>) { Eval(cLabel == 26); }
catch (GenException<ValX2<double, double>[,]>) { Eval(cLabel == 27); }
catch (GenException<ValX2<string, string>[][][]>) { Eval(cLabel == 28); }
catch (GenException<ValX2<object, object>[, , ,]>) { Eval(cLabel == 29); }
catch (GenException<ValX2<Guid, Guid>[][, , ,][]>) { Eval(cLabel == 30); }
catch (GenException<RefX1<int>>) { Eval(cLabel == 31); }
catch (GenException<RefX1<ValX1<int>>>) { Eval(cLabel == 32); }
catch (GenException<RefX2<int, string>>) { Eval(cLabel == 33); }
catch (GenException<RefX3<int, string, Guid>>) { Eval(cLabel == 34); }
catch (GenException<RefX1<RefX1<int>>>) { Eval(cLabel == 35); }
catch (GenException<RefX1<RefX1<RefX1<string>>>>) { Eval(cLabel == 36); }
catch (GenException<RefX1<RefX1<RefX1<RefX1<Guid>>>>>) { Eval(cLabel == 37); }
catch (GenException<RefX1<RefX2<int, string>>>) { Eval(cLabel == 38); }
catch (GenException<RefX2<RefX2<RefX1<int>, RefX3<int, string, RefX1<RefX2<int, string>>>>, RefX2<RefX1<int>, RefX3<int, string, RefX1<RefX2<int, string>>>>>>) { Eval(cLabel == 39); }
catch (GenException<RefX3<RefX1<int[][, , ,]>, RefX2<object[, , ,][][], Guid[][][]>, RefX3<double[, , , , , , , , , ,], Guid[][][][, , , ,][, , , ,][][][], string[][][][][][][][][][][]>>>) { Eval(cLabel == 40); }
catch (GenException<ValX1<int>>) { Eval(cLabel == 41); }
catch (GenException<ValX1<RefX1<int>>>) { Eval(cLabel == 42); }
catch (GenException<ValX2<int, string>>) { Eval(cLabel == 43); }
catch (GenException<ValX3<int, string, Guid>>) { Eval(cLabel == 44); }
catch (GenException<ValX1<ValX1<int>>>) { Eval(cLabel == 45); }
catch (GenException<ValX1<ValX1<ValX1<string>>>>) { Eval(cLabel == 46); }
catch (GenException<ValX1<ValX1<ValX1<ValX1<Guid>>>>>) { Eval(cLabel == 47); }
catch (GenException<ValX1<ValX2<int, string>>>) { Eval(cLabel == 48); }
catch (GenException<ValX2<ValX2<ValX1<int>, ValX3<int, string, ValX1<ValX2<int, string>>>>, ValX2<ValX1<int>, ValX3<int, string, ValX1<ValX2<int, string>>>>>>) { Eval(cLabel == 49); }
catch (GenException<ValX3<ValX1<int[][, , ,]>, ValX2<object[, , ,][][], Guid[][][]>, ValX3<double[, , , , , , , , , ,], Guid[][][][, , , ,][, , , ,][][][], string[][][][][][][][][][][]>>>) { Eval(cLabel == 50); }
}
if (result)
{
Console.WriteLine("Test Passed");
return 100;
}
else
{
Console.WriteLine("Test Failed");
return 1;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcdv = Google.Cloud.DataQnA.V1Alpha;
using sys = System;
namespace Google.Cloud.DataQnA.V1Alpha
{
/// <summary>Resource name for the <c>UserFeedback</c> resource.</summary>
public sealed partial class UserFeedbackName : gax::IResourceName, sys::IEquatable<UserFeedbackName>
{
/// <summary>The possible contents of <see cref="UserFeedbackName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/questions/{question}/userFeedback</c>.
/// </summary>
ProjectLocationQuestion = 1,
}
private static gax::PathTemplate s_projectLocationQuestion = new gax::PathTemplate("projects/{project}/locations/{location}/questions/{question}/userFeedback");
/// <summary>Creates a <see cref="UserFeedbackName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="UserFeedbackName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static UserFeedbackName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new UserFeedbackName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="UserFeedbackName"/> with the pattern
/// <c>projects/{project}/locations/{location}/questions/{question}/userFeedback</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="questionId">The <c>Question</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="UserFeedbackName"/> constructed from the provided ids.</returns>
public static UserFeedbackName FromProjectLocationQuestion(string projectId, string locationId, string questionId) =>
new UserFeedbackName(ResourceNameType.ProjectLocationQuestion, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), questionId: gax::GaxPreconditions.CheckNotNullOrEmpty(questionId, nameof(questionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="UserFeedbackName"/> with pattern
/// <c>projects/{project}/locations/{location}/questions/{question}/userFeedback</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="questionId">The <c>Question</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="UserFeedbackName"/> with pattern
/// <c>projects/{project}/locations/{location}/questions/{question}/userFeedback</c>.
/// </returns>
public static string Format(string projectId, string locationId, string questionId) =>
FormatProjectLocationQuestion(projectId, locationId, questionId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="UserFeedbackName"/> with pattern
/// <c>projects/{project}/locations/{location}/questions/{question}/userFeedback</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="questionId">The <c>Question</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="UserFeedbackName"/> with pattern
/// <c>projects/{project}/locations/{location}/questions/{question}/userFeedback</c>.
/// </returns>
public static string FormatProjectLocationQuestion(string projectId, string locationId, string questionId) =>
s_projectLocationQuestion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(questionId, nameof(questionId)));
/// <summary>Parses the given resource name string into a new <see cref="UserFeedbackName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/questions/{question}/userFeedback</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="userFeedbackName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="UserFeedbackName"/> if successful.</returns>
public static UserFeedbackName Parse(string userFeedbackName) => Parse(userFeedbackName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="UserFeedbackName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/questions/{question}/userFeedback</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="userFeedbackName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="UserFeedbackName"/> if successful.</returns>
public static UserFeedbackName Parse(string userFeedbackName, bool allowUnparsed) =>
TryParse(userFeedbackName, allowUnparsed, out UserFeedbackName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="UserFeedbackName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/questions/{question}/userFeedback</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="userFeedbackName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="UserFeedbackName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string userFeedbackName, out UserFeedbackName result) =>
TryParse(userFeedbackName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="UserFeedbackName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/questions/{question}/userFeedback</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="userFeedbackName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="UserFeedbackName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string userFeedbackName, bool allowUnparsed, out UserFeedbackName result)
{
gax::GaxPreconditions.CheckNotNull(userFeedbackName, nameof(userFeedbackName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationQuestion.TryParseName(userFeedbackName, out resourceName))
{
result = FromProjectLocationQuestion(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(userFeedbackName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private UserFeedbackName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string questionId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
ProjectId = projectId;
QuestionId = questionId;
}
/// <summary>
/// Constructs a new instance of a <see cref="UserFeedbackName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/questions/{question}/userFeedback</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="questionId">The <c>Question</c> ID. Must not be <c>null</c> or empty.</param>
public UserFeedbackName(string projectId, string locationId, string questionId) : this(ResourceNameType.ProjectLocationQuestion, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), questionId: gax::GaxPreconditions.CheckNotNullOrEmpty(questionId, nameof(questionId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Question</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string QuestionId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationQuestion: return s_projectLocationQuestion.Expand(ProjectId, LocationId, QuestionId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as UserFeedbackName);
/// <inheritdoc/>
public bool Equals(UserFeedbackName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(UserFeedbackName a, UserFeedbackName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(UserFeedbackName a, UserFeedbackName b) => !(a == b);
}
public partial class UserFeedback
{
/// <summary>
/// <see cref="gcdv::UserFeedbackName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::UserFeedbackName UserFeedbackName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::UserFeedbackName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using XCommon.Application.Executes;
using XCommon.Extensions.Converters;
using XCommon.Patterns.Ioc;
using XCommon.Patterns.Repository.Entity;
using XCommon.Patterns.Specification.Query;
using XCommon.Patterns.Specification.Validation;
namespace XCommon.Patterns.Repository
{
public abstract class RepositoryEFBase<TEntity, TFilter, TData, TContext> : IRepositoryEF<TEntity, TFilter>
where TEntity : EntityBase, new()
where TFilter : FilterBase, new()
where TData : class, new()
where TContext : DbContext, new()
{
public RepositoryEFBase()
{
Kernel.Resolve(this);
}
#region Inject
[Inject]
protected virtual ISpecificationValidation<TEntity> SpecificationValidate { get; set; }
[Inject]
protected virtual ISpecificationQuery<TData, TFilter> SpecificationQuery { get; set; }
#endregion
#region Internal
protected virtual string GetEntityName()
{
return typeof(TEntity).Name.Replace("Entity", string.Empty);
}
#endregion
#region Get
public virtual async Task<TEntity> GetByKeyAsync(Guid key)
=> await GetFirstByFilterAsync(new TFilter { Key = key });
public virtual async Task<TEntity> GetFirstByFilterAsync(TFilter filter)
=> (await GetByFilterAsync(filter)).FirstOrDefault();
public virtual async Task<List<TEntity>> GetByFilterAsync(TFilter filter)
{
var result = new List<TEntity>();
using (var db = new TContext())
{
var query = SpecificationQuery.Build(db.Set<TData>(), filter);
await query.ForEachAsync(data =>
{
result.Add(data.Convert<TEntity>());
});
}
return result;
}
#endregion
#region Save
protected virtual async Task<Execute> BeforeSaveAsync(List<TEntity> entities)
{
return await Task.FromResult(new Execute());
}
protected virtual async Task<Execute> AfterSaveAsync(List<TEntity> entities)
{
return await Task.Run(() =>
{
entities.RemoveAll(c => c.Action == EntityAction.Delete);
return new Execute();
});
}
protected virtual async Task<Execute> SaveInternalAsync(List<TEntity> entities, DbContext context)
{
var execute = new Execute();
// Call Before Save
await BeforeSaveAsync(entities);
// Validate the enties
execute.AddMessage(await ValidateManyAsync(entities));
// Something wrong? STOP!
if (execute.HasErro)
{
return execute;
}
// Attach deleted entities to the DBContext
foreach (var entity in entities.Where(c => c.Action == EntityAction.Delete))
{
try
{
var dataEntity = entity.Convert<TData>();
context.Entry(dataEntity).State = EntityState.Deleted;
}
catch (Exception ex)
{
execute.AddException(ex, "Error on delete info to: {0}", GetEntityName());
}
}
// Attach new entities to the DBContext
foreach (var entity in entities.Where(c => c.Action == EntityAction.New))
{
try
{
var dataEntity = entity.Convert<TData>();
context.Entry(dataEntity).State = EntityState.Added;
}
catch (Exception ex)
{
execute.AddException(ex, "Error on insert info to: {0}", GetEntityName());
}
}
// Attach updated entities to the DBContext
foreach (var entity in entities.Where(c => c.Action == EntityAction.Update))
{
try
{
var dataEntity = entity.Convert<TData>();
context.Entry(dataEntity).State = EntityState.Modified;
}
catch (Exception ex)
{
execute.AddException(ex, "Error on update info to: {0}", GetEntityName());
}
}
// If it's okay so far, try to save it and call after save.
if (!execute.HasErro)
{
try
{
await context.SaveChangesAsync();
await AfterSaveAsync(entities);
}
catch (Exception ex)
{
execute.AddException(ex, "Error on savechanges in: {0}", GetEntityName());
}
}
return execute;
}
public async Task<Execute<TEntity>> SaveAsync(TEntity entity)
{
using (var db = new TContext())
{
return await SaveAsync(entity, db);
}
}
public virtual async Task<Execute<TEntity>> SaveAsync(TEntity entity, DbContext context)
{
var resultList = await SaveManyAsync(new List<TEntity> { entity }, context);
var result = new Execute<TEntity>(resultList)
{
Entity = resultList.Entity.FirstOrDefault()
};
return result;
}
public virtual async Task<Execute<List<TEntity>>> SaveManyAsync(List<TEntity> entities)
{
using (var db = new TContext())
{
return await SaveManyAsync(entities, db);
}
}
public virtual async Task<Execute<List<TEntity>>> SaveManyAsync(List<TEntity> entities, DbContext context)
{
var result = new Execute<List<TEntity>>
{
Entity = entities
};
var saveResult = await SaveInternalAsync(result.Entity, context);
result.AddMessage(saveResult);
return result;
}
#endregion
#region Validate
public virtual async Task<Execute> ValidateAsync(TEntity entity)
=> await ValidateManyAsync(new List<TEntity> { entity });
public virtual async Task<Execute> ValidateManyAsync(List<TEntity> entity)
{
var result = new Execute();
foreach (var item in entity)
{
await SpecificationValidate.IsSatisfiedByAsync(item, result);
}
return result;
}
#endregion
}
}
| |
#pragma warning disable SA1633 // File should have header - This is an imported file,
// original header with license shall remain the same
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Universal charset detector code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Shy Shalom <shooshX@gmail.com>
* Rudi Pettazzi <rudi.pettazzi@gmail.com> (C# port)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
using UtfUnknown.Core.Models;
namespace UtfUnknown.Core.Models.MultiByte;
internal class UTF8_SMModel : StateMachineModel
{
private static readonly int[] UTF8_cls =
{
BitPackage.Pack4bits(
1,
1,
1,
1,
1,
1,
1,
1), // 00 - 07
BitPackage.Pack4bits(
1,
1,
1,
1,
1,
1,
0,
0), // 08 - 0f
BitPackage.Pack4bits(
1,
1,
1,
1,
1,
1,
1,
1), // 10 - 17
BitPackage.Pack4bits(
1,
1,
1,
0,
1,
1,
1,
1), // 18 - 1f
BitPackage.Pack4bits(
1,
1,
1,
1,
1,
1,
1,
1), // 20 - 27
BitPackage.Pack4bits(
1,
1,
1,
1,
1,
1,
1,
1), // 28 - 2f
BitPackage.Pack4bits(
1,
1,
1,
1,
1,
1,
1,
1), // 30 - 37
BitPackage.Pack4bits(
1,
1,
1,
1,
1,
1,
1,
1), // 38 - 3f
BitPackage.Pack4bits(
1,
1,
1,
1,
1,
1,
1,
1), // 40 - 47
BitPackage.Pack4bits(
1,
1,
1,
1,
1,
1,
1,
1), // 48 - 4f
BitPackage.Pack4bits(
1,
1,
1,
1,
1,
1,
1,
1), // 50 - 57
BitPackage.Pack4bits(
1,
1,
1,
1,
1,
1,
1,
1), // 58 - 5f
BitPackage.Pack4bits(
1,
1,
1,
1,
1,
1,
1,
1), // 60 - 67
BitPackage.Pack4bits(
1,
1,
1,
1,
1,
1,
1,
1), // 68 - 6f
BitPackage.Pack4bits(
1,
1,
1,
1,
1,
1,
1,
1), // 70 - 77
BitPackage.Pack4bits(
1,
1,
1,
1,
1,
1,
1,
1), // 78 - 7f
BitPackage.Pack4bits(
2,
2,
2,
2,
3,
3,
3,
3), // 80 - 87
BitPackage.Pack4bits(
4,
4,
4,
4,
4,
4,
4,
4), // 88 - 8f
BitPackage.Pack4bits(
4,
4,
4,
4,
4,
4,
4,
4), // 90 - 97
BitPackage.Pack4bits(
4,
4,
4,
4,
4,
4,
4,
4), // 98 - 9f
BitPackage.Pack4bits(
5,
5,
5,
5,
5,
5,
5,
5), // a0 - a7
BitPackage.Pack4bits(
5,
5,
5,
5,
5,
5,
5,
5), // a8 - af
BitPackage.Pack4bits(
5,
5,
5,
5,
5,
5,
5,
5), // b0 - b7
BitPackage.Pack4bits(
5,
5,
5,
5,
5,
5,
5,
5), // b8 - bf
BitPackage.Pack4bits(
0,
0,
6,
6,
6,
6,
6,
6), // c0 - c7
BitPackage.Pack4bits(
6,
6,
6,
6,
6,
6,
6,
6), // c8 - cf
BitPackage.Pack4bits(
6,
6,
6,
6,
6,
6,
6,
6), // d0 - d7
BitPackage.Pack4bits(
6,
6,
6,
6,
6,
6,
6,
6), // d8 - df
BitPackage.Pack4bits(
7,
8,
8,
8,
8,
8,
8,
8), // e0 - e7
BitPackage.Pack4bits(
8,
8,
8,
8,
8,
9,
8,
8), // e8 - ef
BitPackage.Pack4bits(
10,
11,
11,
11,
11,
11,
11,
11), // f0 - f7
BitPackage.Pack4bits(
12,
13,
13,
13,
14,
15,
0,
0) // f8 - ff
};
private static readonly int[] UTF8_st =
{
BitPackage.Pack4bits(
ERROR,
START,
ERROR,
ERROR,
ERROR,
ERROR,
12,
10), //00-07
BitPackage.Pack4bits(
9,
11,
8,
7,
6,
5,
4,
3), //08-0f
BitPackage.Pack4bits(
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR), //10-17
BitPackage.Pack4bits(
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR), //18-1f
BitPackage.Pack4bits(
ITSME,
ITSME,
ITSME,
ITSME,
ITSME,
ITSME,
ITSME,
ITSME), //20-27
BitPackage.Pack4bits(
ITSME,
ITSME,
ITSME,
ITSME,
ITSME,
ITSME,
ITSME,
ITSME), //28-2f
BitPackage.Pack4bits(
ERROR,
ERROR,
5,
5,
5,
5,
ERROR,
ERROR), //30-37
BitPackage.Pack4bits(
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR), //38-3f
BitPackage.Pack4bits(
ERROR,
ERROR,
ERROR,
5,
5,
5,
ERROR,
ERROR), //40-47
BitPackage.Pack4bits(
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR), //48-4f
BitPackage.Pack4bits(
ERROR,
ERROR,
7,
7,
7,
7,
ERROR,
ERROR), //50-57
BitPackage.Pack4bits(
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR), //58-5f
BitPackage.Pack4bits(
ERROR,
ERROR,
ERROR,
ERROR,
7,
7,
ERROR,
ERROR), //60-67
BitPackage.Pack4bits(
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR), //68-6f
BitPackage.Pack4bits(
ERROR,
ERROR,
9,
9,
9,
9,
ERROR,
ERROR), //70-77
BitPackage.Pack4bits(
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR), //78-7f
BitPackage.Pack4bits(
ERROR,
ERROR,
ERROR,
ERROR,
9,
9,
ERROR,
ERROR), //80-87
BitPackage.Pack4bits(
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR), //88-8f
BitPackage.Pack4bits(
ERROR,
ERROR,
12,
12,
12,
12,
ERROR,
ERROR), //90-97
BitPackage.Pack4bits(
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR), //98-9f
BitPackage.Pack4bits(
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
12,
ERROR,
ERROR), //a0-a7
BitPackage.Pack4bits(
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR), //a8-af
BitPackage.Pack4bits(
ERROR,
ERROR,
12,
12,
12,
ERROR,
ERROR,
ERROR), //b0-b7
BitPackage.Pack4bits(
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR), //b8-bf
BitPackage.Pack4bits(
ERROR,
ERROR,
START,
START,
START,
START,
ERROR,
ERROR), //c0-c7
BitPackage.Pack4bits(
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR,
ERROR) //c8-cf
};
private static readonly int[] UTF8CharLenTable =
{
0,
1,
0,
0,
0,
0,
2,
3,
3,
3,
4,
4,
5,
5,
6,
6
};
public UTF8_SMModel()
: base(
new BitPackage(
BitPackage.INDEX_SHIFT_4BITS,
BitPackage.SHIFT_MASK_4BITS,
BitPackage.BIT_SHIFT_4BITS,
BitPackage.UNIT_MASK_4BITS,
UTF8_cls),
16,
new BitPackage(
BitPackage.INDEX_SHIFT_4BITS,
BitPackage.SHIFT_MASK_4BITS,
BitPackage.BIT_SHIFT_4BITS,
BitPackage.UNIT_MASK_4BITS,
UTF8_st),
UTF8CharLenTable,
CodepageName.UTF8) { }
}
| |
#pragma warning disable CS1998
using Grpc.Core;
using FluentAssertions;
using MagicOnion.Client;
using MagicOnion.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
using System.Diagnostics;
using Grpc.Net.Client;
using MessagePack;
namespace MagicOnion.Server.Tests
{
public interface IClientFilterTestService : IService<IClientFilterTestService>
{
UnaryResult<int> Unary1(int x, int y);
UnaryResult<Nil> HeaderEcho();
UnaryResult<Nil> AlwaysError();
}
public class ClientFilterTestService : ServiceBase<IClientFilterTestService>, IClientFilterTestService
{
public async UnaryResult<int> Unary1(int x, int y)
{
return x + y;
}
public UnaryResult<Nil> HeaderEcho()
{
foreach (var item in Context.CallContext.RequestHeaders)
{
Context.CallContext.ResponseTrailers.Add(item);
}
return ReturnNil();
}
public UnaryResult<Nil> AlwaysError()
{
throw new Exception("Ok, throw error!");
}
}
public class CountFilter : IClientFilter
{
public int CalledCount;
public int FilterCount;
public CountFilter(int count)
{
this.FilterCount = count;
}
public async ValueTask<ResponseContext> SendAsync(RequestContext context, Func<RequestContext, ValueTask<ResponseContext>> next)
{
CalledCount++;
var response = (await next(context)).As<int>();
var newResult = await response.ResponseAsync;
return response.WithNewResult(newResult + 10);
}
}
public class AppendHeaderFilter : IClientFilter
{
public async ValueTask<ResponseContext> SendAsync(RequestContext context, Func<RequestContext, ValueTask<ResponseContext>> next)
{
var header = context.CallOptions.Headers;
header.Add("x-foo", "abcdefg");
header.Add("x-bar", "hijklmn");
var response = await next(context);
return response;
}
}
public class LoggingFilter : IClientFilter
{
public async ValueTask<ResponseContext> SendAsync(RequestContext context, Func<RequestContext, ValueTask<ResponseContext>> next)
{
Console.WriteLine("Request Begin:" + context.MethodPath);
var sw = Stopwatch.StartNew();
var response = await next(context);
sw.Stop();
Console.WriteLine("Request Completed:" + context.MethodPath + ", Elapsed:" + sw.Elapsed.TotalMilliseconds + "ms");
return response;
}
}
public class ResponseHandlingFilter : IClientFilter
{
public async ValueTask<ResponseContext> SendAsync(RequestContext context, Func<RequestContext, ValueTask<ResponseContext>> next)
{
var response = await next(context);
if (context.MethodPath == "ICalc/Sum")
{
var sumResult = await response.GetResponseAs<int>();
Console.WriteLine("Called Sum, Result:" + sumResult);
}
return response;
}
}
public class MockRequestFilter : IClientFilter
{
public async ValueTask<ResponseContext> SendAsync(RequestContext context, Func<RequestContext, ValueTask<ResponseContext>> next)
{
if (context.MethodPath == "ICalc/Sum")
{
// don't call next, return mock result.
return new ResponseContext<int>(9999);
}
return await next(context);
}
}
public class RetryFilter : IClientFilter
{
public async ValueTask<ResponseContext> SendAsync(RequestContext context, Func<RequestContext, ValueTask<ResponseContext>> next)
{
Exception lastException = null;
var retryCount = 0;
while (retryCount != 3)
{
try
{
// using same CallOptions so be careful to add duplicate headers or etc.
return await next(context);
}
catch (Exception ex)
{
lastException = ex;
}
retryCount++;
}
throw new RetryFailedException(retryCount, lastException);
}
}
public class RetryFailedException : Exception
{
public int RetryCount { get; }
public Exception LastException { get; }
public RetryFailedException(int retryCount, Exception lastException)
{
this.RetryCount = retryCount;
this.LastException = lastException;
}
}
public class ClientFilterTest : IClassFixture<ServerFixture<ClientFilterTestService>>
{
ITestOutputHelper logger;
GrpcChannel channel;
public ClientFilterTest(ITestOutputHelper logger, ServerFixture<ClientFilterTestService> server)
{
this.logger = logger;
this.channel = server.DefaultChannel;
}
[Fact]
public async Task SimpleFilter()
{
for (int i = 1; i <= 20; i++)
{
var filters = Enumerable.Range(0, i).Select(_ => new CountFilter(i)).ToArray();
var client = MagicOnionClient.Create<IClientFilterTestService>(channel, filters);
var r0 = await client.Unary1(1000, 2000);
r0.Should().Be(3000 + 10 * i);
foreach (var item in filters)
{
item.CalledCount.Should().Be(1);
}
}
}
[Fact]
public async Task HeaderEcho()
{
var res = MagicOnionClient.Create<IClientFilterTestService>(channel, new IClientFilter[]
{
new AppendHeaderFilter(),
new RetryFilter()
}).HeaderEcho();
await res;
var trailers = res.GetTrailers();
trailers.Should().ContainSingle(x => x.Key == "x-foo" && x.Value == "abcdefg");
trailers.Should().ContainSingle(x => x.Key == "x-bar" && x.Value == "hijklmn");
}
[Fact]
public async Task ErrorRetry()
{
var ex = await Assert.ThrowsAsync<RetryFailedException>(async () =>
{
var filter = new RetryFilter();
await MagicOnionClient.Create<IClientFilterTestService>(channel, new IClientFilter[]
{
filter
}).AlwaysError();
});
ex.RetryCount.Should().Be(3);
logger.WriteLine(ex.LastException.ToString());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Collections.Tests
{
public static class CollectionBaseTests
{
[Fact]
public static void Ctor_Empty()
{
var collBase = new MyCollection();
var arrList = new ArrayList();
Assert.Equal(0, collBase.Capacity);
Assert.Equal(arrList.Capacity, collBase.Capacity);
Assert.Equal(0, collBase.InnerListCapacity);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(10)]
[InlineData(1024)]
public static void Ctor_Capacity(int capacity)
{
var collBase = new MyCollection(capacity);
var arrList = new ArrayList(capacity);
Assert.Equal(capacity, collBase.Capacity);
Assert.Equal(arrList.Capacity, collBase.Capacity);
Assert.Equal(capacity, collBase.InnerListCapacity);
}
[Fact]
public static void CtorCapacity_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("capacity", () => new MyCollection(-1)); // Capacity < 0
Assert.Throws<OutOfMemoryException>(() => new MyCollection(int.MaxValue)); // Capacity is too large
}
private static Foo CreateValue(int i) => new Foo(i, i.ToString());
private static MyCollection CreateCollection(int count)
{
var collBase = new MyCollection();
for (int i = 0; i < 100; i++)
{
collBase.Add(CreateValue(i));
}
return collBase;
}
[Fact]
public static void Add()
{
MyCollection collBase = new MyCollection();
for (int i = 0; i < 100; i++)
{
Foo value = CreateValue(i);
collBase.Add(value);
Assert.True(collBase.Contains(value));
}
Assert.Equal(100, collBase.Count);
for (int i = 0; i < collBase.Count; i++)
{
Foo value = CreateValue(i);
Assert.Equal(value, collBase[i]);
}
}
[Fact]
public static void Remove()
{
MyCollection collBase = CreateCollection(100);
for (int i = 0; i < 100; i++)
{
Foo value = CreateValue(i);
collBase.Remove(value);
Assert.False(collBase.Contains(value));
}
Assert.Equal(0, collBase.Count);
}
[Fact]
public static void Remove_Invalid()
{
MyCollection collBase = CreateCollection(100);
Assert.Throws<ArgumentException>(null, () => collBase.Remove(new Foo())); // Non existent object
Assert.Equal(100, collBase.Count);
}
[Fact]
public static void Insert()
{
var collBase = new MyCollection();
for (int i = 0; i < 100; i++)
{
Foo value = CreateValue(i);
collBase.Insert(i, value);
Assert.True(collBase.Contains(value));
}
Assert.Equal(100, collBase.Count);
for (int i = 0; i < collBase.Count; i++)
{
var expected = CreateValue(i);
Assert.Equal(expected, collBase[i]);
}
}
[Fact]
public static void Insert_InvalidIndex_ThrowsArgumentOutOfRangeException()
{
MyCollection collBase = CreateCollection(100);
Assert.Throws<ArgumentOutOfRangeException>("index", () => collBase.Insert(-1, new Foo())); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => collBase.Insert(collBase.Count + 1, new Foo())); // Index > collBase.Count
Assert.Equal(100, collBase.Count);
}
[Fact]
public static void RemoveAt()
{
MyCollection collBase = CreateCollection(100);
for (int i = 0; i < collBase.Count; i++)
{
collBase.RemoveAt(0);
Assert.False(collBase.Contains(CreateValue(i)));
}
}
[Fact]
public static void RemoveAt_InvalidIndex_ThrowsArgumentOutOfRangeException()
{
MyCollection collBase = CreateCollection(100);
Assert.Throws<ArgumentOutOfRangeException>("index", () => collBase.RemoveAt(-1)); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => collBase.RemoveAt(collBase.Count)); // Index > collBase.Count
Assert.Equal(100, collBase.Count);
}
[Fact]
public static void Clear()
{
MyCollection collBase = CreateCollection(100);
collBase.Clear();
Assert.Equal(0, collBase.Count);
}
[Fact]
public static void IndexOf()
{
MyCollection collBase = CreateCollection(100);
for (int i = 0; i < collBase.Count; i++)
{
int ndx = collBase.IndexOf(CreateValue(i));
Assert.Equal(i, ndx);
}
}
[Fact]
public static void Contains()
{
MyCollection collBase = CreateCollection(100);
for (int i = 0; i < collBase.Count; i++)
{
Assert.True(collBase.Contains(CreateValue(i)));
}
Assert.False(collBase.Contains(new Foo()));
}
[Fact]
public static void Item_Get()
{
MyCollection collBase = CreateCollection(100);
for (int i = 0; i < collBase.Count; i++)
{
Assert.Equal(CreateValue(i), collBase[i]);
}
}
[Fact]
public static void Item_Get_InvalidIndex_ThrowsArgumentOutOfRangeException()
{
MyCollection collBase = CreateCollection(100);
Assert.Throws<ArgumentOutOfRangeException>("index", () => collBase[-1]); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => collBase[collBase.Count]); // Index >= InnerList.Count
}
[Fact]
public static void Item_Set()
{
MyCollection collBase = CreateCollection(100);
for (int i = 0; i < collBase.Count; i++)
{
var value = CreateValue(collBase.Count - i);
collBase[i] = value;
Assert.Equal(value, collBase[i]);
}
}
[Fact]
public static void Item_Set_Invalid()
{
MyCollection collBase = CreateCollection(100);
Assert.Throws<ArgumentOutOfRangeException>("index", () => collBase[-1] = new Foo()); // Index < 0
Assert.Throws<ArgumentOutOfRangeException>("index", () => collBase[collBase.Count] = new Foo()); // Index >= InnerList.Count
Assert.Throws<ArgumentNullException>("value", () => collBase[0] = null); // Object is null
}
[Fact]
public static void CopyTo()
{
MyCollection collBase = CreateCollection(100);
// Basic
var fooArr = new Foo[100];
collBase.CopyTo(fooArr, 0);
Assert.Equal(collBase.Count, fooArr.Length);
for (int i = 0; i < fooArr.Length; i++)
{
Assert.Equal(collBase[i], fooArr.GetValue(i));
}
// With index
fooArr = new Foo[collBase.Count * 2];
collBase.CopyTo(fooArr, collBase.Count);
for (int i = collBase.Count; i < fooArr.Length; i++)
{
Assert.Equal(collBase[i - collBase.Count], fooArr.GetValue(i));
}
}
[Fact]
public static void CopyTo_Invalid()
{
MyCollection collBase = CreateCollection(100);
var fooArr = new Foo[100];
// Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", "dstIndex", () => collBase.CopyTo(fooArr, -1));
// Index + fooArray.Length > collBase.Count
AssertExtensions.Throws<ArgumentException>("destinationArray", string.Empty, () => collBase.CopyTo(fooArr, 50));
}
[Fact]
public static void GetEnumerator()
{
MyCollection collBase = CreateCollection(100);
IEnumerator enumerator = collBase.GetEnumerator();
Assert.NotNull(enumerator);
int count = 0;
while (enumerator.MoveNext())
{
Assert.Equal(collBase[count], enumerator.Current);
count++;
}
Assert.Equal(collBase.Count, count);
}
[Fact]
public static void GetEnumerator_Invalid()
{
MyCollection collBase = CreateCollection(100);
IEnumerator enumerator = collBase.GetEnumerator();
// Index < 0
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Index >= dictionary.Count
while (enumerator.MoveNext()) ;
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.False(enumerator.MoveNext());
// Current throws after resetting
enumerator.Reset();
Assert.True(enumerator.MoveNext());
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
}
[Fact]
public static void SyncRoot()
{
// SyncRoot should be the reference to the underlying collection, not to MyCollection
var collBase = new MyCollection();
object syncRoot = collBase.SyncRoot;
Assert.NotEqual(syncRoot, collBase);
Assert.Equal(collBase.SyncRoot, collBase.SyncRoot);
}
[Fact]
public static void IListProperties()
{
MyCollection collBase = CreateCollection(100);
Assert.False(collBase.IsFixedSize);
Assert.False(collBase.IsReadOnly);
Assert.False(collBase.IsSynchronized);
}
[Fact]
public static void CapacityGet()
{
var collBase = new MyCollection(new string[10]);
Assert.True(collBase.Capacity >= collBase.Count);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(44)]
public static void CapacitySet(int capacity)
{
var collBase = new MyCollection(0);
collBase.Capacity = capacity;
Assert.Equal(capacity, collBase.Capacity);
}
[Fact]
public static void Capacity_Set_Invalid()
{
var collBase = new MyCollection(new string[10]);
Assert.Throws<ArgumentOutOfRangeException>("value", () => collBase.Capacity = -1); // Capacity < 0
Assert.Throws<OutOfMemoryException>(() => collBase.Capacity = int.MaxValue); // Capacity is very large
Assert.Throws<ArgumentOutOfRangeException>("value", () => collBase.Capacity = collBase.Count - 1); // Capacity < list.Count
}
[Fact]
public static void Add_Called()
{
var f = new Foo(0, "0");
var collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
Assert.True(collBase.OnValidateCalled);
Assert.True(collBase.OnInsertCalled);
Assert.True(collBase.OnInsertCompleteCalled);
Assert.True(collBase.Contains(f));
}
[Fact]
public static void Add_Throws_Called()
{
var f = new Foo(0, "0");
// Throw OnValidate
var collBase = new OnMethodCalledCollectionBase();
collBase.OnValidateThrow = true;
Assert.Throws<Exception>(() => collBase.Add(f));
Assert.Equal(0, collBase.Count);
// Throw OnInsert
collBase = new OnMethodCalledCollectionBase();
collBase.OnInsertThrow = true;
Assert.Throws<Exception>(() => collBase.Add(f));
Assert.Equal(0, collBase.Count);
// Throw OnInsertComplete
collBase = new OnMethodCalledCollectionBase();
collBase.OnInsertCompleteThrow = true;
Assert.Throws<Exception>(() => collBase.Add(f));
Assert.Equal(0, collBase.Count);
}
[Fact]
public static void Insert_Called()
{
var f = new Foo(0, "0");
var collBase = new OnMethodCalledCollectionBase();
collBase.Insert(0, f);
Assert.True(collBase.OnValidateCalled);
Assert.True(collBase.OnInsertCalled);
Assert.True(collBase.OnInsertCompleteCalled);
Assert.True(collBase.Contains(f));
}
[Fact]
public static void Insert_Throws_Called()
{
var f = new Foo(0, "0");
// Throw OnValidate
var collBase = new OnMethodCalledCollectionBase();
collBase.OnValidateThrow = true;
Assert.Throws<Exception>(() => collBase.Insert(0, f));
Assert.Equal(0, collBase.Count);
// Throw OnInsert
collBase = new OnMethodCalledCollectionBase();
collBase.OnInsertThrow = true;
Assert.Throws<Exception>(() => collBase.Insert(0, f));
Assert.Equal(0, collBase.Count);
// Throw OnInsertComplete
collBase = new OnMethodCalledCollectionBase();
collBase.OnInsertCompleteThrow = true;
Assert.Throws<Exception>(() => collBase.Insert(0, f));
Assert.Equal(0, collBase.Count);
}
[Fact]
public static void Remove_Called()
{
var f = new Foo(0, "0");
var collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.OnValidateCalled = false;
collBase.Remove(f);
Assert.True(collBase.OnValidateCalled);
Assert.True(collBase.OnRemoveCalled);
Assert.True(collBase.OnRemoveCompleteCalled);
Assert.False(collBase.Contains(f));
}
[Fact]
public static void Remove_Throws_Called()
{
var f = new Foo(0, "0");
// Throw OnValidate
var collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.OnValidateThrow = true;
Assert.Throws<Exception>(() => collBase.Remove(f));
Assert.Equal(1, collBase.Count);
// Throw OnRemove
collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.OnRemoveThrow = true;
Assert.Throws<Exception>(() => collBase.Remove(f));
Assert.Equal(1, collBase.Count);
// Throw OnRemoveComplete
collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.OnRemoveCompleteThrow = true;
Assert.Throws<Exception>(() => collBase.Remove(f));
Assert.Equal(1, collBase.Count);
}
[Fact]
public static void RemoveAt_Called()
{
var f = new Foo(0, "0");
var collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.OnValidateCalled = false;
collBase.RemoveAt(0);
Assert.True(collBase.OnValidateCalled);
Assert.True(collBase.OnRemoveCalled);
Assert.True(collBase.OnRemoveCompleteCalled);
Assert.False(collBase.Contains(f));
}
[Fact]
public static void RemoveAt_Throws_Called()
{
var f = new Foo(0, "0");
// Throw OnValidate
var collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.OnValidateThrow = true;
Assert.Throws<Exception>(() => collBase.RemoveAt(0));
Assert.Equal(1, collBase.Count);
// Throw OnRemove
collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.OnRemoveThrow = true;
Assert.Throws<Exception>(() => collBase.RemoveAt(0));
Assert.Equal(1, collBase.Count);
// Throw OnRemoveComplete
collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.OnRemoveCompleteThrow = true;
Assert.Throws<Exception>(() => collBase.RemoveAt(0));
Assert.Equal(1, collBase.Count);
}
[Fact]
public static void Clear_Called()
{
var f = new Foo(0, "0");
var collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.Clear();
Assert.True(collBase.OnClearCalled);
Assert.True(collBase.OnClearCompleteCalled);
Assert.Equal(0, collBase.Count);
}
[Fact]
public static void Clear_Throws_Called()
{
var f = new Foo(0, "0");
// Throw OnValidate
var collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.OnValidateThrow = true;
collBase.Clear();
Assert.Equal(0, collBase.Count);
// Throw OnClear
collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.OnClearThrow = true;
Assert.Throws<Exception>(() => collBase.Clear());
Assert.Equal(1, collBase.Count);
// Throw OnClearComplete
collBase = new OnMethodCalledCollectionBase();
collBase.Add(f);
collBase.OnClearCompleteThrow = true;
Assert.Throws<Exception>(() => collBase.Clear());
Assert.Equal(0, collBase.Count);
}
[Fact]
public static void Set_Called()
{
var f = new Foo(1, "1");
var collBase = new OnMethodCalledCollectionBase();
collBase.Add(new Foo());
collBase.OnValidateCalled = false;
collBase[0] = f;
Assert.True(collBase.OnValidateCalled);
Assert.True(collBase.OnSetCalled);
Assert.True(collBase.OnSetCompleteCalled);
Assert.Equal(f, collBase[0]);
}
[Fact]
public static void Set_Throws_Called()
{
var f1 = new Foo(0, "0");
var f2 = new Foo(1, "1");
// Throw OnValidate
var collBase = new OnMethodCalledCollectionBase();
collBase.Add(f1);
collBase.OnValidateThrow = true;
Assert.Throws<Exception>(() => collBase[0] = f2);
Assert.Equal(f1, collBase[0]);
// Throw OnSet
collBase = new OnMethodCalledCollectionBase();
collBase.Add(f1);
collBase.OnSetThrow = true;
Assert.Throws<Exception>(() => collBase[0] = f2);
Assert.Equal(f1, collBase[0]);
// Throw OnSetComplete
collBase = new OnMethodCalledCollectionBase();
collBase.Add(f1);
collBase.OnSetCompleteThrow = true;
Assert.Throws<Exception>(() => collBase[0] = f2);
Assert.Equal(f1, collBase[0]);
}
// CollectionBase is provided to be used as the base class for strongly typed collections. Lets use one of our own here
private class MyCollection : CollectionBase
{
public MyCollection() : base()
{
}
public MyCollection(int capacity) : base(capacity)
{
}
public MyCollection(ICollection collection) : base()
{
foreach (object obj in collection)
{
InnerList.Add(obj);
}
}
public int InnerListCapacity
{
get { return InnerList.Capacity; }
}
public int Add(Foo f1) => List.Add(f1);
public Foo this[int indx]
{
get { return (Foo)List[indx]; }
set { List[indx] = value; }
}
public void CopyTo(Array array, int index) => List.CopyTo(array, index);
public int IndexOf(Foo f) => List.IndexOf(f);
public bool Contains(Foo f) => List.Contains(f);
public void Insert(int index, Foo f) => List.Insert(index, f);
public void Remove(Foo f) => List.Remove(f);
public bool IsSynchronized
{
get { return ((ICollection)this).IsSynchronized; }
}
public object SyncRoot
{
get { return ((ICollection)this).SyncRoot; }
}
public bool IsReadOnly
{
get { return List.IsReadOnly; }
}
public bool IsFixedSize
{
get { return List.IsFixedSize; }
}
}
private class OnMethodCalledCollectionBase : CollectionBase
{
public bool OnValidateCalled;
public bool OnSetCalled;
public bool OnSetCompleteCalled;
public bool OnInsertCalled;
public bool OnInsertCompleteCalled;
public bool OnClearCalled;
public bool OnClearCompleteCalled;
public bool OnRemoveCalled;
public bool OnRemoveCompleteCalled;
public bool OnValidateThrow;
public bool OnSetThrow;
public bool OnSetCompleteThrow;
public bool OnInsertThrow;
public bool OnInsertCompleteThrow;
public bool OnClearThrow;
public bool OnClearCompleteThrow;
public bool OnRemoveThrow;
public bool OnRemoveCompleteThrow;
public int Add(Foo f1) => List.Add(f1);
public Foo this[int indx]
{
get { return (Foo)List[indx]; }
set { List[indx] = value; }
}
public void CopyTo(Array array, int index) => List.CopyTo(array, index);
public int IndexOf(Foo f) => List.IndexOf(f);
public bool Contains(Foo f) => List.Contains(f);
public void Insert(int index, Foo f) => List.Insert(index, f);
public void Remove(Foo f) => List.Remove(f);
protected override void OnSet(int index, object oldValue, object newValue)
{
Assert.True(OnValidateCalled);
Assert.Equal(this[index], oldValue);
OnSetCalled = true;
if (OnSetThrow)
throw new Exception("OnSet");
}
protected override void OnInsert(int index, object value)
{
Assert.True(OnValidateCalled);
Assert.True(index <= Count);
if (index != Count)
{
Assert.Equal(this[index], value);
}
OnInsertCalled = true;
if (OnInsertThrow)
throw new Exception("OnInsert");
}
protected override void OnClear()
{
OnClearCalled = true;
if (OnClearThrow)
throw new Exception("OnClear");
}
protected override void OnRemove(int index, object value)
{
Assert.True(OnValidateCalled);
Assert.Equal(this[index], value);
OnRemoveCalled = true;
if (OnRemoveThrow)
throw new Exception("OnRemove");
}
protected override void OnValidate(object value)
{
OnValidateCalled = true;
if (OnValidateThrow)
throw new Exception("OnValidate");
}
protected override void OnSetComplete(int index, object oldValue, object newValue)
{
Assert.True(OnSetCalled);
Assert.Equal(this[index], newValue);
OnSetCompleteCalled = true;
if (OnSetCompleteThrow)
throw new Exception("OnSetComplete");
}
protected override void OnInsertComplete(int index, object value)
{
Assert.True(OnInsertCalled);
Assert.Equal(this[index], value);
OnInsertCompleteCalled = true;
if (OnInsertCompleteThrow)
throw new Exception("OnInsertComplete");
}
protected override void OnClearComplete()
{
Assert.True(OnClearCalled);
Assert.Equal(0, Count);
Assert.Equal(0, InnerList.Count);
OnClearCompleteCalled = true;
if (OnClearCompleteThrow)
throw new Exception("OnClearComplete");
}
protected override void OnRemoveComplete(int index, object value)
{
Assert.True(OnRemoveCalled);
Assert.NotEqual(IndexOf((Foo)value), index);
OnRemoveCompleteCalled = true;
if (OnRemoveCompleteThrow)
throw new Exception("OnRemoveComplete");
}
}
private class Foo
{
public Foo()
{
}
public Foo(int intValue, string stringValue)
{
IntValue = intValue;
StringValue = stringValue;
}
public int IntValue { get; set; }
public string StringValue { get; set; }
public override bool Equals(object obj)
{
Foo foo = obj as Foo;
if (foo == null)
return false;
return foo.IntValue == IntValue && foo.StringValue == StringValue;
}
public override int GetHashCode() => IntValue;
}
}
}
| |
/*
* Copyright 2021 Google LLC All Rights Reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/api/consumer.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Api {
/// <summary>Holder for reflection information generated from google/api/consumer.proto</summary>
public static partial class ConsumerReflection {
#region Descriptor
/// <summary>File descriptor for google/api/consumer.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ConsumerReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Chlnb29nbGUvYXBpL2NvbnN1bWVyLnByb3RvEgpnb29nbGUuYXBpIj0KEVBy",
"b2plY3RQcm9wZXJ0aWVzEigKCnByb3BlcnRpZXMYASADKAsyFC5nb29nbGUu",
"YXBpLlByb3BlcnR5IqwBCghQcm9wZXJ0eRIMCgRuYW1lGAEgASgJEi8KBHR5",
"cGUYAiABKA4yIS5nb29nbGUuYXBpLlByb3BlcnR5LlByb3BlcnR5VHlwZRIT",
"CgtkZXNjcmlwdGlvbhgDIAEoCSJMCgxQcm9wZXJ0eVR5cGUSDwoLVU5TUEVD",
"SUZJRUQQABIJCgVJTlQ2NBABEggKBEJPT0wQAhIKCgZTVFJJTkcQAxIKCgZE",
"T1VCTEUQBEJoCg5jb20uZ29vZ2xlLmFwaUINQ29uc3VtZXJQcm90b1ABWkVn",
"b29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2FwaS9zZXJ2",
"aWNlY29uZmlnO3NlcnZpY2Vjb25maWdiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.ProjectProperties), global::Google.Api.ProjectProperties.Parser, new[]{ "Properties" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Property), global::Google.Api.Property.Parser, new[]{ "Name", "Type", "Description" }, null, new[]{ typeof(global::Google.Api.Property.Types.PropertyType) }, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// A descriptor for defining project properties for a service. One service may
/// have many consumer projects, and the service may want to behave differently
/// depending on some properties on the project. For example, a project may be
/// associated with a school, or a business, or a government agency, a business
/// type property on the project may affect how a service responds to the client.
/// This descriptor defines which properties are allowed to be set on a project.
///
/// Example:
///
/// project_properties:
/// properties:
/// - name: NO_WATERMARK
/// type: BOOL
/// description: Allows usage of the API without watermarks.
/// - name: EXTENDED_TILE_CACHE_PERIOD
/// type: INT64
/// </summary>
public sealed partial class ProjectProperties : pb::IMessage<ProjectProperties>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<ProjectProperties> _parser = new pb::MessageParser<ProjectProperties>(() => new ProjectProperties());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ProjectProperties> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.ConsumerReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ProjectProperties() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ProjectProperties(ProjectProperties other) : this() {
properties_ = other.properties_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ProjectProperties Clone() {
return new ProjectProperties(this);
}
/// <summary>Field number for the "properties" field.</summary>
public const int PropertiesFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Api.Property> _repeated_properties_codec
= pb::FieldCodec.ForMessage(10, global::Google.Api.Property.Parser);
private readonly pbc::RepeatedField<global::Google.Api.Property> properties_ = new pbc::RepeatedField<global::Google.Api.Property>();
/// <summary>
/// List of per consumer project-specific properties.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Api.Property> Properties {
get { return properties_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ProjectProperties);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ProjectProperties other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!properties_.Equals(other.properties_)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= properties_.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.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 !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
properties_.WriteTo(output, _repeated_properties_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
properties_.WriteTo(ref output, _repeated_properties_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += properties_.CalculateSize(_repeated_properties_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ProjectProperties other) {
if (other == null) {
return;
}
properties_.Add(other.properties_);
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
properties_.AddEntriesFrom(input, _repeated_properties_codec);
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
properties_.AddEntriesFrom(ref input, _repeated_properties_codec);
break;
}
}
}
}
#endif
}
/// <summary>
/// Defines project properties.
///
/// API services can define properties that can be assigned to consumer projects
/// so that backends can perform response customization without having to make
/// additional calls or maintain additional storage. For example, Maps API
/// defines properties that controls map tile cache period, or whether to embed a
/// watermark in a result.
///
/// These values can be set via API producer console. Only API providers can
/// define and set these properties.
/// </summary>
public sealed partial class Property : pb::IMessage<Property>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<Property> _parser = new pb::MessageParser<Property>(() => new Property());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Property> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.ConsumerReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Property() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Property(Property other) : this() {
name_ = other.name_;
type_ = other.type_;
description_ = other.description_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Property Clone() {
return new Property(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// The name of the property (a.k.a key).
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "type" field.</summary>
public const int TypeFieldNumber = 2;
private global::Google.Api.Property.Types.PropertyType type_ = global::Google.Api.Property.Types.PropertyType.Unspecified;
/// <summary>
/// The type of this property.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Api.Property.Types.PropertyType Type {
get { return type_; }
set {
type_ = value;
}
}
/// <summary>Field number for the "description" field.</summary>
public const int DescriptionFieldNumber = 3;
private string description_ = "";
/// <summary>
/// The description of the property
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Description {
get { return description_; }
set {
description_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Property);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Property other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (Type != other.Type) return false;
if (Description != other.Description) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (Type != global::Google.Api.Property.Types.PropertyType.Unspecified) hash ^= Type.GetHashCode();
if (Description.Length != 0) hash ^= Description.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.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 !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (Type != global::Google.Api.Property.Types.PropertyType.Unspecified) {
output.WriteRawTag(16);
output.WriteEnum((int) Type);
}
if (Description.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Description);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (Type != global::Google.Api.Property.Types.PropertyType.Unspecified) {
output.WriteRawTag(16);
output.WriteEnum((int) Type);
}
if (Description.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Description);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (Type != global::Google.Api.Property.Types.PropertyType.Unspecified) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type);
}
if (Description.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Description);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Property other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.Type != global::Google.Api.Property.Types.PropertyType.Unspecified) {
Type = other.Type;
}
if (other.Description.Length != 0) {
Description = other.Description;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 16: {
Type = (global::Google.Api.Property.Types.PropertyType) input.ReadEnum();
break;
}
case 26: {
Description = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 16: {
Type = (global::Google.Api.Property.Types.PropertyType) input.ReadEnum();
break;
}
case 26: {
Description = input.ReadString();
break;
}
}
}
}
#endif
#region Nested types
/// <summary>Container for nested types declared in the Property message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// Supported data type of the property values
/// </summary>
public enum PropertyType {
/// <summary>
/// The type is unspecified, and will result in an error.
/// </summary>
[pbr::OriginalName("UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// The type is `int64`.
/// </summary>
[pbr::OriginalName("INT64")] Int64 = 1,
/// <summary>
/// The type is `bool`.
/// </summary>
[pbr::OriginalName("BOOL")] Bool = 2,
/// <summary>
/// The type is `string`.
/// </summary>
[pbr::OriginalName("STRING")] String = 3,
/// <summary>
/// The type is 'double'.
/// </summary>
[pbr::OriginalName("DOUBLE")] Double = 4,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Runtime.InteropServices;
using System.ComponentModel;
namespace Oranikle.DesignBase.UI.Docking
{
[ToolboxItem(false)]
public partial class DockWindow : Panel, INestedPanesContainer, ISplitterDragSource
{
private DockPanel m_dockPanel;
private DockState m_dockState;
private SplitterControl m_splitter;
private NestedPaneCollection m_nestedPanes;
internal DockWindow(DockPanel dockPanel, DockState dockState)
{
m_nestedPanes = new NestedPaneCollection(this);
m_dockPanel = dockPanel;
m_dockState = dockState;
Visible = false;
SuspendLayout();
if (DockState == DockState.DockLeft || DockState == DockState.DockRight ||
DockState == DockState.DockTop || DockState == DockState.DockBottom)
{
m_splitter = new SplitterControl();
Controls.Add(m_splitter);
}
if (DockState == DockState.DockLeft)
{
Dock = DockStyle.Left;
m_splitter.Dock = DockStyle.Right;
}
else if (DockState == DockState.DockRight)
{
Dock = DockStyle.Right;
m_splitter.Dock = DockStyle.Left;
}
else if (DockState == DockState.DockTop)
{
Dock = DockStyle.Top;
m_splitter.Dock = DockStyle.Bottom;
}
else if (DockState == DockState.DockBottom)
{
Dock = DockStyle.Bottom;
m_splitter.Dock = DockStyle.Top;
}
else if (DockState == DockState.Document)
{
Dock = DockStyle.Fill;
}
ResumeLayout();
}
public VisibleNestedPaneCollection VisibleNestedPanes
{
get { return NestedPanes.VisibleNestedPanes; }
}
public NestedPaneCollection NestedPanes
{
get { return m_nestedPanes; }
}
public DockPanel DockPanel
{
get { return m_dockPanel; }
}
public DockState DockState
{
get { return m_dockState; }
}
public bool IsFloat
{
get { return DockState == DockState.Float; }
}
internal DockPane DefaultPane
{
get { return VisibleNestedPanes.Count == 0 ? null : VisibleNestedPanes[0]; }
}
public virtual Rectangle DisplayingRectangle
{
get
{
Rectangle rect = ClientRectangle;
// if DockWindow is document, exclude the border
if (DockState == DockState.Document)
{
rect.X += 1;
rect.Y += 1;
rect.Width -= 2;
rect.Height -= 2;
}
// exclude the splitter
else if (DockState == DockState.DockLeft)
rect.Width -= Measures.SplitterSize;
else if (DockState == DockState.DockRight)
{
rect.X += Measures.SplitterSize;
rect.Width -= Measures.SplitterSize;
}
else if (DockState == DockState.DockTop)
rect.Height -= Measures.SplitterSize;
else if (DockState == DockState.DockBottom)
{
rect.Y += Measures.SplitterSize;
rect.Height -= Measures.SplitterSize;
}
return rect;
}
}
protected override void OnPaint(PaintEventArgs e)
{
// if DockWindow is document, draw the border
if (DockState == DockState.Document)
e.Graphics.DrawRectangle(SystemPens.ControlDark, ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width - 1, ClientRectangle.Height - 1);
base.OnPaint(e);
}
protected override void OnLayout(LayoutEventArgs levent)
{
VisibleNestedPanes.Refresh();
if (VisibleNestedPanes.Count == 0)
{
if (Visible)
Visible = false;
}
else if (!Visible)
{
Visible = true;
VisibleNestedPanes.Refresh();
}
base.OnLayout (levent);
}
#region ISplitterDragSource Members
void ISplitterDragSource.BeginDrag(Rectangle rectSplitter)
{
}
void ISplitterDragSource.EndDrag()
{
}
bool ISplitterDragSource.IsVertical
{
get { return (DockState == DockState.DockLeft || DockState == DockState.DockRight); }
}
Rectangle ISplitterDragSource.DragLimitBounds
{
get
{
Rectangle rectLimit = DockPanel.DockArea;
Point location;
if ((Control.ModifierKeys & Keys.Shift) == 0)
location = Location;
else
location = DockPanel.DockArea.Location;
if (((ISplitterDragSource)this).IsVertical)
{
rectLimit.X += MeasurePane.MinSize;
rectLimit.Width -= 2 * MeasurePane.MinSize;
rectLimit.Y = location.Y;
if ((Control.ModifierKeys & Keys.Shift) == 0)
rectLimit.Height = Height;
}
else
{
rectLimit.Y += MeasurePane.MinSize;
rectLimit.Height -= 2 * MeasurePane.MinSize;
rectLimit.X = location.X;
if ((Control.ModifierKeys & Keys.Shift) == 0)
rectLimit.Width = Width;
}
return DockPanel.RectangleToScreen(rectLimit);
}
}
void ISplitterDragSource.MoveSplitter(int offset)
{
if ((Control.ModifierKeys & Keys.Shift) != 0)
SendToBack();
Rectangle rectDockArea = DockPanel.DockArea;
if (DockState == DockState.DockLeft && rectDockArea.Width > 0)
{
if (DockPanel.DockLeftPortion > 1)
DockPanel.DockLeftPortion = Width + offset;
else
DockPanel.DockLeftPortion += ((double)offset) / (double)rectDockArea.Width;
}
else if (DockState == DockState.DockRight && rectDockArea.Width > 0)
{
if (DockPanel.DockRightPortion > 1)
DockPanel.DockRightPortion = Width - offset;
else
DockPanel.DockRightPortion -= ((double)offset) / (double)rectDockArea.Width;
}
else if (DockState == DockState.DockBottom && rectDockArea.Height > 0)
{
if (DockPanel.DockBottomPortion > 1)
DockPanel.DockBottomPortion = Height - offset;
else
DockPanel.DockBottomPortion -= ((double)offset) / (double)rectDockArea.Height;
}
else if (DockState == DockState.DockTop && rectDockArea.Height > 0)
{
if (DockPanel.DockTopPortion > 1)
DockPanel.DockTopPortion = Height + offset;
else
DockPanel.DockTopPortion += ((double)offset) / (double)rectDockArea.Height;
}
}
#region IDragSource Members
Control IDragSource.DragControl
{
get { return this; }
}
#endregion
#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.
// #define StressTest // set to raise the amount of time spent in concurrency tests that stress the collections
using System;
using System.Collections.Generic;
using System.Collections.Tests;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Concurrent.Tests
{
public abstract class ProducerConsumerCollectionTests : IEnumerable_Generic_Tests<int>
{
protected override IEnumerable<ModifyEnumerable> ModifyEnumerables => new List<ModifyEnumerable>();
protected override int CreateT(int seed) => new Random(seed).Next();
protected override EnumerableOrder Order => EnumerableOrder.Unspecified;
protected override IEnumerable<int> GenericIEnumerableFactory(int count) => CreateProducerConsumerCollection(count);
protected IProducerConsumerCollection<int> CreateProducerConsumerCollection() => CreateProducerConsumerCollection<int>();
protected IProducerConsumerCollection<int> CreateProducerConsumerCollection(int count) => CreateProducerConsumerCollection(Enumerable.Range(0, count));
protected abstract IProducerConsumerCollection<T> CreateProducerConsumerCollection<T>();
protected abstract IProducerConsumerCollection<int> CreateProducerConsumerCollection(IEnumerable<int> collection);
protected abstract bool IsEmpty(IProducerConsumerCollection<int> pcc);
protected abstract bool TryPeek<T>(IProducerConsumerCollection<T> pcc, out T result);
protected virtual IProducerConsumerCollection<int> CreateOracle() => CreateOracle(Enumerable.Empty<int>());
protected abstract IProducerConsumerCollection<int> CreateOracle(IEnumerable<int> collection);
protected static TaskFactory ThreadFactory { get; } = new TaskFactory(
CancellationToken.None, TaskCreationOptions.LongRunning, TaskContinuationOptions.LongRunning, TaskScheduler.Default);
private const double ConcurrencyTestSeconds =
#if StressTest
8.0;
#else
1.0;
#endif
protected virtual string CopyToNoLengthParamName => "destinationArray";
[Fact]
public void Ctor_InvalidArgs_Throws()
{
AssertExtensions.Throws<ArgumentNullException>("collection", () => CreateProducerConsumerCollection(null));
}
[Fact]
public void Ctor_NoArg_ItemsAndCountMatch()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.Equal(0, c.Count);
Assert.True(IsEmpty(c));
Assert.Equal(Enumerable.Empty<int>(), c);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(1000)]
public void Ctor_Collection_ItemsAndCountMatch(int count)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, count));
IProducerConsumerCollection<int> oracle = CreateOracle(Enumerable.Range(1, count));
Assert.Equal(oracle.Count == 0, IsEmpty(c));
Assert.Equal(oracle.Count, c.Count);
Assert.Equal<int>(oracle, c);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(3)]
[InlineData(1000)]
public void Ctor_InitializeFromCollection_ContainsExpectedItems(int numItems)
{
var expected = new HashSet<int>(Enumerable.Range(0, numItems));
IProducerConsumerCollection<int> pcc = CreateProducerConsumerCollection(expected);
Assert.Equal(expected.Count, pcc.Count);
int item;
var actual = new HashSet<int>();
for (int i = 0; i < expected.Count; i++)
{
Assert.Equal(expected.Count - i, pcc.Count);
Assert.True(pcc.TryTake(out item));
actual.Add(item);
}
Assert.False(pcc.TryTake(out item));
Assert.Equal(0, item);
AssertSetsEqual(expected, actual);
}
[Fact]
public void Add_TakeFromAnotherThread_ExpectedItemsTaken()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.True(IsEmpty(c));
Assert.Equal(0, c.Count);
const int NumItems = 100000;
Task producer = Task.Run(() => Parallel.For(1, NumItems + 1, i => Assert.True(c.TryAdd(i))));
var hs = new HashSet<int>();
while (hs.Count < NumItems)
{
int item;
if (c.TryTake(out item)) hs.Add(item);
}
producer.GetAwaiter().GetResult();
Assert.True(IsEmpty(c));
Assert.Equal(0, c.Count);
AssertSetsEqual(new HashSet<int>(Enumerable.Range(1, NumItems)), hs);
}
[Fact]
public void AddSome_ThenInterleaveAddsAndTakes_MatchesOracle()
{
IProducerConsumerCollection<int> c = CreateOracle();
IProducerConsumerCollection<int> oracle = CreateProducerConsumerCollection();
Action take = () =>
{
int item1;
Assert.True(c.TryTake(out item1));
int item2;
Assert.True(oracle.TryTake(out item2));
Assert.Equal(item1, item2);
Assert.Equal(c.Count, oracle.Count);
Assert.Equal<int>(c, oracle);
};
for (int i = 0; i < 100; i++)
{
Assert.True(oracle.TryAdd(i));
Assert.True(c.TryAdd(i));
Assert.Equal(c.Count, oracle.Count);
Assert.Equal<int>(c, oracle);
// Start taking some after we've added some
if (i > 50)
{
take();
}
}
// Take the rest
while (c.Count > 0)
{
take();
}
}
[Fact]
public void AddTake_RandomChangesMatchOracle()
{
const int Iters = 1000;
var r = new Random(42);
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
IProducerConsumerCollection<int> oracle = CreateOracle();
for (int i = 0; i < Iters; i++)
{
if (r.NextDouble() < .5)
{
Assert.Equal(oracle.TryAdd(i), c.TryAdd(i));
}
else
{
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
}
}
Assert.Equal(oracle.Count, c.Count);
}
[Theory]
[InlineData(100, 1, 100, true)]
[InlineData(100, 4, 10, false)]
[InlineData(1000, 11, 100, true)]
[InlineData(100000, 2, 50000, true)]
public void Initialize_ThenTakeOrPeekInParallel_ItemsObtainedAsExpected(int numStartingItems, int threadsCount, int itemsPerThread, bool take)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, numStartingItems));
int successes = 0;
using (var b = new Barrier(threadsCount))
{
WaitAllOrAnyFailed(Enumerable.Range(0, threadsCount).Select(threadNum => ThreadFactory.StartNew(() =>
{
b.SignalAndWait();
for (int j = 0; j < itemsPerThread; j++)
{
int data;
if (take ? c.TryTake(out data) : TryPeek(c, out data))
{
Interlocked.Increment(ref successes);
Assert.NotEqual(0, data); // shouldn't be default(T)
}
}
})).ToArray());
}
Assert.Equal(
take ? numStartingItems : threadsCount * itemsPerThread,
successes);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(1000)]
public void ToArray_AddAllItemsThenEnumerate_ItemsAndCountMatch(int count)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
IProducerConsumerCollection<int> oracle = CreateOracle();
for (int i = 0; i < count; i++)
{
Assert.Equal(oracle.TryAdd(i + count), c.TryAdd(i + count));
}
Assert.Equal(oracle.ToArray(), c.ToArray());
if (count > 0)
{
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
Assert.Equal(oracle.ToArray(), c.ToArray());
}
}
[Theory]
[InlineData(1, 10)]
[InlineData(2, 10)]
[InlineData(10, 10)]
[InlineData(100, 10)]
public void ToArray_AddAndTakeItemsIntermixedWithEnumeration_ItemsAndCountMatch(int initialCount, int iters)
{
IEnumerable<int> initialItems = Enumerable.Range(1, initialCount);
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems);
IProducerConsumerCollection<int> oracle = CreateOracle(initialItems);
for (int i = 0; i < iters; i++)
{
Assert.Equal<int>(oracle, c);
Assert.Equal(oracle.TryAdd(initialCount + i), c.TryAdd(initialCount + i));
Assert.Equal<int>(oracle, c);
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
Assert.Equal<int>(oracle, c);
}
}
[Fact]
public void AddFromMultipleThreads_ItemsRemainAfterThreadsGoAway()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
for (int i = 0; i < 1000; i += 100)
{
// Create a thread that adds items to the collection
ThreadFactory.StartNew(() =>
{
for (int j = i; j < i + 100; j++)
{
Assert.True(c.TryAdd(j));
}
}).GetAwaiter().GetResult();
// Allow threads to be collected
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
AssertSetsEqual(new HashSet<int>(Enumerable.Range(0, 1000)), new HashSet<int>(c));
}
[Fact]
public void AddManyItems_ThenTakeOnSameThread_ItemsOutputInExpectedOrder()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(0, 100000));
IProducerConsumerCollection<int> oracle = CreateOracle(Enumerable.Range(0, 100000));
for (int i = 99999; i >= 0; --i)
{
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
}
}
[Fact]
public void TryPeek_SucceedsOnEmptyCollectionThatWasOnceNonEmpty()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
int item;
for (int i = 0; i < 2; i++)
{
Assert.False(TryPeek(c, out item));
Assert.Equal(0, item);
}
Assert.True(c.TryAdd(42));
for (int i = 0; i < 2; i++)
{
Assert.True(TryPeek(c, out item));
Assert.Equal(42, item);
}
Assert.True(c.TryTake(out item));
Assert.Equal(42, item);
Assert.False(TryPeek(c, out item));
Assert.Equal(0, item);
Assert.False(c.TryTake(out item));
Assert.Equal(0, item);
}
[Fact]
public void AddTakeWithAtLeastOneElementInCollection_IsEmpty_AlwaysFalse()
{
int items = 1000;
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.True(c.TryAdd(0)); // make sure it's never empty
var cts = new CancellationTokenSource();
// Consumer repeatedly calls IsEmpty until it's told to stop
Task consumer = Task.Run(() =>
{
while (!cts.IsCancellationRequested) Assert.False(IsEmpty(c));
});
// Producer adds/takes a bunch of items, then tells the consumer to stop
Task producer = Task.Run(() =>
{
int ignored;
for (int i = 1; i <= items; i++)
{
Assert.True(c.TryAdd(i));
Assert.True(c.TryTake(out ignored));
}
cts.Cancel();
});
Task.WaitAll(producer, consumer);
}
[Fact]
public void CopyTo_Empty_NothingCopied()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
c.CopyTo(new int[0], 0);
c.CopyTo(new int[10], 10);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
public void CopyTo_SzArray_ZeroIndex_ExpectedElementsCopied(int size)
{
IEnumerable<int> initialItems = Enumerable.Range(1, size);
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems);
int[] actual = new int[size];
c.CopyTo(actual, 0);
IProducerConsumerCollection<int> oracle = CreateOracle(initialItems);
int[] expected = new int[size];
oracle.CopyTo(expected, 0);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
public void CopyTo_SzArray_NonZeroIndex_ExpectedElementsCopied(int size)
{
IEnumerable<int> initialItems = Enumerable.Range(1, size);
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems);
int[] actual = new int[size + 2];
c.CopyTo(actual, 1);
IProducerConsumerCollection<int> oracle = CreateOracle(initialItems);
int[] expected = new int[size + 2];
oracle.CopyTo(expected, 1);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
public void CopyTo_ArrayZeroLowerBound_ZeroIndex_ExpectedElementsCopied(int size)
{
IEnumerable<int> initialItems = Enumerable.Range(1, size);
ICollection c = CreateProducerConsumerCollection(initialItems);
Array actual = Array.CreateInstance(typeof(int), new int[] { size }, new int[] { 0 });
c.CopyTo(actual, 0);
ICollection oracle = CreateOracle(initialItems);
Array expected = Array.CreateInstance(typeof(int), new int[] { size }, new int[] { 0 });
oracle.CopyTo(expected, 0);
Assert.Equal(expected.Cast<int>(), actual.Cast<int>());
}
[Fact]
public void CopyTo_ArrayNonZeroLowerBound_ExpectedElementsCopied()
{
if (!PlatformDetection.IsNonZeroLowerBoundArraySupported)
return;
int[] initialItems = Enumerable.Range(1, 10).ToArray();
const int LowerBound = 1;
ICollection c = CreateProducerConsumerCollection(initialItems);
Array actual = Array.CreateInstance(typeof(int), new int[] { initialItems.Length }, new int[] { LowerBound });
c.CopyTo(actual, LowerBound);
ICollection oracle = CreateOracle(initialItems);
int[] expected = new int[initialItems.Length];
oracle.CopyTo(expected, 0);
for (int i = 0; i < expected.Length; i++)
{
Assert.Equal(expected[i], actual.GetValue(i + LowerBound));
}
}
[Fact]
public void CopyTo_InvalidArgs_Throws()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(0, 10));
int[] dest = new int[10];
AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(dest, -1));
AssertExtensions.Throws<ArgumentException>(CopyToNoLengthParamName, "", () => c.CopyTo(dest, dest.Length));
AssertExtensions.Throws<ArgumentException>(CopyToNoLengthParamName, "", () => c.CopyTo(dest, dest.Length - 2));
AssertExtensions.Throws<ArgumentException>(null, () => c.CopyTo(new int[7, 7], 0));
}
[Fact]
public void ICollectionCopyTo_InvalidArgs_Throws()
{
ICollection c = CreateProducerConsumerCollection(Enumerable.Range(0, 10));
Array dest = new int[10];
AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(dest, -1));
AssertExtensions.Throws<ArgumentException>(CopyToNoLengthParamName, "", () => c.CopyTo(dest, dest.Length));
AssertExtensions.Throws<ArgumentException>(CopyToNoLengthParamName, "", () => c.CopyTo(dest, dest.Length - 2));
}
[Theory]
[InlineData(100, 1, 10)]
[InlineData(4, 100000, 10)]
public void BlockingCollection_WrappingCollection_ExpectedElementsTransferred(int numThreadsPerConsumerProducer, int numItemsPerThread, int producerSpin)
{
var bc = new BlockingCollection<int>(CreateProducerConsumerCollection());
long dummy = 0;
Task[] producers = Enumerable.Range(0, numThreadsPerConsumerProducer).Select(_ => ThreadFactory.StartNew(() =>
{
for (int i = 1; i <= numItemsPerThread; i++)
{
for (int j = 0; j < producerSpin; j++) dummy *= j; // spin a little
bc.Add(i);
}
})).ToArray();
Task[] consumers = Enumerable.Range(0, numThreadsPerConsumerProducer).Select(_ => ThreadFactory.StartNew(() =>
{
for (int i = 0; i < numItemsPerThread; i++)
{
const int TimeoutMs = 100000;
int item;
Assert.True(bc.TryTake(out item, TimeoutMs), $"Couldn't get {i}th item after {TimeoutMs}ms");
Assert.NotEqual(0, item);
}
})).ToArray();
WaitAllOrAnyFailed(producers);
WaitAllOrAnyFailed(consumers);
}
[Fact]
public void GetEnumerator_NonGeneric()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
IEnumerable e = c;
Assert.False(e.GetEnumerator().MoveNext());
Assert.True(c.TryAdd(42));
Assert.True(c.TryAdd(84));
var hs = new HashSet<int>(e.Cast<int>());
Assert.Equal(2, hs.Count);
Assert.Contains(42, hs);
Assert.Contains(84, hs);
}
[Fact]
public void GetEnumerator_EnumerationsAreSnapshots()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.Empty(c);
using (IEnumerator<int> e1 = c.GetEnumerator())
{
Assert.True(c.TryAdd(1));
using (IEnumerator<int> e2 = c.GetEnumerator())
{
Assert.True(c.TryAdd(2));
using (IEnumerator<int> e3 = c.GetEnumerator())
{
int item;
Assert.True(c.TryTake(out item));
using (IEnumerator<int> e4 = c.GetEnumerator())
{
Assert.False(e1.MoveNext());
Assert.True(e2.MoveNext());
Assert.False(e2.MoveNext());
Assert.True(e3.MoveNext());
Assert.True(e3.MoveNext());
Assert.False(e3.MoveNext());
Assert.True(e4.MoveNext());
Assert.False(e4.MoveNext());
}
}
}
}
}
[Theory]
[InlineData(0, true)]
[InlineData(1, true)]
[InlineData(1, false)]
[InlineData(10, true)]
[InlineData(100, true)]
[InlineData(100, false)]
public async Task GetEnumerator_Generic_ExpectedElementsYielded(int numItems, bool consumeFromSameThread)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
using (var e = c.GetEnumerator())
{
Assert.False(e.MoveNext());
}
// Add, and validate enumeration after each item added
for (int i = 1; i <= numItems; i++)
{
Assert.True(c.TryAdd(i));
Assert.Equal(i, c.Count);
Assert.Equal(i, c.Distinct().Count());
}
// Take, and validate enumerate after each item removed.
Action consume = () =>
{
for (int i = 1; i <= numItems; i++)
{
int item;
Assert.True(c.TryTake(out item));
Assert.Equal(numItems - i, c.Count);
Assert.Equal(numItems - i, c.Distinct().Count());
}
};
if (consumeFromSameThread)
{
consume();
}
else
{
await ThreadFactory.StartNew(consume);
}
}
[Fact]
public void TryAdd_TryTake_ToArray()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.True(c.TryAdd(42));
Assert.Equal(new[] { 42 }, c.ToArray());
Assert.True(c.TryAdd(84));
Assert.Equal(new[] { 42, 84 }, c.ToArray().OrderBy(i => i));
int item;
Assert.True(c.TryTake(out item));
int remainingItem = item == 42 ? 84 : 42;
Assert.Equal(new[] { remainingItem }, c.ToArray());
Assert.True(c.TryTake(out item));
Assert.Equal(remainingItem, item);
Assert.Empty(c.ToArray());
}
[Fact]
public void ICollection_IsSynchronized_SyncRoot()
{
ICollection c = CreateProducerConsumerCollection();
Assert.False(c.IsSynchronized);
Assert.Throws<NotSupportedException>(() => c.SyncRoot);
}
[Fact]
public void ToArray_ParallelInvocations_Succeed()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.Empty(c.ToArray());
const int NumItems = 10000;
Parallel.For(0, NumItems, i => Assert.True(c.TryAdd(i)));
Assert.Equal(NumItems, c.Count);
Parallel.For(0, 10, i =>
{
var hs = new HashSet<int>(c.ToArray());
Assert.Equal(NumItems, hs.Count);
});
}
[Fact]
public void ToArray_AddTakeSameThread_ExpectedResultsAfterAddsAndTakes()
{
const int Items = 20;
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
IProducerConsumerCollection<int> oracle = CreateOracle();
for (int i = 0; i < Items; i++)
{
Assert.True(c.TryAdd(i));
Assert.True(oracle.TryAdd(i));
Assert.Equal(oracle.ToArray(), c.ToArray());
}
for (int i = Items - 1; i >= 0; i--)
{
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
Assert.Equal(oracle.ToArray(), c.ToArray());
}
}
[Fact]
public void GetEnumerator_ParallelInvocations_Succeed()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.Empty(c.ToArray());
const int NumItems = 10000;
Parallel.For(0, NumItems, i => Assert.True(c.TryAdd(i)));
Assert.Equal(NumItems, c.Count);
Parallel.For(0, 10, i =>
{
var hs = new HashSet<int>(c);
Assert.Equal(NumItems, hs.Count);
});
}
[Theory]
[InlineData(1, ConcurrencyTestSeconds / 2)]
[InlineData(4, ConcurrencyTestSeconds / 2)]
public void ManyConcurrentAddsTakes_EnsureTrackedCountsMatchResultingCollection(int threadsPerProc, double seconds)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
DateTime end = default(DateTime);
using (var b = new Barrier(Environment.ProcessorCount * threadsPerProc, _ => end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds)))
{
Task<int>[] tasks = Enumerable.Range(0, b.ParticipantCount).Select(_ => ThreadFactory.StartNew(() =>
{
b.SignalAndWait();
int count = 0;
var rand = new Random();
while (DateTime.UtcNow < end)
{
if (rand.NextDouble() < .5)
{
Assert.True(c.TryAdd(rand.Next()));
count++;
}
else
{
int item;
if (c.TryTake(out item)) count--;
}
}
return count;
})).ToArray();
Task.WaitAll(tasks);
Assert.Equal(tasks.Sum(t => t.Result), c.Count);
}
}
[Fact]
[OuterLoop]
public void ManyConcurrentAddsTakes_CollectionRemainsConsistent()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
const int operations = 30000;
Action addAndRemove = () =>
{
for (int i = 1; i < operations; i++)
{
int addCount = new Random(12354).Next(1, 100);
int item;
for (int j = 0; j < addCount; j++)
Assert.True(c.TryAdd(i));
for (int j = 0; j < addCount; j++)
Assert.True(c.TryTake(out item));
}
};
const int numberOfThreads = 3;
var tasks = new Task[numberOfThreads];
for (int i = 0; i < numberOfThreads; i++)
tasks[i] = ThreadFactory.StartNew(addAndRemove);
// Wait for them all to finish
WaitAllOrAnyFailed(tasks);
Assert.Empty(c);
}
[Theory]
[InlineData(ConcurrencyTestSeconds)]
public void ManyConcurrentAddsTakesPeeks_ForceContentionWithOtherThreadsTaking(double seconds)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
const int MaxCount = 4;
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);
Task<long> addsTakes = ThreadFactory.StartNew(() =>
{
long total = 0;
while (DateTime.UtcNow < end)
{
for (int i = 1; i <= MaxCount; i++)
{
Assert.True(c.TryAdd(i));
total++;
}
int item;
if (TryPeek(c, out item))
{
Assert.InRange(item, 1, MaxCount);
}
for (int i = 1; i <= MaxCount; i++)
{
if (c.TryTake(out item))
{
total--;
Assert.InRange(item, 1, MaxCount);
}
}
}
return total;
});
Task<long> takesFromOtherThread = ThreadFactory.StartNew(() =>
{
long total = 0;
int item;
while (DateTime.UtcNow < end)
{
if (c.TryTake(out item))
{
total++;
Assert.InRange(item, 1, MaxCount);
}
}
return total;
});
WaitAllOrAnyFailed(addsTakes, takesFromOtherThread);
long remaining = addsTakes.Result - takesFromOtherThread.Result;
Assert.InRange(remaining, 0, long.MaxValue);
Assert.Equal(remaining, c.Count);
}
[Theory]
[InlineData(ConcurrencyTestSeconds)]
public void ManyConcurrentAddsTakesPeeks_ForceContentionWithOtherThreadsPeeking(double seconds)
{
IProducerConsumerCollection<LargeStruct> c = CreateProducerConsumerCollection<LargeStruct>();
const int MaxCount = 4;
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);
Task<long> addsTakes = ThreadFactory.StartNew(() =>
{
long total = 0;
while (DateTime.UtcNow < end)
{
for (int i = 1; i <= MaxCount; i++)
{
Assert.True(c.TryAdd(new LargeStruct(i)));
total++;
}
LargeStruct item;
Assert.True(TryPeek(c, out item));
Assert.InRange(item.Value, 1, MaxCount);
for (int i = 1; i <= MaxCount; i++)
{
if (c.TryTake(out item))
{
total--;
Assert.InRange(item.Value, 1, MaxCount);
}
}
}
return total;
});
Task peeksFromOtherThread = ThreadFactory.StartNew(() =>
{
LargeStruct item;
while (DateTime.UtcNow < end)
{
if (TryPeek(c, out item))
{
Assert.InRange(item.Value, 1, MaxCount);
}
}
});
WaitAllOrAnyFailed(addsTakes, peeksFromOtherThread);
Assert.Equal(0, addsTakes.Result);
Assert.Equal(0, c.Count);
}
[Theory]
[InlineData(ConcurrencyTestSeconds)]
public void ManyConcurrentAddsTakes_ForceContentionWithToArray(double seconds)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
const int MaxCount = 4;
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);
Task addsTakes = ThreadFactory.StartNew(() =>
{
while (DateTime.UtcNow < end)
{
for (int i = 1; i <= MaxCount; i++)
{
Assert.True(c.TryAdd(i));
}
for (int i = 1; i <= MaxCount; i++)
{
int item;
Assert.True(c.TryTake(out item));
Assert.InRange(item, 1, MaxCount);
}
}
});
while (DateTime.UtcNow < end)
{
int[] arr = c.ToArray();
Assert.InRange(arr.Length, 0, MaxCount);
Assert.DoesNotContain(0, arr); // make sure we didn't get default(T)
}
addsTakes.GetAwaiter().GetResult();
Assert.Equal(0, c.Count);
}
[Theory]
[InlineData(0, ConcurrencyTestSeconds / 2)]
[InlineData(1, ConcurrencyTestSeconds / 2)]
public void ManyConcurrentAddsTakes_ForceContentionWithGetEnumerator(int initialCount, double seconds)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, initialCount));
const int MaxCount = 4;
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);
Task addsTakes = ThreadFactory.StartNew(() =>
{
while (DateTime.UtcNow < end)
{
for (int i = 1; i <= MaxCount; i++)
{
Assert.True(c.TryAdd(i));
}
for (int i = 1; i <= MaxCount; i++)
{
int item;
Assert.True(c.TryTake(out item));
Assert.InRange(item, 1, MaxCount);
}
}
});
while (DateTime.UtcNow < end)
{
int[] arr = c.Select(i => i).ToArray();
Assert.InRange(arr.Length, initialCount, MaxCount + initialCount);
Assert.DoesNotContain(0, arr); // make sure we didn't get default(T)
}
addsTakes.GetAwaiter().GetResult();
Assert.Equal(initialCount, c.Count);
}
[Theory]
[InlineData(0)]
[InlineData(10)]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public void DebuggerAttributes_Success(int count)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(count);
DebuggerAttributes.ValidateDebuggerDisplayReferences(c);
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(c);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public void DebuggerTypeProxy_Ctor_NullArgument_Throws()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Type proxyType = DebuggerAttributes.GetProxyType(c);
var tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, new object[] { null }));
Assert.IsType<ArgumentNullException>(tie.InnerException);
}
protected static void AssertSetsEqual<T>(HashSet<T> expected, HashSet<T> actual)
{
Assert.Equal(expected.Count, actual.Count);
Assert.Subset(expected, actual);
Assert.Subset(actual, expected);
}
protected static void WaitAllOrAnyFailed(params Task[] tasks)
{
if (tasks.Length == 0)
{
return;
}
int remaining = tasks.Length;
var mres = new ManualResetEventSlim();
foreach (Task task in tasks)
{
task.ContinueWith(t =>
{
if (Interlocked.Decrement(ref remaining) == 0 || t.IsFaulted)
{
mres.Set();
}
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
mres.Wait();
// Either all tasks are completed or at least one failed
foreach (Task t in tasks)
{
if (t.IsFaulted)
{
t.GetAwaiter().GetResult(); // propagate for the first one that failed
}
}
}
private struct LargeStruct // used to help validate that values aren't torn while being read
{
private readonly long _a, _b, _c, _d, _e, _f, _g, _h;
public LargeStruct(long value) { _a = _b = _c = _d = _e = _f = _g = _h = value; }
public long Value
{
get
{
if (_a != _b || _a != _c || _a != _d || _a != _e || _a != _f || _a != _g || _a != _h)
{
throw new Exception($"Inconsistent {nameof(LargeStruct)}: {_a} {_b} {_c} {_d} {_e} {_f} {_g} {_h}");
}
return _a;
}
}
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public class PostIncrementAssignTests : IncDecAssignTests
{
[Theory]
[MemberData("Int16sAndIncrements")]
[MemberData("NullableInt16sAndIncrements")]
[MemberData("UInt16sAndIncrements")]
[MemberData("NullableUInt16sAndIncrements")]
[MemberData("Int32sAndIncrements")]
[MemberData("NullableInt32sAndIncrements")]
[MemberData("UInt32sAndIncrements")]
[MemberData("NullableUInt32sAndIncrements")]
[MemberData("Int64sAndIncrements")]
[MemberData("NullableInt64sAndIncrements")]
[MemberData("UInt64sAndIncrements")]
[MemberData("NullableUInt64sAndIncrements")]
[MemberData("DecimalsAndIncrements")]
[MemberData("NullableDecimalsAndIncrements")]
[MemberData("SinglesAndIncrements")]
[MemberData("NullableSinglesAndIncrements")]
[MemberData("DoublesAndIncrements")]
[MemberData("NullableDoublesAndIncrements")]
public void ReturnsCorrectValues(Type type, object value, object _)
{
ParameterExpression variable = Expression.Variable(type);
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(value, type)),
Expression.PostIncrementAssign(variable)
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(value, type), block)).Compile()());
}
[Theory]
[MemberData("Int16sAndIncrements")]
[MemberData("NullableInt16sAndIncrements")]
[MemberData("UInt16sAndIncrements")]
[MemberData("NullableUInt16sAndIncrements")]
[MemberData("Int32sAndIncrements")]
[MemberData("NullableInt32sAndIncrements")]
[MemberData("UInt32sAndIncrements")]
[MemberData("NullableUInt32sAndIncrements")]
[MemberData("Int64sAndIncrements")]
[MemberData("NullableInt64sAndIncrements")]
[MemberData("UInt64sAndIncrements")]
[MemberData("NullableUInt64sAndIncrements")]
[MemberData("DecimalsAndIncrements")]
[MemberData("NullableDecimalsAndIncrements")]
[MemberData("SinglesAndIncrements")]
[MemberData("NullableSinglesAndIncrements")]
[MemberData("DoublesAndIncrements")]
[MemberData("NullableDoublesAndIncrements")]
public void AssignsCorrectValues(Type type, object value, object result)
{
ParameterExpression variable = Expression.Variable(type);
LabelTarget target = Expression.Label(type);
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(value, type)),
Expression.PostIncrementAssign(variable),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(type))
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile()());
}
[Fact]
public void SingleNanToNan()
{
TestPropertyClass<float> instance = new TestPropertyClass<float>();
instance.TestInstance = float.NaN;
Assert.True(float.IsNaN(
Expression.Lambda<Func<float>>(
Expression.PostIncrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<float>),
"TestInstance"
)
)
).Compile()()
));
Assert.True(float.IsNaN(instance.TestInstance));
}
[Fact]
public void DoubleNanToNan()
{
TestPropertyClass<double> instance = new TestPropertyClass<double>();
instance.TestInstance = double.NaN;
Assert.True(double.IsNaN(
Expression.Lambda<Func<double>>(
Expression.PostIncrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<double>),
"TestInstance"
)
)
).Compile()()
));
Assert.True(double.IsNaN(instance.TestInstance));
}
[Theory]
[MemberData("IncrementOverflowingValues")]
public void OverflowingValuesThrow(object value)
{
ParameterExpression variable = Expression.Variable(value.GetType());
Action overflow = Expression.Lambda<Action>(
Expression.Block(
typeof(void),
new[] { variable },
Expression.Assign(variable, Expression.Constant(value)),
Expression.PostIncrementAssign(variable)
)
).Compile();
Assert.Throws<OverflowException>(overflow);
}
[Theory]
[MemberData("UnincrementableAndUndecrementableTypes")]
public void InvalidOperandType(Type type)
{
ParameterExpression variable = Expression.Variable(type);
Assert.Throws<InvalidOperationException>(() => Expression.PostIncrementAssign(variable));
}
[Fact]
public void MethodCorrectResult()
{
ParameterExpression variable = Expression.Variable(typeof(string));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant("hello")),
Expression.PostIncrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod"))
);
Assert.Equal("hello", Expression.Lambda<Func<string>>(block).Compile()());
}
[Fact]
public void MethodCorrectAssign()
{
ParameterExpression variable = Expression.Variable(typeof(string));
LabelTarget target = Expression.Label(typeof(string));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant("hello")),
Expression.PostIncrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod")),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(typeof(string)))
);
Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile()());
}
[Fact]
public void IncorrectMethodType()
{
Expression variable = Expression.Variable(typeof(int));
MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod");
Assert.Throws<InvalidOperationException>(() => Expression.PostIncrementAssign(variable, method));
}
[Fact]
public void IncorrectMethodParameterCount()
{
Expression variable = Expression.Variable(typeof(string));
MethodInfo method = typeof(object).GetTypeInfo().GetDeclaredMethod("ReferenceEquals");
Assert.Throws<ArgumentException>(() => Expression.PostIncrementAssign(variable, method));
}
[Fact]
public void IncorrectMethodReturnType()
{
Expression variable = Expression.Variable(typeof(int));
MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("GetString");
Assert.Throws<ArgumentException>(() => Expression.PostIncrementAssign(variable, method));
}
[Fact]
public void StaticMemberAccessCorrect()
{
TestPropertyClass<long>.TestStatic = 2L;
Assert.Equal(
2L,
Expression.Lambda<Func<long>>(
Expression.PostIncrementAssign(
Expression.Property(null, typeof(TestPropertyClass<long>), "TestStatic")
)
).Compile()()
);
Assert.Equal(3L, TestPropertyClass<long>.TestStatic);
}
[Fact]
public void InstanceMemberAccessCorrect()
{
TestPropertyClass<int> instance = new TestPropertyClass<int>();
instance.TestInstance = 2;
Assert.Equal(
2,
Expression.Lambda<Func<int>>(
Expression.PostIncrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<int>),
"TestInstance"
)
)
).Compile()()
);
Assert.Equal(3, instance.TestInstance);
}
[Fact]
public void ArrayAccessCorrect()
{
int[] array = new int[1];
array[0] = 2;
Assert.Equal(
2,
Expression.Lambda<Func<int>>(
Expression.PostIncrementAssign(
Expression.ArrayAccess(Expression.Constant(array), Expression.Constant(0))
)
).Compile()()
);
Assert.Equal(3, array[0]);
}
[Fact]
public void CanReduce()
{
ParameterExpression variable = Expression.Variable(typeof(int));
UnaryExpression op = Expression.PostIncrementAssign(variable);
Assert.True(op.CanReduce);
Assert.NotSame(op, op.ReduceAndCheck());
}
[Fact]
public void NullOperand()
{
Assert.Throws<ArgumentNullException>("expression", () => Expression.PostIncrementAssign(null));
}
[Fact]
public void UnwritableOperand()
{
Assert.Throws<ArgumentException>("expression", () => Expression.PostIncrementAssign(Expression.Constant(1)));
}
[Fact]
public void UnreadableOperand()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("expression", () => Expression.PostIncrementAssign(value));
}
[Fact]
public void UpdateSameOperandSameNode()
{
UnaryExpression op = Expression.PostIncrementAssign(Expression.Variable(typeof(int)));
Assert.Same(op, op.Update(op.Operand));
}
[Fact]
public void UpdateDiffOperandDiffNode()
{
UnaryExpression op = Expression.PostIncrementAssign(Expression.Variable(typeof(int)));
Assert.NotSame(op, op.Update(Expression.Variable(typeof(int))));
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Text;
using NUnit.Framework.Api;
using NUnit.Framework.Internal;
using NUnit.Framework.Extensibility;
namespace NUnit.Framework.Builders
{
/// <summary>
/// Built-in SuiteBuilder for NUnit TestFixture
/// </summary>
public class NUnitTestFixtureBuilder : ISuiteBuilder
{
#region Static Fields
static readonly string NO_TYPE_ARGS_MSG =
"Fixture type contains generic parameters. You must either provide " +
"Type arguments or specify constructor arguments that allow NUnit " +
"to deduce the Type arguments.";
#endregion
#region Instance Fields
/// <summary>
/// The NUnitTestFixture being constructed;
/// </summary>
private TestFixture fixture;
private Extensibility.ITestCaseBuilder2 testBuilder;
#endregion
#region Constructor
public NUnitTestFixtureBuilder()
{
testBuilder = new NUnitTestCaseBuilder();
}
#endregion
#region ISuiteBuilder Methods
/// <summary>
/// Checks to see if the fixture type has the TestFixtureAttribute
/// </summary>
/// <param name="type">The fixture type to check</param>
/// <returns>True if the fixture can be built, false if not</returns>
public bool CanBuildFrom(Type type)
{
if ( type.IsAbstract && !type.IsSealed )
return false;
if (type.IsDefined(typeof(TestFixtureAttribute), true))
return true;
#if CLR_2_0 || CLR_4_0
// Generics must have a TestFixtureAttribute
if (type.IsGenericTypeDefinition)
return false;
#endif
return Reflect.HasMethodWithAttribute(type, typeof(NUnit.Framework.TestAttribute)) ||
Reflect.HasMethodWithAttribute(type, typeof(NUnit.Framework.TestCaseAttribute)) ||
Reflect.HasMethodWithAttribute(type, typeof(NUnit.Framework.TestCaseSourceAttribute)) ||
Reflect.HasMethodWithAttribute(type, typeof(NUnit.Framework.TheoryAttribute));
}
/// <summary>
/// Build a TestSuite from type provided.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public Test BuildFrom(Type type)
{
TestFixtureAttribute[] attrs = GetTestFixtureAttributes(type);
#if CLR_2_0 || CLR_4_0
if (type.IsGenericType)
return BuildMultipleFixtures(type, attrs);
#endif
switch (attrs.Length)
{
case 0:
return BuildSingleFixture(type, null);
case 1:
object[] args = (object[])attrs[0].Arguments;
return args == null || args.Length == 0
? BuildSingleFixture(type, attrs[0])
: BuildMultipleFixtures(type, attrs);
default:
return BuildMultipleFixtures(type, attrs);
}
}
#endregion
#region Helper Methods
private Test BuildMultipleFixtures(Type type, TestFixtureAttribute[] attrs)
{
TestSuite suite = new ParameterizedFixtureSuite(type);
if (attrs.Length > 0)
{
foreach (TestFixtureAttribute attr in attrs)
suite.Add(BuildSingleFixture(type, attr));
}
else
{
suite.RunState = RunState.NotRunnable;
suite.Properties.Set(PropertyNames.SkipReason, NO_TYPE_ARGS_MSG);
}
return suite;
}
private Test BuildSingleFixture(Type type, TestFixtureAttribute attr)
{
object[] arguments = null;
if (attr != null)
{
arguments = (object[])attr.Arguments;
#if CLR_2_0 || CLR_4_0
if (type.ContainsGenericParameters)
{
Type[] typeArgs = (Type[])attr.TypeArgs;
if( typeArgs.Length > 0 ||
TypeHelper.CanDeduceTypeArgsFromArgs(type, arguments, ref typeArgs))
{
type = TypeHelper.MakeGenericType(type, typeArgs);
}
}
#endif
}
this.fixture = new TestFixture(type, arguments);
CheckTestFixtureIsValid(fixture);
fixture.ApplyAttributesToTest(type);
if (fixture.RunState == RunState.Runnable && attr != null)
{
if (attr.Ignore)
{
fixture.RunState = RunState.Ignored;
fixture.Properties.Set(PropertyNames.SkipReason, attr.IgnoreReason);
}
}
AddTestCases(type);
return this.fixture;
}
/// <summary>
/// Method to add test cases to the newly constructed fixture.
/// </summary>
/// <param name="fixtureType"></param>
private void AddTestCases( Type fixtureType )
{
IList methods = fixtureType.GetMethods(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static );
foreach(MethodInfo method in methods)
{
Test test = BuildTestCase(method, this.fixture);
if(test != null)
{
this.fixture.Add( test );
}
}
}
/// <summary>
/// Method to create a test case from a MethodInfo and add
/// it to the fixture being built. It first checks to see if
/// any global TestCaseBuilder addin wants to build the
/// test case. If not, it uses the internal builder
/// collection maintained by this fixture builder. After
/// building the test case, it applies any decorators
/// that have been installed.
///
/// The default implementation has no test case builders.
/// Derived classes should add builders to the collection
/// in their constructor.
/// </summary>
/// <param name="method">The MethodInfo for which a test is to be created</param>
/// <param name="suite">The test suite being built.</param>
/// <returns>A newly constructed Test</returns>
private Test BuildTestCase( MethodInfo method, TestSuite suite )
{
return testBuilder.CanBuildFrom(method, suite)
? testBuilder.BuildFrom(method, suite)
: null;
}
private void CheckTestFixtureIsValid(TestFixture fixture)
{
Type fixtureType = fixture.FixtureType;
#if CLR_2_0 || CLR_4_0
if (fixtureType.ContainsGenericParameters)
{
SetNotRunnable(fixture, NO_TYPE_ARGS_MSG);
return;
}
#endif
if( !IsStaticClass(fixtureType) && !HasValidConstructor(fixtureType, fixture.arguments) )
{
SetNotRunnable(fixture, "No suitable constructor was found");
return;
}
if (!CheckSetUpTearDownMethods(fixture, fixture.SetUpMethods))
return;
if (!CheckSetUpTearDownMethods(fixture, fixture.TearDownMethods))
return;
if (!CheckSetUpTearDownMethods(fixture, Reflect.GetMethodsWithAttribute(fixture.FixtureType, typeof(TestFixtureSetUpAttribute), true)))
return;
CheckSetUpTearDownMethods(fixture, Reflect.GetMethodsWithAttribute(fixture.FixtureType, typeof(TestFixtureTearDownAttribute), true));
}
private static bool HasValidConstructor(Type fixtureType, object[] args)
{
Type[] argTypes;
// Note: This could be done more simply using
// Type.EmptyTypes and Type.GetTypeArray() but
// they don't exist in all runtimes we support.
if (args == null)
argTypes = new Type[0];
else
{
argTypes = new Type[args.Length];
int index = 0;
foreach (object arg in args)
argTypes[index++] = arg.GetType();
}
return fixtureType.GetConstructor(argTypes) != null;
}
private void SetNotRunnable(TestFixture fixture, string reason)
{
fixture.RunState = RunState.NotRunnable;
fixture.Properties.Set(PropertyNames.SkipReason, reason);
}
private static bool IsStaticClass(Type type)
{
return type.IsAbstract && type.IsSealed;
}
private bool CheckSetUpTearDownMethods(TestFixture fixture, MethodInfo[] methods)
{
foreach (MethodInfo method in methods)
if (method.IsAbstract ||
!method.IsPublic && !method.IsFamily ||
method.GetParameters().Length > 0 ||
!method.ReturnType.Equals(typeof(void)))
{
SetNotRunnable(fixture, string.Format("Invalid signature for Setup or TearDown method: {0}", method.Name));
return false;
}
return true;
}
/// <summary>
/// Get TestFixtureAttributes following a somewhat obscure
/// set of rules to eliminate spurious duplication of fixtures.
/// 1. If there are any attributes with args, they are the only
/// ones returned and those without args are ignored.
/// 2. No more than one attribute without args is ever returned.
/// </summary>
private TestFixtureAttribute[] GetTestFixtureAttributes(Type type)
{
TestFixtureAttribute[] attrs =
(TestFixtureAttribute[])type.GetCustomAttributes(typeof(TestFixtureAttribute), true);
// Just return - no possibility of duplication
if (attrs.Length <= 1)
return attrs;
int withArgs = 0;
bool[] hasArgs = new bool[attrs.Length];
// Count and record those attrs with arguments
for (int i = 0; i < attrs.Length; i++)
{
TestFixtureAttribute attr = attrs[i];
if (attr.Arguments.Length > 0 || attr.TypeArgs.Length > 0)
{
withArgs++;
hasArgs[i] = true;
}
}
// If all attributes have args, just return them
if (withArgs == attrs.Length)
return attrs;
// If all attributes are without args, just return the first found
if (withArgs == 0)
return new TestFixtureAttribute[] { attrs[0] };
// Some of each type, so extract those with args
int count = 0;
TestFixtureAttribute[] result = new TestFixtureAttribute[withArgs];
for (int i = 0; i < attrs.Length; i++)
if (hasArgs[i])
result[count++] = attrs[i];
return result;
}
#endregion
}
}
| |
using Orleans.Serialization.Buffers;
using Orleans.Serialization.WireProtocol;
using System.Runtime.CompilerServices;
namespace Orleans.Serialization.Utilities
{
/// <summary>
/// Extension method for working with variable-width integers.
/// </summary>
public static class VarIntReaderExtensions
{
/// <summary>
/// Reads a variable-width <see cref="sbyte"/>.
/// </summary>
/// <typeparam name="TInput">The reader input type.</typeparam>
/// <param name="reader">The reader.</param>
/// <returns>A variable-width integer.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static sbyte ReadVarInt8<TInput>(this ref Reader<TInput> reader) => ZigZagDecode((byte)reader.ReadVarUInt32());
/// <summary>
/// Reads a variable-width <see cref="ushort"/>.
/// </summary>
/// <typeparam name="TInput">The reader input type.</typeparam>
/// <param name="reader">The reader.</param>
/// <returns>A variable-width integer.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static short ReadVarInt16<TInput>(this ref Reader<TInput> reader) => ZigZagDecode((ushort)reader.ReadVarUInt32());
/// <summary>
/// Reads a variable-width <see cref="byte"/>.
/// </summary>
/// <typeparam name="TInput">The reader input type.</typeparam>
/// <param name="reader">The reader.</param>
/// <returns>A variable-width integer.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte ReadVarUInt8<TInput>(this ref Reader<TInput> reader) => (byte)reader.ReadVarUInt32();
/// <summary>
/// Reads a variable-width <see cref="ushort"/>.
/// </summary>
/// <typeparam name="TInput">The reader input type.</typeparam>
/// <param name="reader">The reader.</param>
/// <returns>A variable-width integer.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ushort ReadVarUInt16<TInput>(this ref Reader<TInput> reader) => (ushort)reader.ReadVarUInt32();
/// <summary>
/// Reads a variable-width <see cref="int"/>.
/// </summary>
/// <typeparam name="TInput">The reader input type.</typeparam>
/// <param name="reader">The reader.</param>
/// <returns>A variable-width integer.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int ReadVarInt32<TInput>(this ref Reader<TInput> reader) => ZigZagDecode(reader.ReadVarUInt32());
/// <summary>
/// Reads a variable-width <see cref="long"/>.
/// </summary>
/// <typeparam name="TInput">The reader input type.</typeparam>
/// <param name="reader">The reader.</param>
/// <returns>A variable-width integer.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static long ReadVarInt64<TInput>(this ref Reader<TInput> reader) => ZigZagDecode(reader.ReadVarUInt64());
/// <summary>
/// Reads a variable-width <see cref="byte"/>.
/// </summary>
/// <typeparam name="TInput">The reader input type.</typeparam>
/// <param name="reader">The reader.</param>
/// <param name="wireType">The wire type.</param>
/// <returns>A variable-width integer.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte ReadUInt8<TInput>(this ref Reader<TInput> reader, WireType wireType) => wireType switch
{
WireType.VarInt => reader.ReadVarUInt8(),
WireType.Fixed32 => (byte)reader.ReadUInt32(),
WireType.Fixed64 => (byte)reader.ReadUInt64(),
_ => ExceptionHelper.ThrowArgumentOutOfRange<byte>(nameof(wireType)),
};
/// <summary>
/// Reads a variable-width <see cref="ushort"/>.
/// </summary>
/// <typeparam name="TInput">The reader input type.</typeparam>
/// <param name="reader">The reader.</param>
/// <param name="wireType">The wire type.</param>
/// <returns>A variable-width integer.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ushort ReadUInt16<TInput>(this ref Reader<TInput> reader, WireType wireType) => wireType switch
{
WireType.VarInt => reader.ReadVarUInt16(),
WireType.Fixed32 => (ushort)reader.ReadUInt32(),
WireType.Fixed64 => (ushort)reader.ReadUInt64(),
_ => ExceptionHelper.ThrowArgumentOutOfRange<ushort>(nameof(wireType)),
};
/// <summary>
/// Reads a variable-width <see cref="uint"/>.
/// </summary>
/// <typeparam name="TInput">The reader input type.</typeparam>
/// <param name="reader">The reader.</param>
/// <param name="wireType">The wire type.</param>
/// <returns>A variable-width integer.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static uint ReadUInt32<TInput>(this ref Reader<TInput> reader, WireType wireType) => wireType switch
{
WireType.VarInt => reader.ReadVarUInt32(),
WireType.Fixed32 => reader.ReadUInt32(),
WireType.Fixed64 => (uint)reader.ReadUInt64(),
_ => ExceptionHelper.ThrowArgumentOutOfRange<uint>(nameof(wireType)),
};
/// <summary>
/// Reads a variable-width <see cref="ulong"/>.
/// </summary>
/// <typeparam name="TInput">The reader input type.</typeparam>
/// <param name="reader">The reader.</param>
/// <param name="wireType">The wire type.</param>
/// <returns>A variable-width integer.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong ReadUInt64<TInput>(this ref Reader<TInput> reader, WireType wireType) => wireType switch
{
WireType.VarInt => reader.ReadVarUInt64(),
WireType.Fixed32 => reader.ReadUInt32(),
WireType.Fixed64 => reader.ReadUInt64(),
_ => ExceptionHelper.ThrowArgumentOutOfRange<ulong>(nameof(wireType)),
};
/// <summary>
/// Reads a variable-width <see cref="sbyte"/>.
/// </summary>
/// <typeparam name="TInput">The reader input type.</typeparam>
/// <param name="reader">The reader.</param>
/// <param name="wireType">The wire type.</param>
/// <returns>A variable-width integer.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static sbyte ReadInt8<TInput>(this ref Reader<TInput> reader, WireType wireType) => wireType switch
{
WireType.VarInt => reader.ReadVarInt8(),
WireType.Fixed32 => (sbyte)reader.ReadInt32(),
WireType.Fixed64 => (sbyte)reader.ReadInt64(),
_ => ExceptionHelper.ThrowArgumentOutOfRange<sbyte>(nameof(wireType)),
};
/// <summary>
/// Reads a variable-width <see cref="short"/>.
/// </summary>
/// <typeparam name="TInput">The reader input type.</typeparam>
/// <param name="reader">The reader.</param>
/// <param name="wireType">The wire type.</param>
/// <returns>A variable-width integer.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static short ReadInt16<TInput>(this ref Reader<TInput> reader, WireType wireType) => wireType switch
{
WireType.VarInt => reader.ReadVarInt16(),
WireType.Fixed32 => (short)reader.ReadInt32(),
WireType.Fixed64 => (short)reader.ReadInt64(),
_ => ExceptionHelper.ThrowArgumentOutOfRange<short>(nameof(wireType)),
};
/// <summary>
/// Reads a variable-width <see cref="int"/>.
/// </summary>
/// <typeparam name="TInput">The reader input type.</typeparam>
/// <param name="reader">The reader.</param>
/// <param name="wireType">The wire type.</param>
/// <returns>A variable-width integer.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int ReadInt32<TInput>(this ref Reader<TInput> reader, WireType wireType)
{
if (wireType == WireType.VarInt)
{
return reader.ReadVarInt32();
}
return ReadInt32Slower(ref reader, wireType);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static int ReadInt32Slower<TInput>(this ref Reader<TInput> reader, WireType wireType) => wireType switch
{
WireType.Fixed32 => reader.ReadInt32(),
WireType.Fixed64 => (int)reader.ReadInt64(),
_ => ExceptionHelper.ThrowArgumentOutOfRange<int>(nameof(wireType)),
};
/// <summary>
/// Reads a variable-width <see cref="long"/>.
/// </summary>
/// <typeparam name="TInput">The reader input type.</typeparam>
/// <param name="reader">The reader.</param>
/// <param name="wireType">The wire type.</param>
/// <returns>A variable-width integer.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static long ReadInt64<TInput>(this ref Reader<TInput> reader, WireType wireType) => wireType switch
{
WireType.VarInt => reader.ReadVarInt64(),
WireType.Fixed32 => reader.ReadInt32(),
WireType.Fixed64 => reader.ReadInt64(),
_ => ExceptionHelper.ThrowArgumentOutOfRange<long>(nameof(wireType)),
};
private const sbyte Int8Msb = unchecked((sbyte)0x80);
private const short Int16Msb = unchecked((short)0x8000);
private const int Int32Msb = unchecked((int)0x80000000);
private const long Int64Msb = unchecked((long)0x8000000000000000);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static sbyte ZigZagDecode(byte encoded)
{
var value = (sbyte)encoded;
return (sbyte)(-(value & 0x01) ^ ((sbyte)(value >> 1) & ~Int8Msb));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static short ZigZagDecode(ushort encoded)
{
var value = (short)encoded;
return (short)(-(value & 0x01) ^ ((short)(value >> 1) & ~Int16Msb));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int ZigZagDecode(uint encoded)
{
var value = (int)encoded;
return -(value & 0x01) ^ ((value >> 1) & ~Int32Msb);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static long ZigZagDecode(ulong encoded)
{
var value = (long)encoded;
return -(value & 0x01L) ^ ((value >> 1) & ~Int64Msb);
}
}
}
| |
// MIT License
//
// Copyright(c) 2022 ICARUS Consulting GmbH
//
// 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.Globalization;
using System.IO;
using System.Text;
using Yaapii.Atoms.Bytes;
using Yaapii.Atoms.IO;
#pragma warning disable MaxClassLength // Class length max
namespace Yaapii.Atoms.Text
{
/// <summary>
/// A <see cref="IText"/> out of other objects.
/// </summary>
public sealed class LiveText : TextEnvelope
{
/// <summary>
/// A <see cref="IText"/> out of a int.
/// </summary>
/// <param name="input">number</param>
public LiveText(int input) : this(() => input + "")
{ }
/// <summary>
/// A <see cref="IText"/> out of a long.
/// </summary>
/// <param name="input">number</param>
public LiveText(long input) : this(() => input + "")
{ }
/// <summary>
/// A <see cref="IText"/> out of a double
/// </summary>
/// <param name="input">a <see cref="double"/></param>
public LiveText(double input) : this(
() => input.ToString(CultureInfo.InvariantCulture)
)
{ }
/// <summary>
/// A <see cref="IText"/> out of a double
/// </summary>
/// <param name="input">a <see cref="double"/></param>
/// <param name="cultureInfo">The </param>
public LiveText(double input, CultureInfo cultureInfo) : this(
() => input.ToString(cultureInfo)
)
{ }
/// <summary>
/// A <see cref="IText"/> out of a float
/// </summary>
/// <param name="input">a <see cref="float"/></param>
public LiveText(float input) : this(
() => input.ToString(CultureInfo.InvariantCulture)
)
{ }
/// <summary>
/// A <see cref="IText"/> out of a double
/// </summary>
/// <param name="input">a <see cref="float"/></param>
/// <param name="cultureInfo">The </param>
public LiveText(float input, CultureInfo cultureInfo) : this(
() => input.ToString(cultureInfo)
)
{ }
/// <summary>
/// A <see cref="IText"/> out of a <see cref="Uri"/>.
/// </summary>
/// <param name="uri">a file <see cref="Uri"/></param>
public LiveText(Uri uri) : this(new InputOf(uri))
{ }
/// <summary>
/// A <see cref="IText"/> out of a <see cref="Uri"/>.
/// </summary>
/// <param name="uri">a file <see cref="Uri"/></param>
/// <param name="encoding">encoding of the data at the uri</param>
public LiveText(Uri uri, Encoding encoding) : this(new InputOf(uri), encoding)
{ }
/// <summary>
/// A <see cref="IText"/> out of a <see cref="FileInfo"/>
/// </summary>
/// <param name="file"></param>
public LiveText(FileInfo file) : this(new InputOf(file))
{ }
/// <summary>
/// A <see cref="IText"/> out of a <see cref="FileInfo"/>
/// </summary>
/// <param name="file"></param>
/// <param name="encoding"></param>
public LiveText(FileInfo file, Encoding encoding) : this(new InputOf(file), encoding)
{ }
/// <summary>
/// A <see cref="IText"/> out of a <see cref="IInput"/>.
/// </summary>
/// <param name="stream">a <see cref="Stream"/></param>
public LiveText(Stream stream) : this(new InputOf(stream))
{ }
/// <summary>
/// A <see cref="IText"/> out of a <see cref="IInput"/>.
/// </summary>
/// <param name="input">a <see cref="IInput"/></param>
public LiveText(IInput input) : this(new BytesOf(input))
{ }
/// <summary>
/// A <see cref="IText"/> out of a <see cref="IInput"/>.
/// </summary>
/// <param name="input">a input</param>
/// <param name="max">maximum buffer size</param>
public LiveText(IInput input, int max) : this(input, max, Encoding.GetEncoding(0))
{ }
/// <summary>
/// A <see cref="IText"/> out of a <see cref="IInput"/>.
/// </summary>
/// <param name="input">a input</param>
/// <param name="encoding"><see cref="Encoding"/> of the input</param>
public LiveText(IInput input, Encoding encoding) : this(new BytesOf(input), encoding)
{ }
/// <summary>
/// A <see cref="IText"/> out of a <see cref="IInput"/>.
/// </summary>
/// <param name="input">a <see cref="IInput"/></param>
/// <param name="encoding">encoding of the <see cref="IInput"/></param>
/// <param name="max">maximum buffer size</param>
public LiveText(IInput input, int max, Encoding encoding) : this(new BytesOf(input, max), encoding)
{ }
/// <summary>
/// A <see cref="IText"/> out of a <see cref="StreamReader"/>.
/// </summary>
/// <param name="rdr">a <see cref="StreamReader"/></param>
public LiveText(StringReader rdr) : this(new BytesOf(new InputOf(rdr)))
{ }
/// <summary>
/// A <see cref="IText"/> out of a <see cref="StreamReader"/>.
/// </summary>
/// <param name="rdr">a <see cref="StreamReader"/></param>
/// <param name="enc"><see cref="Encoding"/> of the <see cref="StreamReader"/></param>
public LiveText(StringReader rdr, Encoding enc) : this(new BytesOf(rdr), enc)
{ }
/// <summary>
/// A <see cref="IText"/> out of a <see cref="StreamReader"/>.
/// </summary>
/// <param name="rdr">a <see cref="StreamReader"/></param>
public LiveText(StreamReader rdr) : this(new BytesOf(rdr))
{ }
/// <summary>
/// A <see cref="IText"/> out of a <see cref="StreamReader"/>.
/// </summary>
/// <param name="rdr">a <see cref="StreamReader"/></param>
/// <param name="cset"><see cref="Encoding"/> of the <see cref="StreamReader"/></param>
public LiveText(StreamReader rdr, Encoding cset) : this(new BytesOf(rdr, cset))
{ }
/// <summary>
/// A <see cref="IText"/> out of a <see cref="StreamReader"/>.
/// </summary>
/// <param name="rdr">a <see cref="StreamReader"/></param>
/// <param name="cset"><see cref="Encoding"/> of the <see cref="StreamReader"/></param>
/// <param name="max">maximum buffer size</param>
public LiveText(StreamReader rdr, Encoding cset, int max) : this(new BytesOf(rdr, cset, max))
{ }
/// <summary>
/// A <see cref="IText"/> out of a <see cref="StringBuilder"/>.
/// </summary>
/// <param name="builder">a <see cref="StringBuilder"/></param>
public LiveText(StringBuilder builder) : this(new BytesOf(builder))
{ }
/// <summary>
/// A <see cref="IText"/> out of a <see cref="StringBuilder"/>.
/// </summary>
/// <param name="builder">a <see cref="StringBuilder"/></param>
/// <param name="enc"><see cref="Encoding"/> of the <see cref="StreamReader"/></param>
public LiveText(StringBuilder builder, Encoding enc) : this(new BytesOf(builder, enc))
{ }
/// <summary>
/// A <see cref="IText"/> out of a <see cref="char"/> array.
/// </summary>
/// <param name="chars">a char array</param>
public LiveText(params char[] chars) : this(new BytesOf(chars))
{ }
/// <summary>
/// A <see cref="IText"/> out of a <see cref="char"/> array.
/// </summary>
/// <param name="chars">a char array</param>
/// <param name="encoding"><see cref="Encoding"/> of the chars</param>
public LiveText(char[] chars, Encoding encoding) : this(new BytesOf(chars, encoding))
{ }
/// <summary>
/// A <see cref="IText"/> out of a <see cref="Exception"/>.
/// </summary>
/// <param name="error"><see cref="Exception"/> to serialize</param>
public LiveText(Exception error) : this(new BytesOf(error))
{ }
/// <summary>
/// A <see cref="IText"/> out of a <see cref="byte"/> array.
/// </summary>
/// <param name="bytes">a byte array</param>
public LiveText(params byte[] bytes) : this(new BytesOf(bytes))
{ }
/// <summary>
/// A <see cref="IText"/> out of <see cref="IBytes"/> object.
/// </summary>
/// <param name="bytes">A <see cref="IBytes"/> object</param>
public LiveText(IBytes bytes) : this(bytes, Encoding.GetEncoding(0))
{ }
/// <summary>
/// A <see cref="IText"/> out of <see cref="IBytes"/> object.
/// </summary>
/// <param name="bytes">A <see cref="IBytes"/> object</param>
/// <param name="encoding"><see cref="Encoding"/> of the <see cref="IBytes"/> object</param>
public LiveText(IBytes bytes, Encoding encoding) : this(
() =>
{
var memoryStream = new MemoryStream(bytes.AsBytes());
return new StreamReader(memoryStream, encoding).ReadToEnd(); // removes the BOM from the Byte-Array
})
{ }
/// <summary>
/// A <see cref="IText"/> out of <see cref="string"/>.
/// </summary>
/// <param name="input">a string</param>
public LiveText(String input) : this(input, Encoding.GetEncoding(0))
{ }
/// <summary>
/// A <see cref="IText"/> out of <see cref="string"/>.
/// </summary>
/// <param name="input">a string</param>
/// <param name="encoding"><see cref="Encoding"/> of the string</param>
public LiveText(String input, Encoding encoding) : this(
() => encoding.GetString(encoding.GetBytes(input)))
{ }
/// <summary>
/// A <see cref="IText"/> out of the return value of a <see cref="IFunc{T}"/>.
/// </summary>
/// <param name="fnc">func returning a string</param>
public LiveText(IFunc<string> fnc) : this(() => fnc.Invoke())
{ }
/// <summary>
/// A <see cref="IText"/> out of encapsulating <see cref="IScalar{T}"/>.
/// </summary>
/// <param name="scalar">scalar of a string</param>
public LiveText(IScalar<String> scalar) : this(() => scalar.Value())
{ }
/// <summary>
/// A <see cref="IText"/> out of encapsulating <see cref="IScalar{T}"/>.
/// </summary>
/// <param name="txt">func building a of a string</param>
public LiveText(Func<String> txt) : base(txt, true)
{ }
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Diagnostics.Contracts;
using HyperSlackers.Bootstrap.Extensions;
namespace HyperSlackers.Bootstrap
{
public class TypeAhead
{
internal ActionResult result;
internal Task<ActionResult> taskResult;
internal string actionName;
internal string controllerName;
internal string source;
internal int? items;
internal int? minLength;
internal string matcher;
internal string sorter;
internal string updater;
internal string highlighter;
public TypeAhead()
{
}
public TypeAhead Action(string action)
{
Contract.Requires<ArgumentException>(!action.IsNullOrWhiteSpace());
Contract.Ensures(Contract.Result<TypeAhead>() != null);
actionName = action;
return this;
}
public TypeAhead ActionResult(ActionResult result)
{
Contract.Requires<ArgumentNullException>(result != null, "result");
Contract.Ensures(Contract.Result<TypeAhead>() != null);
this.result = result;
return this;
}
public TypeAhead Controller(string controller)
{
Contract.Requires<ArgumentException>(!controller.IsNullOrWhiteSpace());
Contract.Ensures(Contract.Result<TypeAhead>() != null);
controllerName = controller;
return this;
}
public TypeAhead Highlighter(string highlighter)
{
Contract.Requires<ArgumentException>(!highlighter.IsNullOrWhiteSpace());
Contract.Ensures(Contract.Result<TypeAhead>() != null);
this.highlighter = highlighter;
return this;
}
public TypeAhead Items(int items)
{
Contract.Requires<ArgumentOutOfRangeException>(items >= 0);
Contract.Ensures(Contract.Result<TypeAhead>() != null);
this.items = new int?(items);
return this;
}
public TypeAhead Matcher(string matcher)
{
Contract.Requires<ArgumentException>(!matcher.IsNullOrWhiteSpace());
Contract.Ensures(Contract.Result<TypeAhead>() != null);
this.matcher = matcher;
return this;
}
public TypeAhead MinLength(int minLength)
{
Contract.Requires<ArgumentOutOfRangeException>(minLength > 0);
Contract.Ensures(Contract.Result<TypeAhead>() != null);
this.minLength = new int?(minLength);
return this;
}
public TypeAhead Sorter(string sorter)
{
Contract.Requires<ArgumentException>(!sorter.IsNullOrWhiteSpace());
Contract.Ensures(Contract.Result<TypeAhead>() != null);
this.sorter = sorter;
return this;
}
public TypeAhead Source(string source)
{
Contract.Requires<ArgumentException>(!source.IsNullOrWhiteSpace());
Contract.Ensures(Contract.Result<TypeAhead>() != null);
this.source = source;
return this;
}
public TypeAhead TaskResult(Task<ActionResult> taskResult)
{
Contract.Requires<ArgumentNullException>(taskResult != null, "taskResult");
Contract.Ensures(Contract.Result<TypeAhead>() != null);
this.taskResult = taskResult;
return this;
}
public TypeAhead Updater(string updater)
{
Contract.Requires<ArgumentException>(!updater.IsNullOrWhiteSpace());
Contract.Ensures(Contract.Result<TypeAhead>() != null);
this.updater = updater;
return this;
}
internal virtual IDictionary<string, object> ToDictionary(HtmlHelper html)
{
Contract.Requires<ArgumentNullException>(html != null, "html");
Contract.Ensures(Contract.Result<IDictionary<string, object>>() != null);
UrlHelper urlHelper = new UrlHelper(html.ViewContext.RequestContext);
Dictionary<string, object> attributes = new Dictionary<string, object>();
attributes.AddIfNotExist("data-provide", "typeahead");
attributes.AddIfNotExist("autocomplete", "off");
if (result != null)
{
attributes.AddIfNotExist("data-url", urlHelper.Action(result));
}
if (taskResult != null)
{
attributes.AddIfNotExist("data-url", urlHelper.Action(taskResult));
}
if (!actionName.IsNullOrWhiteSpace() || !controllerName.IsNullOrWhiteSpace())
{
attributes.AddIfNotExist("data-url", urlHelper.Action(actionName, controllerName));
}
if (items.HasValue)
{
int value = items.Value;
attributes.AddIfNotExist("data-items", value.ToString());
}
if (minLength.HasValue)
{
int num = minLength.Value;
attributes.AddIfNotExist("data-minLength", num.ToString());
}
if (!source.IsNullOrWhiteSpace())
{
attributes.AddIfNotExist("data-source", source);
}
if (!matcher.IsNullOrWhiteSpace())
{
attributes.AddIfNotExist("data-matcher", matcher);
}
if (!sorter.IsNullOrWhiteSpace())
{
attributes.AddIfNotExist("data-sorter", sorter);
}
if (!updater.IsNullOrWhiteSpace())
{
attributes.AddIfNotExist("data-updater", updater);
}
if (!highlighter.IsNullOrWhiteSpace())
{
attributes.AddIfNotExist("data-highlighter", highlighter);
}
return attributes;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override string ToString()
{
return base.ToString();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
return base.Equals(obj);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
return base.GetHashCode();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public new Type GetType()
{
return base.GetType();
}
}
}
| |
//
// Main.cs
//
using System ;
using System.IO ;
using System.Collections ;
using System.Collections.Generic ;
using System.Text ;
using System.Xml ;
using System.Xml.Xsl ;
using System.Xml.XPath ;
using System.Xml.Schema ;
using System.Diagnostics ;
using System.Reflection ;
using System.Threading ;
using System.Net ;
using SNS=System.Net.Sockets ;
using NUnit.Framework ;
using alby.core.threadpool ;
using alby.core.sockets ;
namespace alby.core.sockets.test
{
[TestFixture]
public class TestFileWarp
{
[Test]
public void IpAddressesOnLocalhost()
{
string dns = "" ;
foreach( IPAddress address in Dns.GetHostAddresses( dns ) )
Console.WriteLine( "[{2}]\t\t\t[{1}]\t\t[{0}]", address.ToString(), address.AddressFamily, dns ) ;
dns = Environment.MachineName ;
foreach( IPAddress address in Dns.GetHostAddresses( dns ) )
Console.WriteLine( "[{2}]\t\t[{1}]\t\t[{0}]", address.ToString(), address.AddressFamily, dns ) ;
dns = "localhost" ;
foreach( IPAddress address in Dns.GetHostAddresses( dns ) )
Console.WriteLine( "[{2}]\t\t[{1}]\t\t[{0}]", address.ToString(), address.AddressFamily, dns ) ;
dns = "::1" ;
foreach( IPAddress address in Dns.GetHostAddresses( dns ) )
Console.WriteLine( "[{2}]\t\t\t[{1}]\t\t[{0}]", address.ToString(), address.AddressFamily, dns ) ;
dns = "127.0.0.1" ;
foreach( IPAddress address in Dns.GetHostAddresses( dns ) )
Console.WriteLine( "[{2}]\t\t[{1}]\t\t[{0}]", address.ToString(), address.AddressFamily, dns ) ;
foreach( IPAddress address1 in Dns.GetHostAddresses( "" ) )
{
dns = address1.ToString() ;
foreach( IPAddress address in Dns.GetHostAddresses( dns ) )
Console.WriteLine( "[{2}]\t\t[{1}]\t\t[{0}]", address.ToString(), address.AddressFamily, dns ) ;
}
}
[Test]
public void IsIp4Up() // see if ip4 is up
{
string str = this.GetLocalIp4Address() ;
Console.WriteLine( "[{0}]", str ) ;
Assert.IsTrue( str.Length > 0 ) ;
}
[Test]
public void IsIp6Up()
{
string str = this.GetLocalIp6Address() ;
Console.WriteLine( "[{0}]", str ) ;
Assert.IsTrue( str.Length > 0 ) ;
}
[Test]
public void RunMyFileWarpExample4_LocalMachineName()
{
RunMyFileWarpExample( 4, Environment.MachineName ) ;
}
[Test]
public void RunMyFileWarpExample6_LocalMachineName()
{
RunMyFileWarpExample( 6, Environment.MachineName ) ;
}
[Test]
public void RunMyFileWarpExample6_Localhost()
{
RunMyFileWarpExample( 6, "localhost" ) ;
}
[Test]
public void RunMyFileWarpExample6_ColonColon1()
{
RunMyFileWarpExample( 6, "::1" ) ;
}
[Test]
public void RunMyFileWarpExample4_127dot0dot0dot1()
{
RunMyFileWarpExample( 4, "127.0.0.1" ) ;
}
[Test]
public void RunMyFileWarpExample4_LocalIp4Address()
{
RunMyFileWarpExample( 4, this.GetLocalIp4Address() ) ;
}
[Test]
public void RunMyFileWarpExample6_LocalIp6Address()
{
RunMyFileWarpExample( 6, this.GetLocalIp6Address() ) ;
}
protected void RunMyFileWarpExample( int ipversion, string theServer )
{
string sourceFile = @"alp-ch04-threads.txt";
string sourceFileFullPath = TestFileWarpThreadPoolItem.ServerFileSite + @"\" + sourceFile;
Assert.IsTrue( File.Exists(sourceFileFullPath ));
FileInfo fiSource = new FileInfo( sourceFileFullPath ) ;
Assert.IsTrue( fiSource.Length > 100000 ) ;
alby.core.crypto.Hashing hashing = new alby.core.crypto.Hashing() ;
byte[] hashSource = hashing.Sha512HashFile( sourceFileFullPath ) ;
string destFile = @"c:\temp\unittestcopy.txt" ;
File.Delete(destFile);
Assert.IsFalse( File.Exists( destFile ) ) ;
Console.WriteLine("@@@ [tid {0}] TestFileWarp - start unit test. ", Thread.CurrentThread.ManagedThreadId);
// server
using ( MyThreadPoolManager tpm = new MyThreadPoolManager( 1, 1 ) )
{
Console.WriteLine("@@@ [tid {0}] TestFileWarp - starting server [{1}]. ", Thread.CurrentThread.ManagedThreadId, theServer );
tpm.Queue(new TestFileWarpThreadPoolItem( ipversion ));
tpm.WaitUntilAllStarted();
// client
Console.WriteLine("@@@ [tid {0}] TestFileWarp - starting client to server [{1}]. ", Thread.CurrentThread.ManagedThreadId, theServer);
FileWarpClient fwc ;
if ( ipversion == 4 )
fwc = new FileWarpClient4( theServer, TestFileWarpThreadPoolItem.Port);
else
fwc = new FileWarpClient6( theServer, TestFileWarpThreadPoolItem.Port);
fwc.DownloadFile(sourceFile, destFile);
Console.WriteLine("@@@ [tid {0}] TestFileWarp - finishing client. ", Thread.CurrentThread.ManagedThreadId);
File.WriteAllText(TestFileWarpThreadPoolItem.StopFile, "you can finish now");
Console.WriteLine("@@@ [tid {0}] TestFileWarp - finishing server. ", Thread.CurrentThread.ManagedThreadId);
}
Assert.IsTrue( File.Exists( destFile ) ) ;
FileInfo fiDest = new FileInfo(destFile);
Assert.AreEqual( fiSource.Length, fiDest.Length ) ;
byte[] hashDest = hashing.Sha512HashFile(destFile);
Assert.AreEqual( Convert.ToBase64String( hashDest ), Convert.ToBase64String( hashSource ) ) ;
Console.WriteLine("@@@ [tid {0}] TestFileWarp - finish unit test. ", Thread.CurrentThread.ManagedThreadId);
}
protected string GetLocalIp4Address()
{
foreach( IPAddress address in Dns.GetHostAddresses( "" ) )
{
if ( address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork )
return address.ToString() ;
}
return "" ;
}
protected string GetLocalIp6Address()
{
foreach( IPAddress address in Dns.GetHostAddresses( "" ) )
{
if ( address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6 )
return address.ToString() ;
}
return "" ;
}
} // end class
public class TestFileWarpThreadPoolItem : MyThreadPoolItemBase
{
public const int Port = 10001;
public const int Timeout = 25;
public const string StopFile = @"c:\temp\stopRunMyFileWarpExample.txt";
public const string ServerFileSite = @"c:\albyStuff\development\alby.core.2015\doc" ;
protected int _ipversion ;
public TestFileWarpThreadPoolItem( int ipversion )
: base()
{
_ipversion = ipversion ;
}
public override void Run()
{
FileWarpServer fws ;
if ( _ipversion == 4 )
fws = new FileWarpServer4(Port, Timeout, StopFile, ServerFileSite);
else
fws = new FileWarpServer6(Port, Timeout, StopFile, ServerFileSite);
fws.Listen();
}
}
}
| |
/*
* 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 System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace OpenSim.Framework.Monitoring
{
/// <summary>
/// Static class used to register/deregister checks on runtime conditions.
/// </summary>
public static class ChecksManager
{
// Subcommand used to list other stats.
public const string ListSubCommand = "list";
/// <summary>
/// Checks categorized by category/container/shortname
/// </summary>
/// <remarks>
/// Do not add or remove directly from this dictionary.
/// </remarks>
public static SortedDictionary<string, SortedDictionary<string, SortedDictionary<string, Check>>> RegisteredChecks
= new SortedDictionary<string, SortedDictionary<string, SortedDictionary<string, Check>>>();
// All subcommands
public static HashSet<string> SubCommands = new HashSet<string> { ListSubCommand };
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static void CheckChecks()
{
lock (RegisteredChecks)
{
foreach (SortedDictionary<string, SortedDictionary<string, Check>> category in RegisteredChecks.Values)
{
foreach (SortedDictionary<string, Check> container in category.Values)
{
foreach (Check check in container.Values)
{
if (!check.CheckIt())
m_log.WarnFormat(
"[CHECKS MANAGER]: Check {0}.{1}.{2} failed with message {3}", check.Category, check.Container, check.ShortName, check.LastFailureMessage);
}
}
}
}
}
/// <summary>
/// Deregister an check
/// </summary>>
/// <param name='stat'></param>
/// <returns></returns>
public static bool DeregisterCheck(Check check)
{
SortedDictionary<string, SortedDictionary<string, Check>> category = null, newCategory;
SortedDictionary<string, Check> container = null, newContainer;
lock (RegisteredChecks)
{
if (!TryGetCheckParents(check, out category, out container))
return false;
newContainer = new SortedDictionary<string, Check>(container);
newContainer.Remove(check.ShortName);
newCategory = new SortedDictionary<string, SortedDictionary<string, Check>>(category);
newCategory.Remove(check.Container);
newCategory[check.Container] = newContainer;
RegisteredChecks[check.Category] = newCategory;
return true;
}
}
public static void HandleShowchecksCommand(string module, string[] cmd)
{
ICommandConsole con = MainConsole.Instance;
if (cmd.Length > 2)
{
foreach (string name in cmd.Skip(2))
{
string[] components = name.Split('.');
string categoryName = components[0];
// string containerName = components.Length > 1 ? components[1] : null;
if (categoryName == ListSubCommand)
{
con.Output("check categories available are:");
foreach (string category in RegisteredChecks.Keys)
con.OutputFormat(" {0}", category);
}
// else
// {
// SortedDictionary<string, SortedDictionary<string, Check>> category;
// if (!Registeredchecks.TryGetValue(categoryName, out category))
// {
// con.OutputFormat("No such category as {0}", categoryName);
// }
// else
// {
// if (String.IsNullOrEmpty(containerName))
// {
// OutputConfiguredToConsole(con, category);
// }
// else
// {
// SortedDictionary<string, Check> container;
// if (category.TryGetValue(containerName, out container))
// {
// OutputContainerChecksToConsole(con, container);
// }
// else
// {
// con.OutputFormat("No such container {0} in category {1}", containerName, categoryName);
// }
// }
// }
// }
}
}
else
{
OutputAllChecksToConsole(con);
}
}
/// <summary>
/// Registers a statistic.
/// </summary>
/// <param name='stat'></param>
/// <returns></returns>
public static bool RegisterCheck(Check check)
{
SortedDictionary<string, SortedDictionary<string, Check>> category = null, newCategory;
SortedDictionary<string, Check> container = null, newContainer;
lock (RegisteredChecks)
{
// Check name is not unique across category/container/shortname key.
// XXX: For now just return false. This is to avoid problems in regression tests where all tests
// in a class are run in the same instance of the VM.
if (TryGetCheckParents(check, out category, out container))
return false;
// We take a copy-on-write approach here of replacing dictionaries when keys are added or removed.
// This means that we don't need to lock or copy them on iteration, which will be a much more
// common operation after startup.
if (container != null)
newContainer = new SortedDictionary<string, Check>(container);
else
newContainer = new SortedDictionary<string, Check>();
if (category != null)
newCategory = new SortedDictionary<string, SortedDictionary<string, Check>>(category);
else
newCategory = new SortedDictionary<string, SortedDictionary<string, Check>>();
newContainer[check.ShortName] = check;
newCategory[check.Container] = newContainer;
RegisteredChecks[check.Category] = newCategory;
}
return true;
}
public static void RegisterConsoleCommands(ICommandConsole console)
{
console.Commands.AddCommand(
"General",
false,
"show checks",
"show checks",
"Show checks configured for this server",
"If no argument is specified then info on all checks will be shown.\n"
+ "'list' argument will show check categories.\n"
+ "THIS FACILITY IS EXPERIMENTAL",
HandleShowchecksCommand);
}
public static bool TryGetCheckParents(
Check check,
out SortedDictionary<string, SortedDictionary<string, Check>> category,
out SortedDictionary<string, Check> container)
{
category = null;
container = null;
lock (RegisteredChecks)
{
if (RegisteredChecks.TryGetValue(check.Category, out category))
{
if (category.TryGetValue(check.Container, out container))
{
if (container.ContainsKey(check.ShortName))
return true;
}
}
}
return false;
}
private static void OutputAllChecksToConsole(ICommandConsole con)
{
foreach (var category in RegisteredChecks.Values)
{
OutputCategoryChecksToConsole(con, category);
}
}
private static void OutputCategoryChecksToConsole(
ICommandConsole con, SortedDictionary<string, SortedDictionary<string, Check>> category)
{
foreach (var container in category.Values)
{
OutputContainerChecksToConsole(con, container);
}
}
private static void OutputContainerChecksToConsole(ICommandConsole con, SortedDictionary<string, Check> container)
{
foreach (Check check in container.Values)
{
con.Output(check.ToConsoleString());
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using Autofac;
using Castle.Windsor;
using EasyNetQ.DI.Autofac;
using EasyNetQ.DI.LightInject;
using EasyNetQ.DI.Microsoft;
using EasyNetQ.DI.Ninject;
using EasyNetQ.DI.SimpleInjector;
using EasyNetQ.DI.StructureMap;
using EasyNetQ.DI.Windsor;
using EasyNetQ.Logging;
using LightInject;
using Ninject;
using Xunit;
using LightInjectContainer = LightInject.ServiceContainer;
using NinjectContainer = Ninject.StandardKernel;
using SimpleInjectorContainer = SimpleInjector.Container;
using StructureMapContainer = StructureMap.Container;
using Microsoft.Extensions.DependencyInjection;
namespace EasyNetQ.DI.Tests;
public class ContainerAdapterTests
{
public delegate IServiceResolver ResolverFactory(Action<IServiceRegister> configure);
[Theory]
[MemberData(nameof(GetContainerAdapters))]
public void Should_last_registration_win(ResolverFactory resolverFactory)
{
var first = new Service();
var last = new Service();
var resolver = resolverFactory(c =>
{
c.Register<IService>(first);
c.Register<IService>(last);
});
Assert.Equal(last, resolver.Resolve<IService>());
}
[Theory]
[MemberData(nameof(GetContainerAdapters))]
public void Should_singleton_created_once(ResolverFactory resolverFactory)
{
var resolver = resolverFactory(c => c.Register<IService, Service>());
var first = resolver.Resolve<IService>();
var second = resolver.Resolve<IService>();
Assert.Same(first, second);
}
[Theory]
[MemberData(nameof(GetContainerAdapters))]
public void Should_transient_created_every_time(ResolverFactory resolverFactory)
{
var resolver = resolverFactory(c => c.Register<IService, Service>(Lifetime.Transient));
var first = resolver.Resolve<IService>();
var second = resolver.Resolve<IService>();
Assert.NotSame(first, second);
}
[Theory]
[MemberData(nameof(GetContainerAdapters))]
public void Should_resolve_service_resolver(ResolverFactory resolverFactory)
{
var resolver = resolverFactory(_ => { });
Assert.NotNull(resolver.Resolve<IServiceResolver>());
}
[Theory]
[MemberData(nameof(GetContainerAdapters))]
public void Should_singleton_factory_called_once(ResolverFactory resolverFactory)
{
var resolver = resolverFactory(c => c.Register<IService>(_ => new Service()));
var first = resolver.Resolve<IService>();
var second = resolver.Resolve<IService>();
Assert.Same(first, second);
}
[Theory]
[MemberData(nameof(GetContainerAdapters))]
public void Should_transient_factory_call_every_time(ResolverFactory resolverFactory)
{
var resolver = resolverFactory(c => c.Register<IService>(_ => new Service(), Lifetime.Transient));
var first = resolver.Resolve<IService>();
var second = resolver.Resolve<IService>();
Assert.NotSame(first, second);
}
[Theory]
[MemberData(nameof(GetContainerAdapters))]
public void Should_override_dependency_with_factory(ResolverFactory resolverFactory)
{
var resolver = resolverFactory(c => c.Register<IService, Service>().Register(_ => (IService)new DummyService()));
Assert.IsType<DummyService>(resolver.Resolve<IService>());
}
[Theory]
[MemberData(nameof(GetContainerAdapters))]
public void Should_resolve_singleton_generic(ResolverFactory resolverFactory)
{
var resolver = resolverFactory(c => c.Register(typeof(ILogger<>), typeof(NoopLogger<>)));
var intLogger = resolver.Resolve<ILogger<int>>();
var floatLogger = resolver.Resolve<ILogger<float>>();
Assert.IsType<NoopLogger<int>>(intLogger);
Assert.IsType<NoopLogger<float>>(floatLogger);
Assert.Same(intLogger, resolver.Resolve<ILogger<int>>());
Assert.Same(floatLogger, resolver.Resolve<ILogger<float>>());
}
[Theory]
[MemberData(nameof(GetContainerAdapters))]
public void Should_resolve_transient_generic(ResolverFactory resolverFactory)
{
var resolver = resolverFactory(
c => c.Register(typeof(ILogger<>), typeof(NoopLogger<>), Lifetime.Transient)
);
var intLogger = resolver.Resolve<ILogger<int>>();
var floatLogger = resolver.Resolve<ILogger<float>>();
Assert.IsType<NoopLogger<int>>(intLogger);
Assert.IsType<NoopLogger<float>>(floatLogger);
Assert.NotSame(intLogger, resolver.Resolve<ILogger<int>>());
Assert.NotSame(floatLogger, resolver.Resolve<ILogger<float>>());
}
public static IEnumerable<object[]> GetContainerAdapters()
{
yield return new object[]
{
(ResolverFactory)(c =>
{
var container = new DefaultServiceContainer();
c(container);
return container.Resolve<IServiceResolver>();
})
};
yield return new object[]
{
(ResolverFactory)(c =>
{
var container = new LightInjectContainer();
c(new LightInjectAdapter(container));
return container.GetInstance<IServiceResolver>();
})
};
yield return new object[]
{
(ResolverFactory)(c =>
{
var container = new SimpleInjectorContainer { Options = { AllowOverridingRegistrations = true } };
c(new SimpleInjectorAdapter(container));
return container.GetInstance<IServiceResolver>();
})
};
yield return new object[]
{
(ResolverFactory)(c =>
{
var container = new StructureMapContainer(r => c(new StructureMapAdapter(r)));
return container.GetInstance<IServiceResolver>();
})
};
yield return new object[]
{
(ResolverFactory)(c =>
{
var containerBuilder = new ContainerBuilder();
c(new AutofacAdapter(containerBuilder));
var container = containerBuilder.Build();
return container.Resolve<IServiceResolver>();
})
};
yield return new object[]
{
(ResolverFactory)(c =>
{
var container = new WindsorContainer();
c(new WindsorAdapter(container));
return container.Resolve<IServiceResolver>();
})
};
yield return new object[]
{
(ResolverFactory)(c =>
{
var container = new NinjectContainer();
c(new NinjectAdapter(container));
return container.Get<IServiceResolver>();
})
};
yield return new object[]
{
(ResolverFactory)(c =>
{
var serviceCollection = new ServiceCollection();
c(new ServiceCollectionAdapter(serviceCollection));
var serviceProvider = serviceCollection.BuildServiceProvider(true); //validate scopes
return serviceProvider.GetService<IServiceResolver>();
})
};
}
public interface IService
{
}
public class DummyService : IService
{
}
public class Service : IService
{
private static volatile int sequenceNumber;
private readonly int number;
public Service()
{
number = Interlocked.Increment(ref sequenceNumber);
}
public override string ToString()
{
return number.ToString();
}
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;
namespace PCSComUtils.MasterSetup.DS
{
public class MST_PauseDS
{
public MST_PauseDS()
{
}
private const string THIS = "PCSComUtils.MasterSetup.DS.MST_PauseDS";
//**************************************************************************
/// <Description>
/// This method uses to add data to MST_Pause
/// </Description>
/// <Inputs>
/// MST_PauseVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, February 15, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
MST_PauseVO objObject = (MST_PauseVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "INSERT INTO MST_Pause("
+ MST_PauseTable.CODE_FLD + ","
+ MST_PauseTable.DESCRIPTION_FLD + ")"
+ "VALUES(?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(MST_PauseTable.CODE_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_PauseTable.CODE_FLD].Value = objObject.Code;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_PauseTable.DESCRIPTION_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_PauseTable.DESCRIPTION_FLD].Value = objObject.Description;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from MST_Pause
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql= "DELETE " + MST_PauseTable.TABLE_NAME + " WHERE " + "PauseID" + "=" + pintID.ToString();
OleDbConnection oconPCS=null;
OleDbCommand ocmdPCS =null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from MST_Pause
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// MST_PauseVO
/// </Outputs>
/// <Returns>
/// MST_PauseVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, February 15, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ MST_PauseTable.PAUSEID_FLD + ","
+ MST_PauseTable.CODE_FLD + ","
+ MST_PauseTable.DESCRIPTION_FLD
+ " FROM " + MST_PauseTable.TABLE_NAME
+" WHERE " + MST_PauseTable.PAUSEID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
MST_PauseVO objObject = new MST_PauseVO();
while (odrPCS.Read())
{
objObject.PauseID = int.Parse(odrPCS[MST_PauseTable.PAUSEID_FLD].ToString().Trim());
objObject.Code = odrPCS[MST_PauseTable.CODE_FLD].ToString().Trim();
objObject.Description = odrPCS[MST_PauseTable.DESCRIPTION_FLD].ToString().Trim();
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to MST_Pause
/// </Description>
/// <Inputs>
/// MST_PauseVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
MST_PauseVO objObject = (MST_PauseVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql= "UPDATE MST_Pause SET "
+ MST_PauseTable.CODE_FLD + "= ?" + ","
+ MST_PauseTable.DESCRIPTION_FLD + "= ?"
+" WHERE " + MST_PauseTable.PAUSEID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(MST_PauseTable.CODE_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_PauseTable.CODE_FLD].Value = objObject.Code;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_PauseTable.DESCRIPTION_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_PauseTable.DESCRIPTION_FLD].Value = objObject.Description;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_PauseTable.PAUSEID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_PauseTable.PAUSEID_FLD].Value = objObject.PauseID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from MST_Pause
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, February 15, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ MST_PauseTable.PAUSEID_FLD + ","
+ MST_PauseTable.CODE_FLD + ","
+ MST_PauseTable.DESCRIPTION_FLD
+ " FROM " + MST_PauseTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,MST_PauseTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, February 15, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql= "SELECT "
+ MST_PauseTable.PAUSEID_FLD + ","
+ MST_PauseTable.CODE_FLD + ","
+ MST_PauseTable.DESCRIPTION_FLD
+ " FROM " + MST_PauseTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData,MST_PauseTable.TABLE_NAME);
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
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 Contoso.API.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Threading.Tasks;
using Android.Content;
using Android.Graphics;
using Android.Views;
using Android.Widget;
using com.refractored.fab;
using FABTest1;
using FABTest1.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Path = System.IO.Path;
[assembly: ExportRenderer(typeof (FloatingActionButtonView), typeof (FloatingActionButtonViewRenderer))]
namespace FABTest1.Droid
{
public class FloatingActionButtonViewRenderer : ViewRenderer<FloatingActionButtonView, FrameLayout>
{
private const int MARGIN_DIPS = 16;
private const int FAB_HEIGHT_NORMAL = 56;
private const int FAB_HEIGHT_MINI = 40;
private const int FAB_FRAME_HEIGHT_WITH_PADDING = MARGIN_DIPS*2 + FAB_HEIGHT_NORMAL;
private const int FAB_FRAME_WIDTH_WITH_PADDING = MARGIN_DIPS*2 + FAB_HEIGHT_NORMAL;
private const int FAB_MINI_FRAME_HEIGHT_WITH_PADDING = MARGIN_DIPS*2 + FAB_HEIGHT_MINI;
private const int FAB_MINI_FRAME_WIDTH_WITH_PADDING = MARGIN_DIPS*2 + FAB_HEIGHT_MINI;
private readonly Context context;
private readonly FloatingActionButton fab;
private int appearingListItemIndex = 0;
public FloatingActionButtonViewRenderer()
{
context = Forms.Context;
var d = context.Resources.DisplayMetrics.Density;
var margin = (int) (MARGIN_DIPS*d); // margin in pixels
fab = new FloatingActionButton(context);
var lp = new FrameLayout.LayoutParams(LayoutParams.WrapContent, LayoutParams.WrapContent);
lp.Gravity = GravityFlags.CenterVertical | GravityFlags.CenterHorizontal;
lp.LeftMargin = margin;
lp.TopMargin = margin;
lp.BottomMargin = margin;
lp.RightMargin = margin;
fab.LayoutParameters = lp;
}
protected override void OnElementChanged(ElementChangedEventArgs<FloatingActionButtonView> e)
{
base.OnElementChanged(e);
if (e.OldElement != null || Element == null)
return;
if (e.OldElement != null)
{
e.OldElement.PropertyChanged -= HandlePropertyChanged;
// Experimental - Hiding and showing the FAB correctly is dependent on the objects in the list being unique
if (e.OldElement.ParentList != null)
{
e.OldElement.ParentList.ItemAppearing -= OnListItemAppearing;
e.OldElement.ParentList.ItemDisappearing -= OnListItemDisappearing;
}
}
if (Element != null)
{
Element.PropertyChanged += HandlePropertyChanged;
// Experimental - Hiding and showing the FAB correctly is dependent on the objects in the list being unique
if (Element.ParentList != null)
{
Element.ParentList.ItemAppearing += OnListItemAppearing;
Element.ParentList.ItemDisappearing += OnListItemDisappearing;
}
}
Element.Show = Show;
Element.Hide = Hide;
SetFabImage(Element.ImageName);
SetFabSize(Element.Size);
fab.ColorNormal = Element.ColorNormal.ToAndroid();
fab.ColorPressed = Element.ColorPressed.ToAndroid();
fab.ColorRipple = Element.ColorRipple.ToAndroid();
fab.HasShadow = Element.HasShadow;
fab.Click += Fab_Click;
var frame = new FrameLayout(context);
frame.RemoveAllViews();
frame.AddView(fab);
SetNativeControl(frame);
}
private async void OnListItemDisappearing(object sender, ItemVisibilityEventArgs e)
{
// Experimental - Hiding and showing the FAB correctly is dependent on the objects in the list being unique
var list = sender as Xamarin.Forms.ListView;
if (list == null) return;
await Task.Run(() =>
{
var items = list.ItemsSource as IList;
if (items != null)
{
var index = items.IndexOf(e.Item);
if (index < appearingListItemIndex && index >= 0)
{
appearingListItemIndex = index;
Device.BeginInvokeOnMainThread(async () =>
{
fab.Hide();
//await Task.Delay(2000);
//fab.Show();
});
}
else
{
appearingListItemIndex = index;
}
}
});
}
private async void OnListItemAppearing(object sender, ItemVisibilityEventArgs e)
{
// Experimental - Hiding and showing the FAB correctly is dependent on the objects in the list being unique
var list = sender as Xamarin.Forms.ListView;
if (list == null) return;
await Task.Run(() =>
{
var items = list.ItemsSource as IList;
if (items != null)
{
var index = items.IndexOf(e.Item);
if (index < appearingListItemIndex)
{
appearingListItemIndex = index;
Device.BeginInvokeOnMainThread(() => fab.Show());
}
else
{
appearingListItemIndex = index;
}
}
});
}
public void Show(bool animate = true)
{
fab.Show(animate);
}
public void Hide(bool animate = true)
{
fab.Hide(animate);
}
private void HandlePropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Content")
{
Tracker.UpdateLayout();
}
else if (e.PropertyName == FloatingActionButtonView.ColorNormalProperty.PropertyName)
{
fab.ColorNormal = Element.ColorNormal.ToAndroid();
}
else if (e.PropertyName == FloatingActionButtonView.ColorPressedProperty.PropertyName)
{
fab.ColorPressed = Element.ColorPressed.ToAndroid();
}
else if (e.PropertyName == FloatingActionButtonView.ColorRippleProperty.PropertyName)
{
fab.ColorRipple = Element.ColorRipple.ToAndroid();
}
else if (e.PropertyName == FloatingActionButtonView.ImageNameProperty.PropertyName)
{
SetFabImage(Element.ImageName);
}
else if (e.PropertyName == FloatingActionButtonView.SizeProperty.PropertyName)
{
SetFabSize(Element.Size);
}
else if (e.PropertyName == FloatingActionButtonView.HasShadowProperty.PropertyName)
{
fab.HasShadow = Element.HasShadow;
}
}
private void SetFabImage(string imageName)
{
if (!string.IsNullOrWhiteSpace(imageName))
{
try
{
var drawableNameWithoutExtension = Path.GetFileNameWithoutExtension(imageName);
var resources = context.Resources;
var imageResourceName = resources.GetIdentifier(drawableNameWithoutExtension, "drawable",
context.PackageName);
fab.SetImageBitmap(BitmapFactory.DecodeResource(context.Resources, imageResourceName));
}
catch (Exception ex)
{
throw new FileNotFoundException("There was no Android Drawable by that name.", ex);
}
}
}
private void SetFabSize(FloatingActionButtonSize size)
{
if (size == FloatingActionButtonSize.Mini)
{
fab.Size = FabSize.Mini;
Element.WidthRequest = FAB_MINI_FRAME_WIDTH_WITH_PADDING;
Element.HeightRequest = FAB_MINI_FRAME_HEIGHT_WITH_PADDING;
}
else
{
fab.Size = FabSize.Normal;
Element.WidthRequest = FAB_FRAME_WIDTH_WITH_PADDING;
Element.HeightRequest = FAB_FRAME_HEIGHT_WITH_PADDING;
}
}
private void Fab_Click(object sender, EventArgs e)
{
var clicked = Element.Clicked;
if (Element != null)
{
clicked?.Invoke(sender, e);
if (Element.Command != null && Element.Command.CanExecute(null)) Element.Command.Execute(null);
}
}
}
}
| |
// -----
// Copyright 2010 Deyan Timnev
// This file is part of the Matrix Platform (www.matrixplatform.com).
// The Matrix Platform is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version. The Matrix Platform is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public License along with the Matrix Platform. If not, see http://www.gnu.org/licenses/lgpl.html
// -----
using System;
using System.Reflection;
using System.Windows.Forms;
using Matrix.Common.Core;
using Matrix.Common.Extended.FastSerialization;
using Matrix.Framework.SuperPool.Core;
using System.Runtime.Serialization;
using Matrix.Common.Core.Serialization;
namespace Matrix.Framework.SuperPool.Call
{
/// <summary>
/// Defines the parameters of a call to a super pool item.
/// </summary>
[Serializable]
public class SuperPoolCall : ISerializable, ICloneable
{
public enum StateEnum : int
{
Requesting,
Responding,
EventRaise,
Finished,
}
/// <summary>
/// This is the request call id, both when this is a call or a response.
/// </summary>
public long Id { get; protected set; }
public StateEnum State = StateEnum.Requesting;
public bool RequestResponse = false;
public object[] Parameters = null;
/// <summary>
/// Used only for serializatio, sometimes we may not be able to
/// construct a full MethodInfo on a remote location, so to
/// still preserve the data, we store it here.
/// </summary>
string _methodInfoName = null;
MethodInfo _methodInfoLocal = null;
public MethodInfo MethodInfoLocal
{
get { return _methodInfoLocal; }
set { _methodInfoLocal = value; }
}
/// <summary>
/// Helper delegate type, used when performing invokes on Control instances.
/// </summary>
public delegate object ControlInvokeDelegate(MethodInfo methodInfo, Control control, object[] parameters);
/// <summary>
/// In case an exception has occured in a proxy call and this is the response,
/// the exception is provided here.
/// </summary>
public Exception Exception
{
get
{
object[] parameters = Parameters;
if (State == StateEnum.Responding && parameters.Length > 1)
{
return parameters[1] as Exception;
}
return null;
}
}
/// <summary>
/// Constructor.
/// </summary>
public SuperPoolCall(long id)
{
Id = id;
}
#region ISerializable Members
/// <summary>
/// Implementing the ISerializable to provide a faster, more optimized
/// serialization for the class.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public SuperPoolCall(SerializationInfo info, StreamingContext context)
{
// Get from the info.
SerializationReader reader = new SerializationReader((byte[])info.GetValue("data", typeof(byte[])));
Id = reader.ReadInt64();
State = (StateEnum)reader.ReadInt32();
RequestResponse = reader.ReadBoolean();
Parameters = reader.ReadObjectArray();
string methodInfoName = reader.ReadString();
_methodInfoName = methodInfoName;
MethodInfoLocal = SerializationHelper.DeserializeMethodBaseFromString(_methodInfoName, true);
}
/// <summary>
/// Implementing the ISerializable to provide a faster, more optimized
/// serialization for the class.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
SerializationWriter writer = new SerializationWriter();
writer.Write(Id);
writer.Write((int)State);
writer.Write(RequestResponse);
writer.Write(Parameters);
// It is possible to not be able to construct method info here;
// in this case we shall only contain the name, since we may
// need it later on.
if (MethodInfoLocal != null)
{
writer.Write(SerializationHelper.SerializeMethodBaseToString(MethodInfoLocal, true));
}
else if (string.IsNullOrEmpty(_methodInfoName) == false)
{
writer.Write(_methodInfoName);
}
else
{
writer.Write(string.Empty);
}
// Put to the info.
info.AddValue("data", writer.ToArray());
}
#endregion
/// <summary>
/// *SLOW* Perform the actual call here to the target control object.
/// Control calls are more complex, since they get executed on the control's
/// Invoke() thread, and to do this, we need the actual delegate instance.
/// </summary>
protected object CallControlInvoke(Control target, out Exception exception)
{
if (Matrix.Framework.SuperPool.Core.SuperPool.CallContextEnabled)
{
SuperPoolCallContext.CurrentCall = this;
}
object result = null;
exception = null;
try
{
ControlInvokeDelegate delegateInstance =
delegate(MethodInfo methodInfo, Control controlTarget, object[] parameters)
{
return FastInvokeHelper.CachedInvoke(methodInfo, controlTarget, parameters);
};
// Synchronously perform the invocation.
result = target.Invoke(delegateInstance, new object[] { MethodInfoLocal, target, Parameters });
}
catch (Exception ex)
{
exception = ex;
}
if (Matrix.Framework.SuperPool.Core.SuperPool.CallContextEnabled)
{
SuperPoolCallContext.CurrentCall = null;
}
return result;
}
/// <summary>
/// Perform the actual call here to the target object.
/// </summary>
public object Call(object target, bool autoControlInvoke, out Exception exception)
{
if (autoControlInvoke && target is Control)
{
return CallControlInvoke((Control)target, out exception);
}
if (Matrix.Framework.SuperPool.Core.SuperPool.CallContextEnabled)
{
SuperPoolCallContext.CurrentCall = this;
}
exception = null;
object result = null;
try
{
// This call is very fast since it uses the static cache in the helper.
result = FastInvokeHelper.CachedInvoke(MethodInfoLocal, target, Parameters);
// This conventional invoke gives around 1 Million executions per second load by itself.
// TODO: optimization can be done using the DelegateTypeCache from CallControlInvoke(),
// since it uses the actual strongly typed delegates already.
//result = MethodInfo.Invoke(target, Parameters);
}
catch (Exception ex)
{
exception = ex;
}
if (Matrix.Framework.SuperPool.Core.SuperPool.CallContextEnabled)
{
SuperPoolCallContext.CurrentCall = null;
}
return result;
}
public SuperPoolCall Duplicate()
{
return new SuperPoolCall(this.Id) { State = this.State, MethodInfoLocal = this.MethodInfoLocal,
RequestResponse = this.RequestResponse, Parameters = this.Parameters };
}
#region ICloneable Members
public object Clone()
{
return this.Duplicate();
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Test.Utilities.Parallel;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
[ParallelFixture]
public class VirtualKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAtRoot_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterClass_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterGlobalStatement_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterGlobalVariableDeclaration_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInUsingAlias()
{
VerifyAbsence(
@"using Foo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInEmptyStatement()
{
VerifyAbsence(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInCompilationUnit()
{
VerifyAbsence(@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterExtern()
{
VerifyAbsence(@"extern alias Foo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterUsing()
{
VerifyAbsence(@"using Foo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNamespace()
{
VerifyAbsence(@"namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterTypeDeclaration()
{
VerifyAbsence(@"class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterDelegateDeclaration()
{
VerifyAbsence(@"delegate void Foo();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethodInClass()
{
VerifyKeyword(
@"class C {
void Foo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterFieldInClass()
{
VerifyKeyword(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPropertyInClass()
{
VerifyKeyword(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotBeforeUsing()
{
VerifyAbsence(
@"$$
using Foo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterAssemblyAttribute()
{
VerifyAbsence(@"[assembly: foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterRootAttribute()
{
VerifyAbsence(@"[foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedAttribute()
{
VerifyKeyword(
@"class C {
[foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInsideStruct()
{
VerifyAbsence(@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInsideInterface()
{
VerifyAbsence(@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideClass()
{
VerifyKeyword(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterPartial()
{
VerifyAbsence(@"partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterAbstract()
{
VerifyAbsence(@"abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterInternal()
{
VerifyAbsence(@"internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterPublic()
{
VerifyAbsence(@"public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterStaticInternal()
{
VerifyAbsence(@"static internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterInternalStatic()
{
VerifyAbsence(@"internal static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterInvalidInternal()
{
VerifyAbsence(@"virtual internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterClass()
{
VerifyAbsence(@"class $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterPrivate()
{
VerifyAbsence(@"private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterSealed()
{
VerifyAbsence(@"sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterStatic()
{
VerifyAbsence(@"static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNestedStatic()
{
VerifyAbsence(@"class C {
static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedInternal()
{
VerifyKeyword(
@"class C {
internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNestedPrivate()
{
VerifyAbsence(@"class C {
private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterDelegate()
{
VerifyAbsence(@"delegate $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNestedAbstract()
{
VerifyAbsence(@"class C {
abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNestedVirtual()
{
VerifyAbsence(@"class C {
virtual $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNestedOverride()
{
VerifyAbsence(@"class C {
override $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNestedSealed()
{
VerifyAbsence(@"class C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInProperty()
{
VerifyAbsence(
@"class C {
int Foo { $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPropertyAfterAccessor()
{
VerifyAbsence(
@"class C {
int Foo { get; $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPropertyAfterAccessibility()
{
VerifyAbsence(
@"class C {
int Foo { get; protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPropertyAfterInternal()
{
VerifyAbsence(
@"class C {
int Foo { get; internal $$");
}
}
}
| |
// 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 PermuteSingle1()
{
var test = new ImmUnaryOpTest__PermuteSingle1();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmUnaryOpTest__PermuteSingle1
{
private struct TestStruct
{
public Vector256<Single> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__PermuteSingle1 testClass)
{
var result = Avx.Permute(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static Single[] _data = new Single[Op1ElementCount];
private static Vector256<Single> _clsVar;
private Vector256<Single> _fld;
private SimpleUnaryOpTest__DataTable<Single, Single> _dataTable;
static ImmUnaryOpTest__PermuteSingle1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
}
public ImmUnaryOpTest__PermuteSingle1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Single, Single>(_data, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.Permute(
Unsafe.Read<Vector256<Single>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.Permute(
Avx.LoadVector256((Single*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.Permute(
Avx.LoadAlignedVector256((Single*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.Permute), new Type[] { typeof(Vector256<Single>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Single>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.Permute), new Type[] { typeof(Vector256<Single>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Single*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.Permute), new Type[] { typeof(Vector256<Single>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Single*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.Permute(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector256<Single>>(_dataTable.inArrayPtr);
var result = Avx.Permute(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Avx.LoadVector256((Single*)(_dataTable.inArrayPtr));
var result = Avx.Permute(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Avx.LoadAlignedVector256((Single*)(_dataTable.inArrayPtr));
var result = Avx.Permute(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__PermuteSingle1();
var result = Avx.Permute(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.Permute(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.Permute(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Single> firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(firstOp[1]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[4]) != BitConverter.SingleToInt32Bits(firstOp[5]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.Permute)}<Single>(Vector256<Single><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Management.ServiceBus;
using Microsoft.WindowsAzure.Management.ServiceBus.Models;
namespace Microsoft.WindowsAzure
{
/// <summary>
/// The Service Bus Management API is a REST API for managing Service Bus
/// queues, topics, rules and subscriptions. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/hh780776.aspx for
/// more information)
/// </summary>
public static partial class NotificationHubOperationsExtensions
{
/// <summary>
/// Deletes a notification hub associated with a namespace.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INotificationHubOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='notificationHubName'>
/// Required. The notification hub name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static OperationResponse Delete(this INotificationHubOperations operations, string namespaceName, string notificationHubName)
{
return Task.Factory.StartNew((object s) =>
{
return ((INotificationHubOperations)s).DeleteAsync(namespaceName, notificationHubName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a notification hub associated with a namespace.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INotificationHubOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='notificationHubName'>
/// Required. The notification hub name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<OperationResponse> DeleteAsync(this INotificationHubOperations operations, string namespaceName, string notificationHubName)
{
return operations.DeleteAsync(namespaceName, notificationHubName, CancellationToken.None);
}
/// <summary>
/// Lists the notification hubs associated with a namespace.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INotificationHubOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='notificationHubName'>
/// Required. The notification hub name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static ServiceBusNotificationHubResponse Get(this INotificationHubOperations operations, string namespaceName, string notificationHubName)
{
return Task.Factory.StartNew((object s) =>
{
return ((INotificationHubOperations)s).GetAsync(namespaceName, notificationHubName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the notification hubs associated with a namespace.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INotificationHubOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='notificationHubName'>
/// Required. The notification hub name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<ServiceBusNotificationHubResponse> GetAsync(this INotificationHubOperations operations, string namespaceName, string notificationHubName)
{
return operations.GetAsync(namespaceName, notificationHubName, CancellationToken.None);
}
/// <summary>
/// Lists the notification hubs associated with a namespace.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INotificationHubOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='notificationHubName'>
/// Required. The notification hub name.
/// </param>
/// <returns>
/// The set of connection details for a service bus entity.
/// </returns>
public static ServiceBusConnectionDetailsResponse GetConnectionDetails(this INotificationHubOperations operations, string namespaceName, string notificationHubName)
{
return Task.Factory.StartNew((object s) =>
{
return ((INotificationHubOperations)s).GetConnectionDetailsAsync(namespaceName, notificationHubName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the notification hubs associated with a namespace.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INotificationHubOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='notificationHubName'>
/// Required. The notification hub name.
/// </param>
/// <returns>
/// The set of connection details for a service bus entity.
/// </returns>
public static Task<ServiceBusConnectionDetailsResponse> GetConnectionDetailsAsync(this INotificationHubOperations operations, string namespaceName, string notificationHubName)
{
return operations.GetConnectionDetailsAsync(namespaceName, notificationHubName, CancellationToken.None);
}
/// <summary>
/// Lists the notification hubs associated with a namespace.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INotificationHubOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static ServiceBusNotificationHubsResponse List(this INotificationHubOperations operations, string namespaceName)
{
return Task.Factory.StartNew((object s) =>
{
return ((INotificationHubOperations)s).ListAsync(namespaceName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the notification hubs associated with a namespace.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.INotificationHubOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<ServiceBusNotificationHubsResponse> ListAsync(this INotificationHubOperations operations, string namespaceName)
{
return operations.ListAsync(namespaceName, CancellationToken.None);
}
}
}
| |
using System;
using Csla;
using SelfLoad.DataAccess;
using SelfLoad.DataAccess.ERCLevel;
namespace SelfLoad.Business.ERCLevel
{
/// <summary>
/// D05_SubContinent_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="D05_SubContinent_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="D04_SubContinent"/> collection.
/// </remarks>
[Serializable]
public partial class D05_SubContinent_ReChild : BusinessBase<D05_SubContinent_ReChild>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="SubContinent_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> SubContinent_Child_NameProperty = RegisterProperty<string>(p => p.SubContinent_Child_Name, "Countries Child Name");
/// <summary>
/// Gets or sets the Countries Child Name.
/// </summary>
/// <value>The Countries Child Name.</value>
public string SubContinent_Child_Name
{
get { return GetProperty(SubContinent_Child_NameProperty); }
set { SetProperty(SubContinent_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="D05_SubContinent_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="D05_SubContinent_ReChild"/> object.</returns>
internal static D05_SubContinent_ReChild NewD05_SubContinent_ReChild()
{
return DataPortal.CreateChild<D05_SubContinent_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="D05_SubContinent_ReChild"/> object, based on given parameters.
/// </summary>
/// <param name="subContinent_ID2">The SubContinent_ID2 parameter of the D05_SubContinent_ReChild to fetch.</param>
/// <returns>A reference to the fetched <see cref="D05_SubContinent_ReChild"/> object.</returns>
internal static D05_SubContinent_ReChild GetD05_SubContinent_ReChild(int subContinent_ID2)
{
return DataPortal.FetchChild<D05_SubContinent_ReChild>(subContinent_ID2);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="D05_SubContinent_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 D05_SubContinent_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="D05_SubContinent_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="D05_SubContinent_ReChild"/> object from the database, based on given criteria.
/// </summary>
/// <param name="subContinent_ID2">The Sub Continent ID2.</param>
protected void Child_Fetch(int subContinent_ID2)
{
var args = new DataPortalHookArgs(subContinent_ID2);
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var dal = dalManager.GetProvider<ID05_SubContinent_ReChildDal>();
var data = dal.Fetch(subContinent_ID2);
Fetch(data);
}
OnFetchPost(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
/// <summary>
/// Loads a <see cref="D05_SubContinent_ReChild"/> object from the given <see cref="D05_SubContinent_ReChildDto"/>.
/// </summary>
/// <param name="data">The D05_SubContinent_ReChildDto to use.</param>
private void Fetch(D05_SubContinent_ReChildDto data)
{
// Value properties
LoadProperty(SubContinent_Child_NameProperty, data.SubContinent_Child_Name);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="D05_SubContinent_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(D04_SubContinent parent)
{
var dto = new D05_SubContinent_ReChildDto();
dto.Parent_SubContinent_ID = parent.SubContinent_ID;
dto.SubContinent_Child_Name = SubContinent_Child_Name;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<ID05_SubContinent_ReChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="D05_SubContinent_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(D04_SubContinent parent)
{
if (!IsDirty)
return;
var dto = new D05_SubContinent_ReChildDto();
dto.Parent_SubContinent_ID = parent.SubContinent_ID;
dto.SubContinent_Child_Name = SubContinent_Child_Name;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<ID05_SubContinent_ReChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="D05_SubContinent_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(D04_SubContinent parent)
{
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<ID05_SubContinent_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.SubContinent_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Conn.Routing.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Org.Apache.Http.Conn.Routing
{
/// <summary>
/// <para>Helps tracking the steps in establishing a route.</para><para><para></para><para></para><title>Revision:</title><para>620254 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/routing/RouteTracker
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/routing/RouteTracker", AccessFlags = 49)]
public sealed partial class RouteTracker : global::Org.Apache.Http.Conn.Routing.IRouteInfo, global::Java.Lang.ICloneable
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new route tracker. The target and origin need to be specified at creation time.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Lorg/apache/http/HttpHost;Ljava/net/InetAddress;)V", AccessFlags = 1)]
public RouteTracker(global::Org.Apache.Http.HttpHost target, global::Java.Net.InetAddress local) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new tracker for the given route. Only target and origin are taken from the route, everything else remains to be tracked.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Lorg/apache/http/conn/routing/HttpRoute;)V", AccessFlags = 1)]
public RouteTracker(global::Org.Apache.Http.Conn.Routing.HttpRoute route) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tracks connecting to the target.</para><para></para>
/// </summary>
/// <java-name>
/// connectTarget
/// </java-name>
[Dot42.DexImport("connectTarget", "(Z)V", AccessFlags = 17)]
public void ConnectTarget(bool secure) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tracks connecting to the first proxy.</para><para></para>
/// </summary>
/// <java-name>
/// connectProxy
/// </java-name>
[Dot42.DexImport("connectProxy", "(Lorg/apache/http/HttpHost;Z)V", AccessFlags = 17)]
public void ConnectProxy(global::Org.Apache.Http.HttpHost proxy, bool secure) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tracks tunnelling to the target.</para><para></para>
/// </summary>
/// <java-name>
/// tunnelTarget
/// </java-name>
[Dot42.DexImport("tunnelTarget", "(Z)V", AccessFlags = 17)]
public void TunnelTarget(bool secure) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tracks tunnelling to a proxy in a proxy chain. This will extend the tracked proxy chain, but it does not mark the route as tunnelled. Only end-to-end tunnels are considered there.</para><para></para>
/// </summary>
/// <java-name>
/// tunnelProxy
/// </java-name>
[Dot42.DexImport("tunnelProxy", "(Lorg/apache/http/HttpHost;Z)V", AccessFlags = 17)]
public void TunnelProxy(global::Org.Apache.Http.HttpHost proxy, bool secure) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tracks layering a protocol.</para><para></para>
/// </summary>
/// <java-name>
/// layerProtocol
/// </java-name>
[Dot42.DexImport("layerProtocol", "(Z)V", AccessFlags = 17)]
public void LayerProtocol(bool secure) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Obtains the target host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the target host </para>
/// </returns>
/// <java-name>
/// getTargetHost
/// </java-name>
[Dot42.DexImport("getTargetHost", "()Lorg/apache/http/HttpHost;", AccessFlags = 17)]
public global::Org.Apache.Http.HttpHost GetTargetHost() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.HttpHost);
}
/// <summary>
/// <para>Obtains the local address to connect from.</para><para></para>
/// </summary>
/// <returns>
/// <para>the local address, or <code>null</code> </para>
/// </returns>
/// <java-name>
/// getLocalAddress
/// </java-name>
[Dot42.DexImport("getLocalAddress", "()Ljava/net/InetAddress;", AccessFlags = 17)]
public global::Java.Net.InetAddress GetLocalAddress() /* MethodBuilder.Create */
{
return default(global::Java.Net.InetAddress);
}
/// <summary>
/// <para>Obtains the number of hops in this route. A direct route has one hop. A route through a proxy has two hops. A route through a chain of <b>n</b> proxies has <b>n+1</b> hops.</para><para></para>
/// </summary>
/// <returns>
/// <para>the number of hops in this route </para>
/// </returns>
/// <java-name>
/// getHopCount
/// </java-name>
[Dot42.DexImport("getHopCount", "()I", AccessFlags = 17)]
public int GetHopCount() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Obtains the target of a hop in this route. The target of the last hop is the target host, the target of previous hops is the respective proxy in the chain. For a route through exactly one proxy, target of hop 0 is the proxy and target of hop 1 is the target host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the target of the given hop</para>
/// </returns>
/// <java-name>
/// getHopTarget
/// </java-name>
[Dot42.DexImport("getHopTarget", "(I)Lorg/apache/http/HttpHost;", AccessFlags = 17)]
public global::Org.Apache.Http.HttpHost GetHopTarget(int hop) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.HttpHost);
}
/// <summary>
/// <para>Obtains the first proxy host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the first proxy in the proxy chain, or <code>null</code> if this route is direct </para>
/// </returns>
/// <java-name>
/// getProxyHost
/// </java-name>
[Dot42.DexImport("getProxyHost", "()Lorg/apache/http/HttpHost;", AccessFlags = 17)]
public global::Org.Apache.Http.HttpHost GetProxyHost() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.HttpHost);
}
/// <java-name>
/// isConnected
/// </java-name>
[Dot42.DexImport("isConnected", "()Z", AccessFlags = 17)]
public bool IsConnected() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Obtains the tunnel type of this route. If there is a proxy chain, only end-to-end tunnels are considered.</para><para></para>
/// </summary>
/// <returns>
/// <para>the tunnelling type </para>
/// </returns>
/// <java-name>
/// getTunnelType
/// </java-name>
[Dot42.DexImport("getTunnelType", "()Lorg/apache/http/conn/routing/RouteInfo$TunnelType;", AccessFlags = 17)]
public global::Org.Apache.Http.Conn.Routing.IRouteInfo_TunnelType GetTunnelType() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Routing.IRouteInfo_TunnelType);
}
/// <summary>
/// <para>Checks whether this route is tunnelled through a proxy. If there is a proxy chain, only end-to-end tunnels are considered.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if tunnelled end-to-end through at least one proxy, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isTunnelled
/// </java-name>
[Dot42.DexImport("isTunnelled", "()Z", AccessFlags = 17)]
public bool IsTunnelled() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Obtains the layering type of this route. In the presence of proxies, only layering over an end-to-end tunnel is considered.</para><para></para>
/// </summary>
/// <returns>
/// <para>the layering type </para>
/// </returns>
/// <java-name>
/// getLayerType
/// </java-name>
[Dot42.DexImport("getLayerType", "()Lorg/apache/http/conn/routing/RouteInfo$LayerType;", AccessFlags = 17)]
public global::Org.Apache.Http.Conn.Routing.IRouteInfo_LayerType GetLayerType() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Routing.IRouteInfo_LayerType);
}
/// <summary>
/// <para>Checks whether this route includes a layered protocol. In the presence of proxies, only layering over an end-to-end tunnel is considered.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if layered, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isLayered
/// </java-name>
[Dot42.DexImport("isLayered", "()Z", AccessFlags = 17)]
public bool IsLayered() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Checks whether this route is secure.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if secure, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isSecure
/// </java-name>
[Dot42.DexImport("isSecure", "()Z", AccessFlags = 17)]
public bool IsSecure() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Obtains the tracked route. If a route has been tracked, it is connected. If not connected, nothing has been tracked so far.</para><para></para>
/// </summary>
/// <returns>
/// <para>the tracked route, or <code>null</code> if nothing has been tracked so far </para>
/// </returns>
/// <java-name>
/// toRoute
/// </java-name>
[Dot42.DexImport("toRoute", "()Lorg/apache/http/conn/routing/HttpRoute;", AccessFlags = 17)]
public global::Org.Apache.Http.Conn.Routing.HttpRoute ToRoute() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Routing.HttpRoute);
}
/// <summary>
/// <para>Compares this tracked route to another.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the argument is the same tracked route, <code>false</code> </para>
/// </returns>
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 17)]
public override bool Equals(object o) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Generates a hash code for this tracked route. Route trackers are modifiable and should therefore not be used as lookup keys. Use toRoute to obtain an unmodifiable representation of the tracked route.</para><para></para>
/// </summary>
/// <returns>
/// <para>the hash code </para>
/// </returns>
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "()I", AccessFlags = 17)]
public override int GetHashCode() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Obtains a description of the tracked route.</para><para></para>
/// </summary>
/// <returns>
/// <para>a human-readable representation of the tracked route </para>
/// </returns>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 17)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// clone
/// </java-name>
[Dot42.DexImport("clone", "()Ljava/lang/Object;", AccessFlags = 1)]
public object Clone() /* MethodBuilder.Create */
{
return default(object);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal RouteTracker() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Obtains the target host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the target host </para>
/// </returns>
/// <java-name>
/// getTargetHost
/// </java-name>
public global::Org.Apache.Http.HttpHost TargetHost
{
[Dot42.DexImport("getTargetHost", "()Lorg/apache/http/HttpHost;", AccessFlags = 17)]
get{ return GetTargetHost(); }
}
/// <summary>
/// <para>Obtains the local address to connect from.</para><para></para>
/// </summary>
/// <returns>
/// <para>the local address, or <code>null</code> </para>
/// </returns>
/// <java-name>
/// getLocalAddress
/// </java-name>
public global::Java.Net.InetAddress LocalAddress
{
[Dot42.DexImport("getLocalAddress", "()Ljava/net/InetAddress;", AccessFlags = 17)]
get{ return GetLocalAddress(); }
}
/// <summary>
/// <para>Obtains the number of hops in this route. A direct route has one hop. A route through a proxy has two hops. A route through a chain of <b>n</b> proxies has <b>n+1</b> hops.</para><para></para>
/// </summary>
/// <returns>
/// <para>the number of hops in this route </para>
/// </returns>
/// <java-name>
/// getHopCount
/// </java-name>
public int HopCount
{
[Dot42.DexImport("getHopCount", "()I", AccessFlags = 17)]
get{ return GetHopCount(); }
}
/// <summary>
/// <para>Obtains the first proxy host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the first proxy in the proxy chain, or <code>null</code> if this route is direct </para>
/// </returns>
/// <java-name>
/// getProxyHost
/// </java-name>
public global::Org.Apache.Http.HttpHost ProxyHost
{
[Dot42.DexImport("getProxyHost", "()Lorg/apache/http/HttpHost;", AccessFlags = 17)]
get{ return GetProxyHost(); }
}
/// <summary>
/// <para>Obtains the tunnel type of this route. If there is a proxy chain, only end-to-end tunnels are considered.</para><para></para>
/// </summary>
/// <returns>
/// <para>the tunnelling type </para>
/// </returns>
/// <java-name>
/// getTunnelType
/// </java-name>
public global::Org.Apache.Http.Conn.Routing.IRouteInfo_TunnelType TunnelType
{
[Dot42.DexImport("getTunnelType", "()Lorg/apache/http/conn/routing/RouteInfo$TunnelType;", AccessFlags = 17)]
get{ return GetTunnelType(); }
}
/// <summary>
/// <para>Obtains the layering type of this route. In the presence of proxies, only layering over an end-to-end tunnel is considered.</para><para></para>
/// </summary>
/// <returns>
/// <para>the layering type </para>
/// </returns>
/// <java-name>
/// getLayerType
/// </java-name>
public global::Org.Apache.Http.Conn.Routing.IRouteInfo_LayerType LayerType
{
[Dot42.DexImport("getLayerType", "()Lorg/apache/http/conn/routing/RouteInfo$LayerType;", AccessFlags = 17)]
get{ return GetLayerType(); }
}
}
/// <summary>
/// <para>Read-only interface for route information.</para><para><para></para><para></para><title>Revision:</title><para>652200 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/routing/RouteInfo
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/routing/RouteInfo", AccessFlags = 1537)]
public partial interface IRouteInfo
/* scope: __dot42__ */
{
/// <summary>
/// <para>Obtains the target host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the target host </para>
/// </returns>
/// <java-name>
/// getTargetHost
/// </java-name>
[Dot42.DexImport("getTargetHost", "()Lorg/apache/http/HttpHost;", AccessFlags = 1025)]
global::Org.Apache.Http.HttpHost GetTargetHost() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Obtains the local address to connect from.</para><para></para>
/// </summary>
/// <returns>
/// <para>the local address, or <code>null</code> </para>
/// </returns>
/// <java-name>
/// getLocalAddress
/// </java-name>
[Dot42.DexImport("getLocalAddress", "()Ljava/net/InetAddress;", AccessFlags = 1025)]
global::Java.Net.InetAddress GetLocalAddress() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Obtains the number of hops in this route. A direct route has one hop. A route through a proxy has two hops. A route through a chain of <b>n</b> proxies has <b>n+1</b> hops.</para><para></para>
/// </summary>
/// <returns>
/// <para>the number of hops in this route </para>
/// </returns>
/// <java-name>
/// getHopCount
/// </java-name>
[Dot42.DexImport("getHopCount", "()I", AccessFlags = 1025)]
int GetHopCount() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Obtains the target of a hop in this route. The target of the last hop is the target host, the target of previous hops is the respective proxy in the chain. For a route through exactly one proxy, target of hop 0 is the proxy and target of hop 1 is the target host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the target of the given hop</para>
/// </returns>
/// <java-name>
/// getHopTarget
/// </java-name>
[Dot42.DexImport("getHopTarget", "(I)Lorg/apache/http/HttpHost;", AccessFlags = 1025)]
global::Org.Apache.Http.HttpHost GetHopTarget(int hop) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Obtains the first proxy host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the first proxy in the proxy chain, or <code>null</code> if this route is direct </para>
/// </returns>
/// <java-name>
/// getProxyHost
/// </java-name>
[Dot42.DexImport("getProxyHost", "()Lorg/apache/http/HttpHost;", AccessFlags = 1025)]
global::Org.Apache.Http.HttpHost GetProxyHost() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Obtains the tunnel type of this route. If there is a proxy chain, only end-to-end tunnels are considered.</para><para></para>
/// </summary>
/// <returns>
/// <para>the tunnelling type </para>
/// </returns>
/// <java-name>
/// getTunnelType
/// </java-name>
[Dot42.DexImport("getTunnelType", "()Lorg/apache/http/conn/routing/RouteInfo$TunnelType;", AccessFlags = 1025)]
global::Org.Apache.Http.Conn.Routing.IRouteInfo_TunnelType GetTunnelType() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Checks whether this route is tunnelled through a proxy. If there is a proxy chain, only end-to-end tunnels are considered.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if tunnelled end-to-end through at least one proxy, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isTunnelled
/// </java-name>
[Dot42.DexImport("isTunnelled", "()Z", AccessFlags = 1025)]
bool IsTunnelled() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Obtains the layering type of this route. In the presence of proxies, only layering over an end-to-end tunnel is considered.</para><para></para>
/// </summary>
/// <returns>
/// <para>the layering type </para>
/// </returns>
/// <java-name>
/// getLayerType
/// </java-name>
[Dot42.DexImport("getLayerType", "()Lorg/apache/http/conn/routing/RouteInfo$LayerType;", AccessFlags = 1025)]
global::Org.Apache.Http.Conn.Routing.IRouteInfo_LayerType GetLayerType() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Checks whether this route includes a layered protocol. In the presence of proxies, only layering over an end-to-end tunnel is considered.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if layered, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isLayered
/// </java-name>
[Dot42.DexImport("isLayered", "()Z", AccessFlags = 1025)]
bool IsLayered() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Checks whether this route is secure.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if secure, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isSecure
/// </java-name>
[Dot42.DexImport("isSecure", "()Z", AccessFlags = 1025)]
bool IsSecure() /* MethodBuilder.Create */ ;
}
/// <java-name>
/// org/apache/http/conn/routing/RouteInfo$LayerType
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/routing/RouteInfo$LayerType", AccessFlags = 16409, Signature = "Ljava/lang/Enum<Lorg/apache/http/conn/routing/RouteInfo$LayerType;>;")]
public sealed class IRouteInfo_LayerType
/* scope: __dot42__ */
{
/// <java-name>
/// LAYERED
/// </java-name>
[Dot42.DexImport("LAYERED", "Lorg/apache/http/conn/routing/RouteInfo$LayerType;", AccessFlags = 16409)]
public static readonly global::Org.Apache.Http.Conn.Routing.IRouteInfo_LayerType LAYERED;
/// <java-name>
/// PLAIN
/// </java-name>
[Dot42.DexImport("PLAIN", "Lorg/apache/http/conn/routing/RouteInfo$LayerType;", AccessFlags = 16409)]
public static readonly global::Org.Apache.Http.Conn.Routing.IRouteInfo_LayerType PLAIN;
private IRouteInfo_LayerType() /* TypeBuilder.AddPrivateDefaultCtor */
{
}
}
/// <java-name>
/// org/apache/http/conn/routing/RouteInfo$TunnelType
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/routing/RouteInfo$TunnelType", AccessFlags = 16409, Signature = "Ljava/lang/Enum<Lorg/apache/http/conn/routing/RouteInfo$TunnelType;>;")]
public sealed class IRouteInfo_TunnelType
/* scope: __dot42__ */
{
/// <java-name>
/// PLAIN
/// </java-name>
[Dot42.DexImport("PLAIN", "Lorg/apache/http/conn/routing/RouteInfo$TunnelType;", AccessFlags = 16409)]
public static readonly global::Org.Apache.Http.Conn.Routing.IRouteInfo_TunnelType PLAIN;
/// <java-name>
/// TUNNELLED
/// </java-name>
[Dot42.DexImport("TUNNELLED", "Lorg/apache/http/conn/routing/RouteInfo$TunnelType;", AccessFlags = 16409)]
public static readonly global::Org.Apache.Http.Conn.Routing.IRouteInfo_TunnelType TUNNELLED;
private IRouteInfo_TunnelType() /* TypeBuilder.AddPrivateDefaultCtor */
{
}
}
/// <summary>
/// <para>Encapsulates logic to compute a HttpRoute to a target host. Implementations may for example be based on parameters, or on the standard Java system properties. </para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/routing/HttpRoutePlanner
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/routing/HttpRoutePlanner", AccessFlags = 1537)]
public partial interface IHttpRoutePlanner
/* scope: __dot42__ */
{
/// <summary>
/// <para>Determines the route for a request.</para><para></para>
/// </summary>
/// <returns>
/// <para>the route that the request should take</para>
/// </returns>
/// <java-name>
/// determineRoute
/// </java-name>
[Dot42.DexImport("determineRoute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol" +
"/HttpContext;)Lorg/apache/http/conn/routing/HttpRoute;", AccessFlags = 1025)]
global::Org.Apache.Http.Conn.Routing.HttpRoute DetermineRoute(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Provides directions on establishing a route. Implementations of this interface compare a planned route with a tracked route and indicate the next step required.</para><para><para></para><para></para><title>Revision:</title><para>620255 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/routing/HttpRouteDirector
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/routing/HttpRouteDirector", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IHttpRouteDirectorConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>Indicates that the route can not be established at all. </para>
/// </summary>
/// <java-name>
/// UNREACHABLE
/// </java-name>
[Dot42.DexImport("UNREACHABLE", "I", AccessFlags = 25)]
public const int UNREACHABLE = -1;
/// <summary>
/// <para>Indicates that the route is complete. </para>
/// </summary>
/// <java-name>
/// COMPLETE
/// </java-name>
[Dot42.DexImport("COMPLETE", "I", AccessFlags = 25)]
public const int COMPLETE = 0;
/// <summary>
/// <para>Step: open connection to target. </para>
/// </summary>
/// <java-name>
/// CONNECT_TARGET
/// </java-name>
[Dot42.DexImport("CONNECT_TARGET", "I", AccessFlags = 25)]
public const int CONNECT_TARGET = 1;
/// <summary>
/// <para>Step: open connection to proxy. </para>
/// </summary>
/// <java-name>
/// CONNECT_PROXY
/// </java-name>
[Dot42.DexImport("CONNECT_PROXY", "I", AccessFlags = 25)]
public const int CONNECT_PROXY = 2;
/// <summary>
/// <para>Step: tunnel through proxy to target. </para>
/// </summary>
/// <java-name>
/// TUNNEL_TARGET
/// </java-name>
[Dot42.DexImport("TUNNEL_TARGET", "I", AccessFlags = 25)]
public const int TUNNEL_TARGET = 3;
/// <summary>
/// <para>Step: tunnel through proxy to other proxy. </para>
/// </summary>
/// <java-name>
/// TUNNEL_PROXY
/// </java-name>
[Dot42.DexImport("TUNNEL_PROXY", "I", AccessFlags = 25)]
public const int TUNNEL_PROXY = 4;
/// <summary>
/// <para>Step: layer protocol (over tunnel). </para>
/// </summary>
/// <java-name>
/// LAYER_PROTOCOL
/// </java-name>
[Dot42.DexImport("LAYER_PROTOCOL", "I", AccessFlags = 25)]
public const int LAYER_PROTOCOL = 5;
}
/// <summary>
/// <para>Provides directions on establishing a route. Implementations of this interface compare a planned route with a tracked route and indicate the next step required.</para><para><para></para><para></para><title>Revision:</title><para>620255 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/routing/HttpRouteDirector
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/routing/HttpRouteDirector", AccessFlags = 1537)]
public partial interface IHttpRouteDirector
/* scope: __dot42__ */
{
/// <summary>
/// <para>Provides the next step.</para><para></para>
/// </summary>
/// <returns>
/// <para>one of the constants defined in this interface, indicating either the next step to perform, or success, or failure. 0 is for success, a negative value for failure. </para>
/// </returns>
/// <java-name>
/// nextStep
/// </java-name>
[Dot42.DexImport("nextStep", "(Lorg/apache/http/conn/routing/RouteInfo;Lorg/apache/http/conn/routing/RouteInfo;" +
")I", AccessFlags = 1025)]
int NextStep(global::Org.Apache.Http.Conn.Routing.IRouteInfo plan, global::Org.Apache.Http.Conn.Routing.IRouteInfo fact) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The route for a request. Instances of this class are unmodifiable and therefore suitable for use as lookup keys.</para><para><para></para><para></para><title>Revision:</title><para>653041 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/routing/HttpRoute
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/routing/HttpRoute", AccessFlags = 49)]
public sealed partial class HttpRoute : global::Org.Apache.Http.Conn.Routing.IRouteInfo, global::Java.Lang.ICloneable
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Lorg/apache/http/HttpHost;Ljava/net/InetAddress;[Lorg/apache/http/HttpHost;ZLorg" +
"/apache/http/conn/routing/RouteInfo$TunnelType;Lorg/apache/http/conn/routing/Rou" +
"teInfo$LayerType;)V", AccessFlags = 1)]
public HttpRoute(global::Org.Apache.Http.HttpHost httpHost, global::Java.Net.InetAddress inetAddress, global::Org.Apache.Http.HttpHost[] httpHost1, bool boolean, global::Org.Apache.Http.Conn.Routing.IRouteInfo_TunnelType iRouteInfo_TunnelType, global::Org.Apache.Http.Conn.Routing.IRouteInfo_LayerType iRouteInfo_LayerType) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Lorg/apache/http/HttpHost;Ljava/net/InetAddress;Lorg/apache/http/HttpHost;ZLorg/" +
"apache/http/conn/routing/RouteInfo$TunnelType;Lorg/apache/http/conn/routing/Rout" +
"eInfo$LayerType;)V", AccessFlags = 1)]
public HttpRoute(global::Org.Apache.Http.HttpHost httpHost, global::Java.Net.InetAddress inetAddress, global::Org.Apache.Http.HttpHost httpHost1, bool boolean, global::Org.Apache.Http.Conn.Routing.IRouteInfo_TunnelType iRouteInfo_TunnelType, global::Org.Apache.Http.Conn.Routing.IRouteInfo_LayerType iRouteInfo_LayerType) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new direct route. That is a route without a proxy.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Lorg/apache/http/HttpHost;Ljava/net/InetAddress;Z)V", AccessFlags = 1)]
public HttpRoute(global::Org.Apache.Http.HttpHost target, global::Java.Net.InetAddress local, bool secure) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new direct insecure route.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Lorg/apache/http/HttpHost;)V", AccessFlags = 1)]
public HttpRoute(global::Org.Apache.Http.HttpHost target) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new route through a proxy. When using this constructor, the <code>proxy</code> MUST be given. For convenience, it is assumed that a secure connection will be layered over a tunnel through the proxy.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Lorg/apache/http/HttpHost;Ljava/net/InetAddress;Lorg/apache/http/HttpHost;Z)V", AccessFlags = 1)]
public HttpRoute(global::Org.Apache.Http.HttpHost target, global::Java.Net.InetAddress local, global::Org.Apache.Http.HttpHost proxy, bool secure) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Obtains the target host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the target host </para>
/// </returns>
/// <java-name>
/// getTargetHost
/// </java-name>
[Dot42.DexImport("getTargetHost", "()Lorg/apache/http/HttpHost;", AccessFlags = 17)]
public global::Org.Apache.Http.HttpHost GetTargetHost() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.HttpHost);
}
/// <summary>
/// <para>Obtains the local address to connect from.</para><para></para>
/// </summary>
/// <returns>
/// <para>the local address, or <code>null</code> </para>
/// </returns>
/// <java-name>
/// getLocalAddress
/// </java-name>
[Dot42.DexImport("getLocalAddress", "()Ljava/net/InetAddress;", AccessFlags = 17)]
public global::Java.Net.InetAddress GetLocalAddress() /* MethodBuilder.Create */
{
return default(global::Java.Net.InetAddress);
}
/// <summary>
/// <para>Obtains the number of hops in this route. A direct route has one hop. A route through a proxy has two hops. A route through a chain of <b>n</b> proxies has <b>n+1</b> hops.</para><para></para>
/// </summary>
/// <returns>
/// <para>the number of hops in this route </para>
/// </returns>
/// <java-name>
/// getHopCount
/// </java-name>
[Dot42.DexImport("getHopCount", "()I", AccessFlags = 17)]
public int GetHopCount() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Obtains the target of a hop in this route. The target of the last hop is the target host, the target of previous hops is the respective proxy in the chain. For a route through exactly one proxy, target of hop 0 is the proxy and target of hop 1 is the target host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the target of the given hop</para>
/// </returns>
/// <java-name>
/// getHopTarget
/// </java-name>
[Dot42.DexImport("getHopTarget", "(I)Lorg/apache/http/HttpHost;", AccessFlags = 17)]
public global::Org.Apache.Http.HttpHost GetHopTarget(int hop) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.HttpHost);
}
/// <summary>
/// <para>Obtains the first proxy host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the first proxy in the proxy chain, or <code>null</code> if this route is direct </para>
/// </returns>
/// <java-name>
/// getProxyHost
/// </java-name>
[Dot42.DexImport("getProxyHost", "()Lorg/apache/http/HttpHost;", AccessFlags = 17)]
public global::Org.Apache.Http.HttpHost GetProxyHost() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.HttpHost);
}
/// <summary>
/// <para>Obtains the tunnel type of this route. If there is a proxy chain, only end-to-end tunnels are considered.</para><para></para>
/// </summary>
/// <returns>
/// <para>the tunnelling type </para>
/// </returns>
/// <java-name>
/// getTunnelType
/// </java-name>
[Dot42.DexImport("getTunnelType", "()Lorg/apache/http/conn/routing/RouteInfo$TunnelType;", AccessFlags = 17)]
public global::Org.Apache.Http.Conn.Routing.IRouteInfo_TunnelType GetTunnelType() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Routing.IRouteInfo_TunnelType);
}
/// <summary>
/// <para>Checks whether this route is tunnelled through a proxy. If there is a proxy chain, only end-to-end tunnels are considered.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if tunnelled end-to-end through at least one proxy, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isTunnelled
/// </java-name>
[Dot42.DexImport("isTunnelled", "()Z", AccessFlags = 17)]
public bool IsTunnelled() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Obtains the layering type of this route. In the presence of proxies, only layering over an end-to-end tunnel is considered.</para><para></para>
/// </summary>
/// <returns>
/// <para>the layering type </para>
/// </returns>
/// <java-name>
/// getLayerType
/// </java-name>
[Dot42.DexImport("getLayerType", "()Lorg/apache/http/conn/routing/RouteInfo$LayerType;", AccessFlags = 17)]
public global::Org.Apache.Http.Conn.Routing.IRouteInfo_LayerType GetLayerType() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.Routing.IRouteInfo_LayerType);
}
/// <summary>
/// <para>Checks whether this route includes a layered protocol. In the presence of proxies, only layering over an end-to-end tunnel is considered.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if layered, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isLayered
/// </java-name>
[Dot42.DexImport("isLayered", "()Z", AccessFlags = 17)]
public bool IsLayered() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Checks whether this route is secure.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if secure, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isSecure
/// </java-name>
[Dot42.DexImport("isSecure", "()Z", AccessFlags = 17)]
public bool IsSecure() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Compares this route to another.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the argument is the same route, <code>false</code> </para>
/// </returns>
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 17)]
public override bool Equals(object o) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Generates a hash code for this route.</para><para></para>
/// </summary>
/// <returns>
/// <para>the hash code </para>
/// </returns>
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "()I", AccessFlags = 17)]
public override int GetHashCode() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Obtains a description of this route.</para><para></para>
/// </summary>
/// <returns>
/// <para>a human-readable representation of this route </para>
/// </returns>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 17)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// clone
/// </java-name>
[Dot42.DexImport("clone", "()Ljava/lang/Object;", AccessFlags = 1)]
public object Clone() /* MethodBuilder.Create */
{
return default(object);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal HttpRoute() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Obtains the target host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the target host </para>
/// </returns>
/// <java-name>
/// getTargetHost
/// </java-name>
public global::Org.Apache.Http.HttpHost TargetHost
{
[Dot42.DexImport("getTargetHost", "()Lorg/apache/http/HttpHost;", AccessFlags = 17)]
get{ return GetTargetHost(); }
}
/// <summary>
/// <para>Obtains the local address to connect from.</para><para></para>
/// </summary>
/// <returns>
/// <para>the local address, or <code>null</code> </para>
/// </returns>
/// <java-name>
/// getLocalAddress
/// </java-name>
public global::Java.Net.InetAddress LocalAddress
{
[Dot42.DexImport("getLocalAddress", "()Ljava/net/InetAddress;", AccessFlags = 17)]
get{ return GetLocalAddress(); }
}
/// <summary>
/// <para>Obtains the number of hops in this route. A direct route has one hop. A route through a proxy has two hops. A route through a chain of <b>n</b> proxies has <b>n+1</b> hops.</para><para></para>
/// </summary>
/// <returns>
/// <para>the number of hops in this route </para>
/// </returns>
/// <java-name>
/// getHopCount
/// </java-name>
public int HopCount
{
[Dot42.DexImport("getHopCount", "()I", AccessFlags = 17)]
get{ return GetHopCount(); }
}
/// <summary>
/// <para>Obtains the first proxy host.</para><para></para>
/// </summary>
/// <returns>
/// <para>the first proxy in the proxy chain, or <code>null</code> if this route is direct </para>
/// </returns>
/// <java-name>
/// getProxyHost
/// </java-name>
public global::Org.Apache.Http.HttpHost ProxyHost
{
[Dot42.DexImport("getProxyHost", "()Lorg/apache/http/HttpHost;", AccessFlags = 17)]
get{ return GetProxyHost(); }
}
/// <summary>
/// <para>Obtains the tunnel type of this route. If there is a proxy chain, only end-to-end tunnels are considered.</para><para></para>
/// </summary>
/// <returns>
/// <para>the tunnelling type </para>
/// </returns>
/// <java-name>
/// getTunnelType
/// </java-name>
public global::Org.Apache.Http.Conn.Routing.IRouteInfo_TunnelType TunnelType
{
[Dot42.DexImport("getTunnelType", "()Lorg/apache/http/conn/routing/RouteInfo$TunnelType;", AccessFlags = 17)]
get{ return GetTunnelType(); }
}
/// <summary>
/// <para>Obtains the layering type of this route. In the presence of proxies, only layering over an end-to-end tunnel is considered.</para><para></para>
/// </summary>
/// <returns>
/// <para>the layering type </para>
/// </returns>
/// <java-name>
/// getLayerType
/// </java-name>
public global::Org.Apache.Http.Conn.Routing.IRouteInfo_LayerType LayerType
{
[Dot42.DexImport("getLayerType", "()Lorg/apache/http/conn/routing/RouteInfo$LayerType;", AccessFlags = 17)]
get{ return GetLayerType(); }
}
}
/// <summary>
/// <para>Basic implementation of an HttpRouteDirector. This implementation is stateless and therefore thread-safe.</para><para><para></para><para></para><title>Revision:</title><para>620255 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/conn/routing/BasicRouteDirector
/// </java-name>
[Dot42.DexImport("org/apache/http/conn/routing/BasicRouteDirector", AccessFlags = 33)]
public partial class BasicRouteDirector : global::Org.Apache.Http.Conn.Routing.IHttpRouteDirector
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public BasicRouteDirector() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Provides the next step.</para><para></para>
/// </summary>
/// <returns>
/// <para>one of the constants defined in this class, indicating either the next step to perform, or success, or failure. 0 is for success, a negative value for failure. </para>
/// </returns>
/// <java-name>
/// nextStep
/// </java-name>
[Dot42.DexImport("nextStep", "(Lorg/apache/http/conn/routing/RouteInfo;Lorg/apache/http/conn/routing/RouteInfo;" +
")I", AccessFlags = 1)]
public virtual int NextStep(global::Org.Apache.Http.Conn.Routing.IRouteInfo plan, global::Org.Apache.Http.Conn.Routing.IRouteInfo fact) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Determines the first step to establish a route.</para><para></para>
/// </summary>
/// <returns>
/// <para>the first step </para>
/// </returns>
/// <java-name>
/// firstStep
/// </java-name>
[Dot42.DexImport("firstStep", "(Lorg/apache/http/conn/routing/RouteInfo;)I", AccessFlags = 4)]
protected internal virtual int FirstStep(global::Org.Apache.Http.Conn.Routing.IRouteInfo plan) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Determines the next step to establish a direct connection.</para><para></para>
/// </summary>
/// <returns>
/// <para>one of the constants defined in this class, indicating either the next step to perform, or success, or failure </para>
/// </returns>
/// <java-name>
/// directStep
/// </java-name>
[Dot42.DexImport("directStep", "(Lorg/apache/http/conn/routing/RouteInfo;Lorg/apache/http/conn/routing/RouteInfo;" +
")I", AccessFlags = 4)]
protected internal virtual int DirectStep(global::Org.Apache.Http.Conn.Routing.IRouteInfo plan, global::Org.Apache.Http.Conn.Routing.IRouteInfo fact) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Determines the next step to establish a connection via proxy.</para><para></para>
/// </summary>
/// <returns>
/// <para>one of the constants defined in this class, indicating either the next step to perform, or success, or failure </para>
/// </returns>
/// <java-name>
/// proxiedStep
/// </java-name>
[Dot42.DexImport("proxiedStep", "(Lorg/apache/http/conn/routing/RouteInfo;Lorg/apache/http/conn/routing/RouteInfo;" +
")I", AccessFlags = 4)]
protected internal virtual int ProxiedStep(global::Org.Apache.Http.Conn.Routing.IRouteInfo plan, global::Org.Apache.Http.Conn.Routing.IRouteInfo fact) /* MethodBuilder.Create */
{
return default(int);
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.HSSF.Util
{
using System;
using NUnit.Framework;
using NPOI.SS.Util;
using NPOI.SS;
[TestFixture]
public class TestCellReference
{
[Test]
public void TestColNumConversion()
{
Assert.AreEqual(0, CellReference.ConvertColStringToIndex("A"));
Assert.AreEqual(1, CellReference.ConvertColStringToIndex("B"));
Assert.AreEqual(25, CellReference.ConvertColStringToIndex("Z"));
Assert.AreEqual(26, CellReference.ConvertColStringToIndex("AA"));
Assert.AreEqual(27, CellReference.ConvertColStringToIndex("AB"));
Assert.AreEqual(51, CellReference.ConvertColStringToIndex("AZ"));
Assert.AreEqual(701, CellReference.ConvertColStringToIndex("ZZ"));
Assert.AreEqual(702, CellReference.ConvertColStringToIndex("AAA"));
Assert.AreEqual(18277, CellReference.ConvertColStringToIndex("ZZZ"));
Assert.AreEqual("A", CellReference.ConvertNumToColString(0));
Assert.AreEqual("B", CellReference.ConvertNumToColString(1));
Assert.AreEqual("Z", CellReference.ConvertNumToColString(25));
Assert.AreEqual("AA", CellReference.ConvertNumToColString(26));
Assert.AreEqual("ZZ", CellReference.ConvertNumToColString(701));
Assert.AreEqual("AAA", CellReference.ConvertNumToColString(702));
Assert.AreEqual("ZZZ", CellReference.ConvertNumToColString(18277));
// Absolute references are allowed for the string ones
Assert.AreEqual(0, CellReference.ConvertColStringToIndex("$A"));
Assert.AreEqual(25, CellReference.ConvertColStringToIndex("$Z"));
Assert.AreEqual(26, CellReference.ConvertColStringToIndex("$AA"));
// $ sign isn't allowed elsewhere though
try
{
CellReference.ConvertColStringToIndex("A$B$");
Assert.Fail("Column reference is invalid and shouldn't be accepted");
}
catch (ArgumentException) { }
}
[Test]
public void TestAbsRef1()
{
CellReference cf = new CellReference("$B$5");
ConfirmCell(cf, null, 4, 1, true, true, "$B$5");
}
[Test]
public void TestAbsRef2()
{
CellReference cf = new CellReference(4, 1, true, true);
ConfirmCell(cf, null, 4, 1, true, true, "$B$5");
}
[Test]
public void TestAbsRef3()
{
CellReference cf = new CellReference("B$5");
ConfirmCell(cf, null, 4, 1, true, false, "B$5");
}
[Test]
public void TestAbsRef4()
{
CellReference cf = new CellReference(4, 1, true, false);
ConfirmCell(cf, null, 4, 1, true, false, "B$5");
}
[Test]
public void TestAbsRef5()
{
CellReference cf = new CellReference("$B5");
ConfirmCell(cf, null, 4, 1, false, true, "$B5");
}
[Test]
public void TestAbsRef6()
{
CellReference cf = new CellReference(4, 1, false, true);
ConfirmCell(cf, null, 4, 1, false, true, "$B5");
}
[Test]
public void TestAbsRef7()
{
CellReference cf = new CellReference("B5");
ConfirmCell(cf, null, 4, 1, false, false, "B5");
}
[Test]
public void TestAbsRef8()
{
CellReference cf = new CellReference(4, 1, false, false);
ConfirmCell(cf, null, 4, 1, false, false, "B5");
}
[Test]
public void TestSpecialSheetNames()
{
CellReference cf;
cf = new CellReference("'profit + loss'!A1");
ConfirmCell(cf, "profit + loss", 0, 0, false, false, "'profit + loss'!A1");
cf = new CellReference("'O''Brien''s Sales'!A1");
ConfirmCell(cf, "O'Brien's Sales", 0, 0, false, false, "'O''Brien''s Sales'!A1");
cf = new CellReference("'Amazing!'!A1");
ConfirmCell(cf, "Amazing!", 0, 0, false, false, "'Amazing!'!A1");
}
/* package */
internal static void ConfirmCell(CellReference cf, String expSheetName, int expRow,
int expCol, bool expIsRowAbs, bool expIsColAbs, String expText)
{
Assert.AreEqual(expSheetName, cf.SheetName);
Assert.AreEqual(expRow, cf.Row, "row index is wrong");
Assert.AreEqual(expCol, cf.Col, "col index is wrong");
Assert.AreEqual(expIsRowAbs, cf.IsRowAbsolute, "isRowAbsolute is wrong");
Assert.AreEqual(expIsColAbs, cf.IsColAbsolute, "isColAbsolute is wrong");
Assert.AreEqual(expText, cf.FormatAsString(), "text is wrong");
}
[Test]
public void TestClassifyCellReference()
{
ConfirmNameType("a1", NameType.Cell);
ConfirmNameType("pfy1", NameType.NamedRange);
ConfirmNameType("pf1", NameType.NamedRange); // (col) out of cell range
ConfirmNameType("fp1", NameType.Cell);
ConfirmNameType("pf$1", NameType.BadCellOrNamedRange);
ConfirmNameType("_A1", NameType.NamedRange);
ConfirmNameType("A_1", NameType.NamedRange);
ConfirmNameType("A1_", NameType.NamedRange);
ConfirmNameType(".A1", NameType.BadCellOrNamedRange);
ConfirmNameType("A.1", NameType.NamedRange);
ConfirmNameType("A1.", NameType.NamedRange);
}
[Test]
public void TestClassificationOfRowReferences()
{
ConfirmNameType("10", NameType.Row);
ConfirmNameType("$10", NameType.Row);
ConfirmNameType("65536", NameType.Row);
ConfirmNameType("65537", NameType.BadCellOrNamedRange);
ConfirmNameType("$100000", NameType.BadCellOrNamedRange);
ConfirmNameType("$1$1", NameType.BadCellOrNamedRange);
}
private void ConfirmNameType(String ref1, NameType expectedResult)
{
NameType actualResult = CellReference.ClassifyCellReference(ref1, SpreadsheetVersion.EXCEL97);
Assert.AreEqual(expectedResult, actualResult);
}
[Test]
public void TestConvertColStringToIndex()
{
Assert.AreEqual(0, CellReference.ConvertColStringToIndex("A"));
Assert.AreEqual(1, CellReference.ConvertColStringToIndex("B"));
Assert.AreEqual(14, CellReference.ConvertColStringToIndex("O"));
Assert.AreEqual(701, CellReference.ConvertColStringToIndex("ZZ"));
Assert.AreEqual(18252, CellReference.ConvertColStringToIndex("ZZA"));
Assert.AreEqual(0, CellReference.ConvertColStringToIndex("$A"));
Assert.AreEqual(1, CellReference.ConvertColStringToIndex("$B"));
try
{
CellReference.ConvertColStringToIndex("A$");
Assert.Fail("Should throw exception here");
}
catch (ArgumentException e)
{
Assert.IsTrue(e.Message.Contains("A$"));
}
}
[Test]
public void TestConvertNumColColString()
{
Assert.AreEqual("A", CellReference.ConvertNumToColString(0));
Assert.AreEqual("AV", CellReference.ConvertNumToColString(47));
Assert.AreEqual("AW", CellReference.ConvertNumToColString(48));
Assert.AreEqual("BF", CellReference.ConvertNumToColString(57));
Assert.AreEqual("", CellReference.ConvertNumToColString(-1));
Assert.AreEqual("", CellReference.ConvertNumToColString(Int32.MinValue));
Assert.AreEqual("", CellReference.ConvertNumToColString(Int32.MaxValue));
Assert.AreEqual("FXSHRXW", CellReference.ConvertNumToColString(Int32.MaxValue - 1));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using Xunit;
namespace System.Text.RegularExpressions.Tests
{
public class RegexMatchTests : RemoteExecutorTestBase
{
public static IEnumerable<object[]> Match_Basic_TestData()
{
// Testing octal sequence matches: "\\060(\\061)?\\061"
// Octal \061 is ASCII 49 ('1')
yield return new object[] { @"\060(\061)?\061", "011", RegexOptions.None, 0, 3, true, "011" };
// Testing hexadecimal sequence matches: "(\\x30\\x31\\x32)"
// Hex \x31 is ASCII 49 ('1')
yield return new object[] { @"(\x30\x31\x32)", "012", RegexOptions.None, 0, 3, true, "012" };
// Testing control character escapes???: "2", "(\u0032)"
yield return new object[] { "(\u0034)", "4", RegexOptions.None, 0, 1, true, "4", };
// Using *, +, ?, {}: Actual - "a+\\.?b*\\.?c{2}"
yield return new object[] { @"a+\.?b*\.+c{2}", "ab.cc", RegexOptions.None, 0, 5, true, "ab.cc" };
// Using [a-z], \s, \w: Actual - "([a-zA-Z]+)\\s(\\w+)"
yield return new object[] { @"([a-zA-Z]+)\s(\w+)", "David Bau", RegexOptions.None, 0, 9, true, "David Bau" };
// \\S, \\d, \\D, \\W: Actual - "(\\S+):\\W(\\d+)\\s(\\D+)"
yield return new object[] { @"(\S+):\W(\d+)\s(\D+)", "Price: 5 dollars", RegexOptions.None, 0, 16, true, "Price: 5 dollars" };
// \\S, \\d, \\D, \\W: Actual - "[^0-9]+(\\d+)"
yield return new object[] { @"[^0-9]+(\d+)", "Price: 30 dollars", RegexOptions.None, 0, 17, true, "Price: 30" };
// Zero-width negative lookahead assertion: Actual - "abc(?!XXX)\\w+"
yield return new object[] { @"abc(?!XXX)\w+", "abcXXXdef", RegexOptions.None, 0, 9, false, string.Empty };
// Zero-width positive lookbehind assertion: Actual - "(\\w){6}(?<=XXX)def"
yield return new object[] { @"(\w){6}(?<=XXX)def", "abcXXXdef", RegexOptions.None, 0, 9, true, "abcXXXdef" };
// Zero-width negative lookbehind assertion: Actual - "(\\w){6}(?<!XXX)def"
yield return new object[] { @"(\w){6}(?<!XXX)def", "XXXabcdef", RegexOptions.None, 0, 9, true, "XXXabcdef" };
// Nonbacktracking subexpression: Actual - "[^0-9]+(?>[0-9]+)3"
// The last 3 causes the match to fail, since the non backtracking subexpression does not give up the last digit it matched
// for it to be a success. For a correct match, remove the last character, '3' from the pattern
yield return new object[] { "[^0-9]+(?>[0-9]+)3", "abc123", RegexOptions.None, 0, 6, false, string.Empty };
// Using beginning/end of string chars \A, \Z: Actual - "\\Aaaa\\w+zzz\\Z"
yield return new object[] { @"\Aaaa\w+zzz\Z", "aaaasdfajsdlfjzzz", RegexOptions.None, 0, 17, true, "aaaasdfajsdlfjzzz" };
// Using beginning/end of string chars \A, \Z: Actual - "\\Aaaa\\w+zzz\\Z"
yield return new object[] { @"\Aaaa\w+zzz\Z", "aaaasdfajsdlfjzzza", RegexOptions.None, 0, 18, false, string.Empty };
// Using beginning/end of string chars \A, \Z: Actual - "\\Aaaa\\w+zzz\\Z"
yield return new object[] { @"\A(line2\n)line3\Z", "line2\nline3\n", RegexOptions.Multiline, 0, 12, true, "line2\nline3" };
// Using beginning/end of string chars ^: Actual - "^b"
yield return new object[] { "^b", "ab", RegexOptions.None, 0, 2, false, string.Empty };
// Actual - "(?<char>\\w)\\<char>"
yield return new object[] { @"(?<char>\w)\<char>", "aa", RegexOptions.None, 0, 2, true, "aa" };
// Actual - "(?<43>\\w)\\43"
yield return new object[] { @"(?<43>\w)\43", "aa", RegexOptions.None, 0, 2, true, "aa" };
// Actual - "abc(?(1)111|222)"
yield return new object[] { "(abbc)(?(1)111|222)", "abbc222", RegexOptions.None, 0, 7, false, string.Empty };
// "x" option. Removes unescaped whitespace from the pattern: Actual - " ([^/]+) ","x"
yield return new object[] { " ((.)+) ", "abc", RegexOptions.IgnorePatternWhitespace, 0, 3, true, "abc" };
// "x" option. Removes unescaped whitespace from the pattern. : Actual - "\x20([^/]+)\x20","x"
yield return new object[] { "\x20([^/]+)\x20\x20\x20\x20\x20\x20\x20", " abc ", RegexOptions.IgnorePatternWhitespace, 0, 10, true, " abc " };
// Turning on case insensitive option in mid-pattern : Actual - "aaa(?i:match this)bbb"
if ("i".ToUpper() == "I")
{
yield return new object[] { "aaa(?i:match this)bbb", "aaaMaTcH ThIsbbb", RegexOptions.None, 0, 16, true, "aaaMaTcH ThIsbbb" };
}
// Turning off case insensitive option in mid-pattern : Actual - "aaa(?-i:match this)bbb", "i"
yield return new object[] { "aaa(?-i:match this)bbb", "AaAmatch thisBBb", RegexOptions.IgnoreCase, 0, 16, true, "AaAmatch thisBBb" };
// Turning on/off all the options at once : Actual - "aaa(?imnsx-imnsx:match this)bbb", "i"
yield return new object[] { "aaa(?-i:match this)bbb", "AaAmatcH thisBBb", RegexOptions.IgnoreCase, 0, 16, false, string.Empty };
// Actual - "aaa(?#ignore this completely)bbb"
yield return new object[] { "aaa(?#ignore this completely)bbb", "aaabbb", RegexOptions.None, 0, 6, true, "aaabbb" };
// Trying empty string: Actual "[a-z0-9]+", ""
yield return new object[] { "[a-z0-9]+", "", RegexOptions.None, 0, 0, false, string.Empty };
// Numbering pattern slots: "(?<1>\\d{3})(?<2>\\d{3})(?<3>\\d{4})"
yield return new object[] { @"(?<1>\d{3})(?<2>\d{3})(?<3>\d{4})", "8885551111", RegexOptions.None, 0, 10, true, "8885551111" };
yield return new object[] { @"(?<1>\d{3})(?<2>\d{3})(?<3>\d{4})", "Invalid string", RegexOptions.None, 0, 14, false, string.Empty };
// Not naming pattern slots at all: "^(cat|chat)"
yield return new object[] { "^(cat|chat)", "cats are bad", RegexOptions.None, 0, 12, true, "cat" };
yield return new object[] { "abc", "abc", RegexOptions.None, 0, 3, true, "abc" };
yield return new object[] { "abc", "aBc", RegexOptions.None, 0, 3, false, string.Empty };
yield return new object[] { "abc", "aBc", RegexOptions.IgnoreCase, 0, 3, true, "aBc" };
// Using *, +, ?, {}: Actual - "a+\\.?b*\\.?c{2}"
yield return new object[] { @"a+\.?b*\.+c{2}", "ab.cc", RegexOptions.None, 0, 5, true, "ab.cc" };
// RightToLeft
yield return new object[] { @"\s+\d+", "sdf 12sad", RegexOptions.RightToLeft, 0, 9, true, " 12" };
yield return new object[] { @"\s+\d+", " asdf12 ", RegexOptions.RightToLeft, 0, 6, false, string.Empty };
yield return new object[] { "aaa", "aaabbb", RegexOptions.None, 3, 3, false, string.Empty };
yield return new object[] { @"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 3, false, string.Empty };
yield return new object[] { @"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 11, 21, false, string.Empty };
// IgnoreCase
yield return new object[] { "AAA", "aaabbb", RegexOptions.IgnoreCase, 0, 6, true, "aaa" };
yield return new object[] { @"\p{Lu}", "1bc", RegexOptions.IgnoreCase, 0, 3, true, "b" };
yield return new object[] { @"\p{Ll}", "1bc", RegexOptions.IgnoreCase, 0, 3, true, "b" };
yield return new object[] { @"\p{Lt}", "1bc", RegexOptions.IgnoreCase, 0, 3, true, "b" };
yield return new object[] { @"\p{Lo}", "1bc", RegexOptions.IgnoreCase, 0, 3, false, string.Empty };
// "\D+"
yield return new object[] { @"\D+", "12321", RegexOptions.None, 0, 5, false, string.Empty };
// Groups
yield return new object[] { "(?<first_name>\\S+)\\s(?<last_name>\\S+)", "David Bau", RegexOptions.None, 0, 9, true, "David Bau" };
// "^b"
yield return new object[] { "^b", "abc", RegexOptions.None, 0, 3, false, string.Empty };
// RightToLeft
yield return new object[] { @"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 0, 32, true, "foo4567890" };
yield return new object[] { @"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 22, true, "foo4567890" };
yield return new object[] { @"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 4, true, "foo4" };
// Trim leading and trailing whitespace
yield return new object[] { @"\s*(.*?)\s*$", " Hello World ", RegexOptions.None, 0, 13, true, " Hello World " };
// < in group
yield return new object[] { @"(?<cat>cat)\w+(?<dog-0>dog)", "cat_Hello_World_dog", RegexOptions.None, 0, 19, false, string.Empty };
// Atomic Zero-Width Assertions \A \Z \z \G \b \B
yield return new object[] { @"\A(cat)\s+(dog)", "cat \n\n\ncat dog", RegexOptions.None, 0, 20, false, string.Empty };
yield return new object[] { @"\A(cat)\s+(dog)", "cat \n\n\ncat dog", RegexOptions.Multiline, 0, 20, false, string.Empty };
yield return new object[] { @"\A(cat)\s+(dog)", "cat \n\n\ncat dog", RegexOptions.ECMAScript, 0, 20, false, string.Empty };
yield return new object[] { @"(cat)\s+(dog)\Z", "cat dog\n\n\ncat", RegexOptions.None, 0, 15, false, string.Empty };
yield return new object[] { @"(cat)\s+(dog)\Z", "cat dog\n\n\ncat ", RegexOptions.Multiline, 0, 20, false, string.Empty };
yield return new object[] { @"(cat)\s+(dog)\Z", "cat dog\n\n\ncat ", RegexOptions.ECMAScript, 0, 20, false, string.Empty };
yield return new object[] { @"(cat)\s+(dog)\z", "cat dog\n\n\ncat", RegexOptions.None, 0, 15, false, string.Empty };
yield return new object[] { @"(cat)\s+(dog)\z", "cat dog\n\n\ncat ", RegexOptions.Multiline, 0, 20, false, string.Empty };
yield return new object[] { @"(cat)\s+(dog)\z", "cat dog\n\n\ncat ", RegexOptions.ECMAScript, 0, 20, false, string.Empty };
yield return new object[] { @"(cat)\s+(dog)\z", "cat \n\n\n dog\n", RegexOptions.None, 0, 16, false, string.Empty };
yield return new object[] { @"(cat)\s+(dog)\z", "cat \n\n\n dog\n", RegexOptions.Multiline, 0, 16, false, string.Empty };
yield return new object[] { @"(cat)\s+(dog)\z", "cat \n\n\n dog\n", RegexOptions.ECMAScript, 0, 16, false, string.Empty };
yield return new object[] { @"\b@cat", "123START123;@catEND", RegexOptions.None, 0, 19, false, string.Empty };
yield return new object[] { @"\b<cat", "123START123'<catEND", RegexOptions.None, 0, 19, false, string.Empty };
yield return new object[] { @"\b,cat", "satwe,,,START',catEND", RegexOptions.None, 0, 21, false, string.Empty };
yield return new object[] { @"\b\[cat", "`12START123'[catEND", RegexOptions.None, 0, 19, false, string.Empty };
yield return new object[] { @"\B@cat", "123START123@catEND", RegexOptions.None, 0, 18, false, string.Empty };
yield return new object[] { @"\B<cat", "123START123<catEND", RegexOptions.None, 0, 18, false, string.Empty };
yield return new object[] { @"\B,cat", "satwe,,,START,catEND", RegexOptions.None, 0, 20, false, string.Empty };
yield return new object[] { @"\B\[cat", "`12START123[catEND", RegexOptions.None, 0, 18, false, string.Empty };
// Lazy operator Backtracking
yield return new object[] { @"http://([a-zA-z0-9\-]*\.?)*?(:[0-9]*)??/", "http://www.msn.com", RegexOptions.IgnoreCase, 0, 18, false, string.Empty };
// Grouping Constructs Invalid Regular Expressions
yield return new object[] { "(?!)", "(?!)cat", RegexOptions.None, 0, 7, false, string.Empty };
yield return new object[] { "(?<!)", "(?<!)cat", RegexOptions.None, 0, 8, false, string.Empty };
// Alternation construct
yield return new object[] { "(?(cat)|dog)", "cat", RegexOptions.None, 0, 3, true, string.Empty };
yield return new object[] { "(?(cat)|dog)", "catdog", RegexOptions.None, 0, 6, true, string.Empty };
yield return new object[] { "(?(cat)dog1|dog2)", "catdog1", RegexOptions.None, 0, 7, false, string.Empty };
yield return new object[] { "(?(cat)dog1|dog2)", "catdog2", RegexOptions.None, 0, 7, true, "dog2" };
yield return new object[] { "(?(cat)dog1|dog2)", "catdog1dog2", RegexOptions.None, 0, 11, true, "dog2" };
yield return new object[] { "(?(dog2))", "dog2", RegexOptions.None, 0, 4, true, string.Empty };
yield return new object[] { "(?(cat)|dog)", "oof", RegexOptions.None, 0, 3, false, string.Empty };
yield return new object[] { "(?(a:b))", "a", RegexOptions.None, 0, 1, true, string.Empty };
yield return new object[] { "(?(a:))", "a", RegexOptions.None, 0, 1, true, string.Empty };
// No Negation
yield return new object[] { "[abcd-[abcd]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { "[1234-[1234]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
// All Negation
yield return new object[] { "[^abcd-[^abcd]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { "[^1234-[^1234]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
// No Negation
yield return new object[] { "[a-z-[a-z]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { "[0-9-[0-9]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
// All Negation
yield return new object[] { "[^a-z-[^a-z]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { "[^0-9-[^0-9]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
// No Negation
yield return new object[] { @"[\w-[\w]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\W-[\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\s-[\s]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\S-[\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\d-[\d]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\D-[\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
// All Negation
yield return new object[] { @"[^\w-[^\w]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\W-[^\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\s-[^\s]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\S-[^\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\d-[^\d]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\D-[^\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
// MixedNegation
yield return new object[] { @"[^\w-[\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\w-[^\W]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\s-[\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\s-[^\S]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\d-[\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\d-[^\D]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
// No Negation
yield return new object[] { @"[\p{Ll}-[\p{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\P{Ll}-[\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\p{Lu}-[\p{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\P{Lu}-[\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\p{Nd}-[\p{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\P{Nd}-[\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
// All Negation
yield return new object[] { @"[^\p{Ll}-[^\p{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\P{Ll}-[^\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\p{Lu}-[^\p{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\P{Lu}-[^\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\p{Nd}-[^\p{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\P{Nd}-[^\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
// MixedNegation
yield return new object[] { @"[^\p{Ll}-[\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\p{Ll}-[^\P{Ll}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\p{Lu}-[\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\p{Lu}-[^\P{Lu}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[^\p{Nd}-[\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
yield return new object[] { @"[\p{Nd}-[^\P{Nd}]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty };
// Character Class Substraction
yield return new object[] { @"[ab\-\[cd-[-[]]]]", "[]]", RegexOptions.None, 0, 3, false, string.Empty };
yield return new object[] { @"[ab\-\[cd-[-[]]]]", "-]]", RegexOptions.None, 0, 3, false, string.Empty };
yield return new object[] { @"[ab\-\[cd-[-[]]]]", "`]]", RegexOptions.None, 0, 3, false, string.Empty };
yield return new object[] { @"[ab\-\[cd-[-[]]]]", "e]]", RegexOptions.None, 0, 3, false, string.Empty };
yield return new object[] { @"[ab\-\[cd-[[]]]]", "']]", RegexOptions.None, 0, 3, false, string.Empty };
yield return new object[] { @"[ab\-\[cd-[[]]]]", "e]]", RegexOptions.None, 0, 3, false, string.Empty };
yield return new object[] { @"[a-[a-f]]", "abcdefghijklmnopqrstuvwxyz", RegexOptions.None, 0, 26, false, string.Empty };
}
[Theory]
[MemberData(nameof(Match_Basic_TestData))]
public void Match(string pattern, string input, RegexOptions options, int beginning, int length, bool expectedSuccess, string expectedValue)
{
bool isDefaultStart = RegexHelpers.IsDefaultStart(input, options, beginning);
bool isDefaultCount = RegexHelpers.IsDefaultCount(input, options, length);
if (options == RegexOptions.None)
{
if (isDefaultStart && isDefaultCount)
{
// Use Match(string) or Match(string, string)
VerifyMatch(new Regex(pattern).Match(input), expectedSuccess, expectedValue);
VerifyMatch(Regex.Match(input, pattern), expectedSuccess, expectedValue);
Assert.Equal(expectedSuccess, new Regex(pattern).IsMatch(input));
Assert.Equal(expectedSuccess, Regex.IsMatch(input, pattern));
}
if (beginning + length == input.Length)
{
// Use Match(string, int)
VerifyMatch(new Regex(pattern).Match(input, beginning), expectedSuccess, expectedValue);
Assert.Equal(expectedSuccess, new Regex(pattern).IsMatch(input, beginning));
}
// Use Match(string, int, int)
VerifyMatch(new Regex(pattern).Match(input, beginning, length), expectedSuccess, expectedValue);
}
if (isDefaultStart && isDefaultCount)
{
// Use Match(string) or Match(string, string, RegexOptions)
VerifyMatch(new Regex(pattern, options).Match(input), expectedSuccess, expectedValue);
VerifyMatch(Regex.Match(input, pattern, options), expectedSuccess, expectedValue);
Assert.Equal(expectedSuccess, Regex.IsMatch(input, pattern, options));
}
if (beginning + length == input.Length && (options & RegexOptions.RightToLeft) == 0)
{
// Use Match(string, int)
VerifyMatch(new Regex(pattern, options).Match(input, beginning), expectedSuccess, expectedValue);
}
// Use Match(string, int, int)
VerifyMatch(new Regex(pattern, options).Match(input, beginning, length), expectedSuccess, expectedValue);
}
public static void VerifyMatch(Match match, bool expectedSuccess, string expectedValue)
{
Assert.Equal(expectedSuccess, match.Success);
Assert.Equal(expectedValue, match.Value);
// Groups can never be empty
Assert.True(match.Groups.Count >= 1);
Assert.Equal(expectedSuccess, match.Groups[0].Success);
Assert.Equal(expectedValue, match.Groups[0].Value);
}
[Fact]
public void Match_Timeout()
{
Regex regex = new Regex(@"\p{Lu}", RegexOptions.IgnoreCase, TimeSpan.FromHours(1));
Match match = regex.Match("abc");
Assert.True(match.Success);
Assert.Equal("a", match.Value);
}
public static IEnumerable<object[]> Match_Advanced_TestData()
{
// \B special character escape: ".*\\B(SUCCESS)\\B.*"
yield return new object[]
{
@".*\B(SUCCESS)\B.*", "adfadsfSUCCESSadsfadsf", RegexOptions.None, 0, 22,
new CaptureData[]
{
new CaptureData("adfadsfSUCCESSadsfadsf", 0, 22),
new CaptureData("SUCCESS", 7, 7)
}
};
// Using |, (), ^, $, .: Actual - "^aaa(bb.+)(d|c)$"
yield return new object[]
{
"^aaa(bb.+)(d|c)$", "aaabb.cc", RegexOptions.None, 0, 8,
new CaptureData[]
{
new CaptureData("aaabb.cc", 0, 8),
new CaptureData("bb.c", 3, 4),
new CaptureData("c", 7, 1)
}
};
// Using greedy quantifiers: Actual - "(a+)(b*)(c?)"
yield return new object[]
{
"(a+)(b*)(c?)", "aaabbbccc", RegexOptions.None, 0, 9,
new CaptureData[]
{
new CaptureData("aaabbbc", 0, 7),
new CaptureData("aaa", 0, 3),
new CaptureData("bbb", 3, 3),
new CaptureData("c", 6, 1)
}
};
// Using lazy quantifiers: Actual - "(d+?)(e*?)(f??)"
// Interesting match from this pattern and input. If needed to go to the end of the string change the ? to + in the last lazy quantifier
yield return new object[]
{
"(d+?)(e*?)(f??)", "dddeeefff", RegexOptions.None, 0, 9,
new CaptureData[]
{
new CaptureData("d", 0, 1),
new CaptureData("d", 0, 1),
new CaptureData(string.Empty, 1, 0),
new CaptureData(string.Empty, 1, 0)
}
};
// Noncapturing group : Actual - "(a+)(?:b*)(ccc)"
yield return new object[]
{
"(a+)(?:b*)(ccc)", "aaabbbccc", RegexOptions.None, 0, 9,
new CaptureData[]
{
new CaptureData("aaabbbccc", 0, 9),
new CaptureData("aaa", 0, 3),
new CaptureData("ccc", 6, 3),
}
};
// Zero-width positive lookahead assertion: Actual - "abc(?=XXX)\\w+"
yield return new object[]
{
@"abc(?=XXX)\w+", "abcXXXdef", RegexOptions.None, 0, 9,
new CaptureData[]
{
new CaptureData("abcXXXdef", 0, 9)
}
};
// Backreferences : Actual - "(\\w)\\1"
yield return new object[]
{
@"(\w)\1", "aa", RegexOptions.None, 0, 2,
new CaptureData[]
{
new CaptureData("aa", 0, 2),
new CaptureData("a", 0, 1),
}
};
// Alternation constructs: Actual - "(111|aaa)"
yield return new object[]
{
"(111|aaa)", "aaa", RegexOptions.None, 0, 3,
new CaptureData[]
{
new CaptureData("aaa", 0, 3),
new CaptureData("aaa", 0, 3)
}
};
// Actual - "(?<1>\\d+)abc(?(1)222|111)"
yield return new object[]
{
@"(?<MyDigits>\d+)abc(?(MyDigits)222|111)", "111abc222", RegexOptions.None, 0, 9,
new CaptureData[]
{
new CaptureData("111abc222", 0, 9),
new CaptureData("111", 0, 3)
}
};
// Using "n" Regex option. Only explicitly named groups should be captured: Actual - "([0-9]*)\\s(?<s>[a-z_A-Z]+)", "n"
yield return new object[]
{
@"([0-9]*)\s(?<s>[a-z_A-Z]+)", "200 dollars", RegexOptions.ExplicitCapture, 0, 11,
new CaptureData[]
{
new CaptureData("200 dollars", 0, 11),
new CaptureData("dollars", 4, 7)
}
};
// Single line mode "s". Includes new line character: Actual - "([^/]+)","s"
yield return new object[]
{
"(.*)", "abc\nsfc", RegexOptions.Singleline, 0, 7,
new CaptureData[]
{
new CaptureData("abc\nsfc", 0, 7),
new CaptureData("abc\nsfc", 0, 7),
}
};
// "([0-9]+(\\.[0-9]+){3})"
yield return new object[]
{
@"([0-9]+(\.[0-9]+){3})", "209.25.0.111", RegexOptions.None, 0, 12,
new CaptureData[]
{
new CaptureData("209.25.0.111", 0, 12),
new CaptureData("209.25.0.111", 0, 12),
new CaptureData(".111", 8, 4, new CaptureData[]
{
new CaptureData(".25", 3, 3),
new CaptureData(".0", 6, 2),
new CaptureData(".111", 8, 4),
}),
}
};
// Groups and captures
yield return new object[]
{
@"(?<A1>a*)(?<A2>b*)(?<A3>c*)", "aaabbccccccccccaaaabc", RegexOptions.None, 0, 21,
new CaptureData[]
{
new CaptureData("aaabbcccccccccc", 0, 15),
new CaptureData("aaa", 0, 3),
new CaptureData("bb", 3, 2),
new CaptureData("cccccccccc", 5, 10)
}
};
yield return new object[]
{
@"(?<A1>A*)(?<A2>B*)(?<A3>C*)", "aaabbccccccccccaaaabc", RegexOptions.IgnoreCase, 0, 21,
new CaptureData[]
{
new CaptureData("aaabbcccccccccc", 0, 15),
new CaptureData("aaa", 0, 3),
new CaptureData("bb", 3, 2),
new CaptureData("cccccccccc", 5, 10)
}
};
// Using |, (), ^, $, .: Actual - "^aaa(bb.+)(d|c)$"
yield return new object[]
{
"^aaa(bb.+)(d|c)$", "aaabb.cc", RegexOptions.None, 0, 8,
new CaptureData[]
{
new CaptureData("aaabb.cc", 0, 8),
new CaptureData("bb.c", 3, 4),
new CaptureData("c", 7, 1)
}
};
// Actual - ".*\\b(\\w+)\\b"
yield return new object[]
{
@".*\b(\w+)\b", "XSP_TEST_FAILURE SUCCESS", RegexOptions.None, 0, 24,
new CaptureData[]
{
new CaptureData("XSP_TEST_FAILURE SUCCESS", 0, 24),
new CaptureData("SUCCESS", 17, 7)
}
};
// Mutliline
yield return new object[]
{
"(line2$\n)line3", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24,
new CaptureData[]
{
new CaptureData("line2\nline3", 6, 11),
new CaptureData("line2\n", 6, 6)
}
};
// Mutliline
yield return new object[]
{
"(line2\n^)line3", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24,
new CaptureData[]
{
new CaptureData("line2\nline3", 6, 11),
new CaptureData("line2\n", 6, 6)
}
};
// Mutliline
yield return new object[]
{
"(line3\n$\n)line4", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24,
new CaptureData[]
{
new CaptureData("line3\n\nline4", 12, 12),
new CaptureData("line3\n\n", 12, 7)
}
};
// Mutliline
yield return new object[]
{
"(line3\n^\n)line4", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24,
new CaptureData[]
{
new CaptureData("line3\n\nline4", 12, 12),
new CaptureData("line3\n\n", 12, 7)
}
};
// Mutliline
yield return new object[]
{
"(line2$\n^)line3", "line1\nline2\nline3\n\nline4", RegexOptions.Multiline, 0, 24,
new CaptureData[]
{
new CaptureData("line2\nline3", 6, 11),
new CaptureData("line2\n", 6, 6)
}
};
// RightToLeft
yield return new object[]
{
"aaa", "aaabbb", RegexOptions.RightToLeft, 3, 3,
new CaptureData[]
{
new CaptureData("aaa", 0, 3)
}
};
}
[Theory]
[MemberData(nameof(Match_Advanced_TestData))]
public void Match(string pattern, string input, RegexOptions options, int beginning, int length, CaptureData[] expected)
{
bool isDefaultStart = RegexHelpers.IsDefaultStart(input, options, beginning);
bool isDefaultCount = RegexHelpers.IsDefaultStart(input, options, length);
if (options == RegexOptions.None)
{
if (isDefaultStart && isDefaultCount)
{
// Use Match(string) or Match(string, string)
VerifyMatch(new Regex(pattern).Match(input), true, expected);
VerifyMatch(Regex.Match(input, pattern), true, expected);
Assert.True(new Regex(pattern).IsMatch(input));
Assert.True(Regex.IsMatch(input, pattern));
}
if (beginning + length == input.Length)
{
// Use Match(string, int)
VerifyMatch(new Regex(pattern).Match(input, beginning), true, expected);
Assert.True(new Regex(pattern).IsMatch(input, beginning));
}
else
{
// Use Match(string, int, int)
VerifyMatch(new Regex(pattern).Match(input, beginning, length), true, expected);
}
}
if (isDefaultStart && isDefaultCount)
{
// Use Match(string) or Match(string, string, RegexOptions)
VerifyMatch(new Regex(pattern, options).Match(input), true, expected);
VerifyMatch(Regex.Match(input, pattern, options), true, expected);
Assert.True(Regex.IsMatch(input, pattern, options));
}
if (beginning + length == input.Length)
{
// Use Match(string, int)
VerifyMatch(new Regex(pattern, options).Match(input, beginning), true, expected);
}
if ((options & RegexOptions.RightToLeft) == 0)
{
// Use Match(string, int, int)
VerifyMatch(new Regex(pattern, options).Match(input, beginning, length), true, expected);
}
}
public static void VerifyMatch(Match match, bool expectedSuccess, CaptureData[] expected)
{
Assert.Equal(expectedSuccess, match.Success);
Assert.Equal(expected[0].Value, match.Value);
Assert.Equal(expected[0].Index, match.Index);
Assert.Equal(expected[0].Length, match.Length);
Assert.Equal(1, match.Captures.Count);
Assert.Equal(expected[0].Value, match.Captures[0].Value);
Assert.Equal(expected[0].Index, match.Captures[0].Index);
Assert.Equal(expected[0].Length, match.Captures[0].Length);
Assert.Equal(expected.Length, match.Groups.Count);
for (int i = 0; i < match.Groups.Count; i++)
{
Assert.Equal(expectedSuccess, match.Groups[i].Success);
Assert.Equal(expected[i].Value, match.Groups[i].Value);
Assert.Equal(expected[i].Index, match.Groups[i].Index);
Assert.Equal(expected[i].Length, match.Groups[i].Length);
Assert.Equal(expected[i].Captures.Length, match.Groups[i].Captures.Count);
for (int j = 0; j < match.Groups[i].Captures.Count; j++)
{
Assert.Equal(expected[i].Captures[j].Value, match.Groups[i].Captures[j].Value);
Assert.Equal(expected[i].Captures[j].Index, match.Groups[i].Captures[j].Index);
Assert.Equal(expected[i].Captures[j].Length, match.Groups[i].Captures[j].Length);
}
}
}
[Theory]
[InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${time}", "16:00")]
[InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${1}", "08")]
[InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${2}", "10")]
[InlineData(@"(?<1>\d{1,2})/(?<2>\d{1,2})/(?<3>\d{2,4})\s(?<time>\S+)", "08/10/99 16:00", "${3}", "99")]
[InlineData("abc", "abc", "abc", "abc")]
public void Result(string pattern, string input, string replacement, string expected)
{
Assert.Equal(expected, new Regex(pattern).Match(input).Result(replacement));
}
[Fact]
public void Result_Invalid()
{
Match match = Regex.Match("foo", "foo");
AssertExtensions.Throws<ArgumentNullException>("replacement", () => match.Result(null));
Assert.Throws<NotSupportedException>(() => RegularExpressions.Match.Empty.Result("any"));
}
[Fact]
public void Match_SpecialUnicodeCharacters_enUS()
{
RemoteInvoke(() =>
{
CultureInfo.CurrentCulture = new CultureInfo("en-US");
Match("\u0131", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
Match("\u0131", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void Match_SpecialUnicodeCharacters_Invariant()
{
RemoteInvoke(() =>
{
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
Match("\u0131", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
Match("\u0131", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
Match("\u0130", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
Match("\u0130", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void Match_Invalid()
{
// Input is null
AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Match(null, "pattern"));
AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Match(null, "pattern", RegexOptions.None));
AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Match(null, "pattern", RegexOptions.None, TimeSpan.FromSeconds(1)));
AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Match(null));
AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Match(null, 0));
AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Match(null, 0, 0));
// Pattern is null
AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Match("input", null));
AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Match("input", null, RegexOptions.None));
AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Match("input", null, RegexOptions.None, TimeSpan.FromSeconds(1)));
// Start is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").Match("input", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").Match("input", -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").Match("input", 6));
Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").Match("input", 6, 0));
// Length is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => new Regex("pattern").Match("input", 0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => new Regex("pattern").Match("input", 0, 6));
}
[Theory]
[InlineData(")")]
[InlineData("())")]
[InlineData("[a-z-[aeiuo]")]
[InlineData("[a-z-[aeiuo")]
[InlineData("[a-z-[b]")]
[InlineData("[a-z-[b")]
[InlineData("[b-a]")]
[InlineData(@"[a-c]{2,1}")]
[InlineData(@"\d{2147483648}")]
[InlineData("[a-z-[b][")]
[InlineData(@"\")]
[InlineData("(?()|||||)")]
public void Match_InvalidPattern(string pattern)
{
AssertExtensions.Throws<ArgumentException>(null, () => Regex.Match("input", pattern));
}
[Fact]
public void IsMatch_Invalid()
{
// Input is null
AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.IsMatch(null, "pattern"));
AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.IsMatch(null, "pattern", RegexOptions.None));
AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.IsMatch(null, "pattern", RegexOptions.None, TimeSpan.FromSeconds(1)));
AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").IsMatch(null));
AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").IsMatch(null, 0));
// Pattern is null
AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.IsMatch("input", null));
AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.IsMatch("input", null, RegexOptions.None));
AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.IsMatch("input", null, RegexOptions.None, TimeSpan.FromSeconds(1)));
// Start is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").IsMatch("input", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new Regex("pattern").IsMatch("input", 6));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Text;
using System.Xml.XPath;
using System.Collections;
namespace System.Xml.Xsl.XsltOld
{
internal sealed class RecordBuilder
{
private int _outputState;
private RecordBuilder _next;
private readonly IRecordOutput _output;
// Atomization:
private readonly XmlNameTable _nameTable;
private readonly OutKeywords _atoms;
// Namespace manager for output
private readonly OutputScopeManager _scopeManager;
// Main node + Fields Collection
private readonly BuilderInfo _mainNode = new BuilderInfo();
private readonly ArrayList _attributeList = new ArrayList();
private int _attributeCount;
private readonly ArrayList _namespaceList = new ArrayList();
private int _namespaceCount;
private readonly BuilderInfo _dummy = new BuilderInfo();
// Current position in the list
private BuilderInfo _currentInfo;
// Builder state
private bool _popScope;
private int _recordState;
private int _recordDepth;
private const int NoRecord = 0; // No part of a new record was generated (old record was cleared out)
private const int SomeRecord = 1; // Record was generated partially (can be eventually record)
private const int HaveRecord = 2; // Record was fully generated
private const char s_Minus = '-';
private const string s_Space = " ";
private const string s_SpaceMinus = " -";
private const char s_Question = '?';
private const char s_Greater = '>';
private const string s_SpaceGreater = " >";
private const string PrefixFormat = "xp_{0}";
internal RecordBuilder(IRecordOutput output, XmlNameTable nameTable)
{
Debug.Assert(output != null);
_output = output;
_nameTable = nameTable != null ? nameTable : new NameTable();
_atoms = new OutKeywords(_nameTable);
_scopeManager = new OutputScopeManager(_nameTable, _atoms);
}
//
// Internal properties
//
internal int OutputState
{
get { return _outputState; }
set { _outputState = value; }
}
internal RecordBuilder Next
{
get { return _next; }
set { _next = value; }
}
internal IRecordOutput Output
{
get { return _output; }
}
internal BuilderInfo MainNode
{
get { return _mainNode; }
}
internal ArrayList AttributeList
{
get { return _attributeList; }
}
internal int AttributeCount
{
get { return _attributeCount; }
}
internal OutputScopeManager Manager
{
get { return _scopeManager; }
}
private void ValueAppend(string s, bool disableOutputEscaping)
{
_currentInfo.ValueAppend(s, disableOutputEscaping);
}
private bool CanOutput(int state)
{
Debug.Assert(_recordState != HaveRecord);
// If we have no record cached or the next event doesn't start new record, we are OK
if (_recordState == NoRecord || (state & StateMachine.BeginRecord) == 0)
{
return true;
}
else
{
_recordState = HaveRecord;
FinalizeRecord();
SetEmptyFlag(state);
return _output.RecordDone(this) == Processor.OutputResult.Continue;
}
}
internal Processor.OutputResult BeginEvent(int state, XPathNodeType nodeType, string prefix, string name, string nspace, bool empty, object htmlProps, bool search)
{
if (!CanOutput(state))
{
return Processor.OutputResult.Overflow;
}
Debug.Assert(_recordState == NoRecord || (state & StateMachine.BeginRecord) == 0);
AdjustDepth(state);
ResetRecord(state);
PopElementScope();
prefix = (prefix != null) ? _nameTable.Add(prefix) : _atoms.Empty;
name = (name != null) ? _nameTable.Add(name) : _atoms.Empty;
nspace = (nspace != null) ? _nameTable.Add(nspace) : _atoms.Empty;
switch (nodeType)
{
case XPathNodeType.Element:
_mainNode.htmlProps = htmlProps as HtmlElementProps;
_mainNode.search = search;
BeginElement(prefix, name, nspace, empty);
break;
case XPathNodeType.Attribute:
BeginAttribute(prefix, name, nspace, htmlProps, search);
break;
case XPathNodeType.Namespace:
BeginNamespace(name, nspace);
break;
case XPathNodeType.Text:
break;
case XPathNodeType.ProcessingInstruction:
if (BeginProcessingInstruction(prefix, name, nspace) == false)
{
return Processor.OutputResult.Error;
}
break;
case XPathNodeType.Comment:
BeginComment();
break;
case XPathNodeType.Root:
break;
case XPathNodeType.Whitespace:
case XPathNodeType.SignificantWhitespace:
case XPathNodeType.All:
break;
}
return CheckRecordBegin(state);
}
internal Processor.OutputResult TextEvent(int state, string text, bool disableOutputEscaping)
{
if (!CanOutput(state))
{
return Processor.OutputResult.Overflow;
}
Debug.Assert(_recordState == NoRecord || (state & StateMachine.BeginRecord) == 0);
AdjustDepth(state);
ResetRecord(state);
PopElementScope();
if ((state & StateMachine.BeginRecord) != 0)
{
_currentInfo.Depth = _recordDepth;
_currentInfo.NodeType = XmlNodeType.Text;
}
ValueAppend(text, disableOutputEscaping);
return CheckRecordBegin(state);
}
internal Processor.OutputResult EndEvent(int state, XPathNodeType nodeType)
{
if (!CanOutput(state))
{
return Processor.OutputResult.Overflow;
}
AdjustDepth(state);
PopElementScope();
_popScope = (state & StateMachine.PopScope) != 0;
if ((state & StateMachine.EmptyTag) != 0 && _mainNode.IsEmptyTag == true)
{
return Processor.OutputResult.Continue;
}
ResetRecord(state);
if ((state & StateMachine.BeginRecord) != 0)
{
if (nodeType == XPathNodeType.Element)
{
EndElement();
}
}
return CheckRecordEnd(state);
}
internal void Reset()
{
if (_recordState == HaveRecord)
{
_recordState = NoRecord;
}
}
internal void TheEnd()
{
if (_recordState == SomeRecord)
{
_recordState = HaveRecord;
FinalizeRecord();
_output.RecordDone(this);
}
_output.TheEnd();
}
//
// Utility implementation methods
//
private int FindAttribute(string name, string nspace, ref string prefix)
{
Debug.Assert(_attributeCount <= _attributeList.Count);
for (int attrib = 0; attrib < _attributeCount; attrib++)
{
Debug.Assert(_attributeList[attrib] != null && _attributeList[attrib] is BuilderInfo);
BuilderInfo attribute = (BuilderInfo)_attributeList[attrib];
if (Ref.Equal(attribute.LocalName, name))
{
if (Ref.Equal(attribute.NamespaceURI, nspace))
{
return attrib;
}
if (Ref.Equal(attribute.Prefix, prefix))
{
// prefix conflict. Should be renamed.
prefix = string.Empty;
}
}
}
return -1;
}
private void BeginElement(string prefix, string name, string nspace, bool empty)
{
Debug.Assert(_attributeCount == 0);
_currentInfo.NodeType = XmlNodeType.Element;
_currentInfo.Prefix = prefix;
_currentInfo.LocalName = name;
_currentInfo.NamespaceURI = nspace;
_currentInfo.Depth = _recordDepth;
_currentInfo.IsEmptyTag = empty;
_scopeManager.PushScope(name, nspace, prefix);
}
private void EndElement()
{
Debug.Assert(_attributeCount == 0);
OutputScope elementScope = _scopeManager.CurrentElementScope;
_currentInfo.NodeType = XmlNodeType.EndElement;
_currentInfo.Prefix = elementScope.Prefix;
_currentInfo.LocalName = elementScope.Name;
_currentInfo.NamespaceURI = elementScope.Namespace;
_currentInfo.Depth = _recordDepth;
}
private int NewAttribute()
{
if (_attributeCount >= _attributeList.Count)
{
Debug.Assert(_attributeCount == _attributeList.Count);
_attributeList.Add(new BuilderInfo());
}
return _attributeCount++;
}
private void BeginAttribute(string prefix, string name, string nspace, object htmlAttrProps, bool search)
{
int attrib = FindAttribute(name, nspace, ref prefix);
if (attrib == -1)
{
attrib = NewAttribute();
}
Debug.Assert(_attributeList[attrib] != null && _attributeList[attrib] is BuilderInfo);
BuilderInfo attribute = (BuilderInfo)_attributeList[attrib];
attribute.Initialize(prefix, name, nspace);
attribute.Depth = _recordDepth;
attribute.NodeType = XmlNodeType.Attribute;
attribute.htmlAttrProps = htmlAttrProps as HtmlAttributeProps;
attribute.search = search;
_currentInfo = attribute;
}
private void BeginNamespace(string name, string nspace)
{
bool thisScope = false;
if (Ref.Equal(name, _atoms.Empty))
{
if (Ref.Equal(nspace, _scopeManager.DefaultNamespace))
{
// Main Node is OK
}
else if (Ref.Equal(_mainNode.NamespaceURI, _atoms.Empty))
{
// http://www.w3.org/1999/11/REC-xslt-19991116-errata/ E25
// Should throw an error but ingnoring it in Everett.
// Would be a breaking change
}
else
{
DeclareNamespace(nspace, name);
}
}
else
{
string nspaceDeclared = _scopeManager.ResolveNamespace(name, out thisScope);
if (nspaceDeclared != null)
{
if (!Ref.Equal(nspace, nspaceDeclared))
{
if (!thisScope)
{
DeclareNamespace(nspace, name);
}
}
}
else
{
DeclareNamespace(nspace, name);
}
}
_currentInfo = _dummy;
_currentInfo.NodeType = XmlNodeType.Attribute;
}
private bool BeginProcessingInstruction(string prefix, string name, string nspace)
{
_currentInfo.NodeType = XmlNodeType.ProcessingInstruction;
_currentInfo.Prefix = prefix;
_currentInfo.LocalName = name;
_currentInfo.NamespaceURI = nspace;
_currentInfo.Depth = _recordDepth;
return true;
}
private void BeginComment()
{
_currentInfo.NodeType = XmlNodeType.Comment;
_currentInfo.Depth = _recordDepth;
}
private void AdjustDepth(int state)
{
switch (state & StateMachine.DepthMask)
{
case StateMachine.DepthUp:
_recordDepth++;
break;
case StateMachine.DepthDown:
_recordDepth--;
break;
default:
break;
}
}
private void ResetRecord(int state)
{
Debug.Assert(_recordState == NoRecord || _recordState == SomeRecord);
if ((state & StateMachine.BeginRecord) != 0)
{
_attributeCount = 0;
_namespaceCount = 0;
_currentInfo = _mainNode;
_currentInfo.Initialize(_atoms.Empty, _atoms.Empty, _atoms.Empty);
_currentInfo.NodeType = XmlNodeType.None;
_currentInfo.IsEmptyTag = false;
_currentInfo.htmlProps = null;
_currentInfo.htmlAttrProps = null;
}
}
private void PopElementScope()
{
if (_popScope)
{
_scopeManager.PopScope();
_popScope = false;
}
}
private Processor.OutputResult CheckRecordBegin(int state)
{
Debug.Assert(_recordState == NoRecord || _recordState == SomeRecord);
if ((state & StateMachine.EndRecord) != 0)
{
_recordState = HaveRecord;
FinalizeRecord();
SetEmptyFlag(state);
return _output.RecordDone(this);
}
else
{
_recordState = SomeRecord;
return Processor.OutputResult.Continue;
}
}
private Processor.OutputResult CheckRecordEnd(int state)
{
Debug.Assert(_recordState == NoRecord || _recordState == SomeRecord);
if ((state & StateMachine.EndRecord) != 0)
{
_recordState = HaveRecord;
FinalizeRecord();
SetEmptyFlag(state);
return _output.RecordDone(this);
}
else
{
// For end event, if there is no end token, don't force token
return Processor.OutputResult.Continue;
}
}
private void SetEmptyFlag(int state)
{
Debug.Assert(_mainNode != null);
if ((state & StateMachine.BeginChild) != 0)
{
_mainNode.IsEmptyTag = false;
}
}
private void AnalyzeSpaceLang()
{
Debug.Assert(_mainNode.NodeType == XmlNodeType.Element);
for (int attr = 0; attr < _attributeCount; attr++)
{
Debug.Assert(_attributeList[attr] is BuilderInfo);
BuilderInfo info = (BuilderInfo)_attributeList[attr];
if (Ref.Equal(info.Prefix, _atoms.Xml))
{
OutputScope scope = _scopeManager.CurrentElementScope;
if (Ref.Equal(info.LocalName, _atoms.Lang))
{
scope.Lang = info.Value;
}
else if (Ref.Equal(info.LocalName, _atoms.Space))
{
scope.Space = TranslateXmlSpace(info.Value);
}
}
}
}
private void FixupElement()
{
Debug.Assert(_mainNode.NodeType == XmlNodeType.Element);
if (Ref.Equal(_mainNode.NamespaceURI, _atoms.Empty))
{
_mainNode.Prefix = _atoms.Empty;
}
if (Ref.Equal(_mainNode.Prefix, _atoms.Empty))
{
if (Ref.Equal(_mainNode.NamespaceURI, _scopeManager.DefaultNamespace))
{
// Main Node is OK
}
else
{
DeclareNamespace(_mainNode.NamespaceURI, _mainNode.Prefix);
}
}
else
{
bool thisScope = false;
string nspace = _scopeManager.ResolveNamespace(_mainNode.Prefix, out thisScope);
if (nspace != null)
{
if (!Ref.Equal(_mainNode.NamespaceURI, nspace))
{
if (thisScope)
{ // Prefix conflict
_mainNode.Prefix = GetPrefixForNamespace(_mainNode.NamespaceURI);
}
else
{
DeclareNamespace(_mainNode.NamespaceURI, _mainNode.Prefix);
}
}
}
else
{
DeclareNamespace(_mainNode.NamespaceURI, _mainNode.Prefix);
}
}
OutputScope elementScope = _scopeManager.CurrentElementScope;
elementScope.Prefix = _mainNode.Prefix;
}
private void FixupAttributes(int attributeCount)
{
for (int attr = 0; attr < attributeCount; attr++)
{
Debug.Assert(_attributeList[attr] is BuilderInfo);
BuilderInfo info = (BuilderInfo)_attributeList[attr];
if (Ref.Equal(info.NamespaceURI, _atoms.Empty))
{
info.Prefix = _atoms.Empty;
}
else
{
if (Ref.Equal(info.Prefix, _atoms.Empty))
{
info.Prefix = GetPrefixForNamespace(info.NamespaceURI);
}
else
{
bool thisScope = false;
string nspace = _scopeManager.ResolveNamespace(info.Prefix, out thisScope);
if (nspace != null)
{
if (!Ref.Equal(info.NamespaceURI, nspace))
{
if (thisScope)
{ // prefix conflict
info.Prefix = GetPrefixForNamespace(info.NamespaceURI);
}
else
{
DeclareNamespace(info.NamespaceURI, info.Prefix);
}
}
}
else
{
DeclareNamespace(info.NamespaceURI, info.Prefix);
}
}
}
}
}
private void AppendNamespaces()
{
for (int i = _namespaceCount - 1; i >= 0; i--)
{
BuilderInfo attribute = (BuilderInfo)_attributeList[NewAttribute()];
attribute.Initialize((BuilderInfo)_namespaceList[i]);
}
}
private void AnalyzeComment()
{
Debug.Assert(_mainNode.NodeType == XmlNodeType.Comment);
Debug.Assert((object)_currentInfo == (object)_mainNode);
StringBuilder newComment = null;
string comment = _mainNode.Value;
bool minus = false;
int index = 0, begin = 0;
for (; index < comment.Length; index++)
{
switch (comment[index])
{
case s_Minus:
if (minus)
{
if (newComment == null)
newComment = new StringBuilder(comment, begin, index, 2 * comment.Length);
else
newComment.Append(comment, begin, index - begin);
newComment.Append(s_SpaceMinus);
begin = index + 1;
}
minus = true;
break;
default:
minus = false;
break;
}
}
if (newComment != null)
{
if (begin < comment.Length)
newComment.Append(comment, begin, comment.Length - begin);
if (minus)
newComment.Append(s_Space);
_mainNode.Value = newComment.ToString();
}
else if (minus)
{
_mainNode.ValueAppend(s_Space, false);
}
}
private void AnalyzeProcessingInstruction()
{
Debug.Assert(_mainNode.NodeType == XmlNodeType.ProcessingInstruction || _mainNode.NodeType == XmlNodeType.XmlDeclaration);
//Debug.Assert((object) this.currentInfo == (object) this.mainNode);
StringBuilder newPI = null;
string pi = _mainNode.Value;
bool question = false;
int index = 0, begin = 0;
for (; index < pi.Length; index++)
{
switch (pi[index])
{
case s_Question:
question = true;
break;
case s_Greater:
if (question)
{
if (newPI == null)
{
newPI = new StringBuilder(pi, begin, index, 2 * pi.Length);
}
else
{
newPI.Append(pi, begin, index - begin);
}
newPI.Append(s_SpaceGreater);
begin = index + 1;
}
question = false;
break;
default:
question = false;
break;
}
}
if (newPI != null)
{
if (begin < pi.Length)
{
newPI.Append(pi, begin, pi.Length - begin);
}
_mainNode.Value = newPI.ToString();
}
}
private void FinalizeRecord()
{
switch (_mainNode.NodeType)
{
case XmlNodeType.Element:
// Save count since FixupElement can add attribute...
int attributeCount = _attributeCount;
FixupElement();
FixupAttributes(attributeCount);
AnalyzeSpaceLang();
AppendNamespaces();
break;
case XmlNodeType.Comment:
AnalyzeComment();
break;
case XmlNodeType.ProcessingInstruction:
AnalyzeProcessingInstruction();
break;
}
}
private int NewNamespace()
{
if (_namespaceCount >= _namespaceList.Count)
{
Debug.Assert(_namespaceCount == _namespaceList.Count);
_namespaceList.Add(new BuilderInfo());
}
return _namespaceCount++;
}
private void DeclareNamespace(string nspace, string prefix)
{
int index = NewNamespace();
Debug.Assert(_namespaceList[index] != null && _namespaceList[index] is BuilderInfo);
BuilderInfo ns = (BuilderInfo)_namespaceList[index];
if (prefix == _atoms.Empty)
{
ns.Initialize(_atoms.Empty, _atoms.Xmlns, _atoms.XmlnsNamespace);
}
else
{
ns.Initialize(_atoms.Xmlns, prefix, _atoms.XmlnsNamespace);
}
ns.Depth = _recordDepth;
ns.NodeType = XmlNodeType.Attribute;
ns.Value = nspace;
_scopeManager.PushNamespace(prefix, nspace);
}
private string DeclareNewNamespace(string nspace)
{
string prefix = _scopeManager.GeneratePrefix(PrefixFormat);
DeclareNamespace(nspace, prefix);
return prefix;
}
internal string GetPrefixForNamespace(string nspace)
{
string prefix = null;
if (_scopeManager.FindPrefix(nspace, out prefix))
{
Debug.Assert(prefix != null && prefix.Length > 0);
return prefix;
}
else
{
return DeclareNewNamespace(nspace);
}
}
private static XmlSpace TranslateXmlSpace(string space)
{
if (space == "default")
{
return XmlSpace.Default;
}
else if (space == "preserve")
{
return XmlSpace.Preserve;
}
else
{
return XmlSpace.None;
}
}
}
}
| |
/*
* 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.Data;
using System.Reflection;
using System.Collections.Generic;
using log4net;
using MySql.Data.MySqlClient;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Data;
namespace OpenSim.Data.MySQL
{
/// <summary>
/// A MySQL Interface for the Asset Server
/// </summary>
public class MySQLAssetData : AssetDataBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_connectionString;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
#region IPlugin Members
public override string Version { get { return "1.0.0.0"; } }
/// <summary>
/// <para>Initialises Asset interface</para>
/// <para>
/// <list type="bullet">
/// <item>Loads and initialises the MySQL storage plugin.</item>
/// <item>Warns and uses the obsolete mysql_connection.ini if connect string is empty.</item>
/// <item>Check for migration</item>
/// </list>
/// </para>
/// </summary>
/// <param name="connect">connect string</param>
public override void Initialise(string connect)
{
m_connectionString = connect;
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
Migration m = new Migration(dbcon, Assembly, "AssetStore");
m.Update();
dbcon.Close();
}
}
public override void Initialise()
{
throw new NotImplementedException();
}
public override void Dispose() { }
/// <summary>
/// The name of this DB provider
/// </summary>
override public string Name
{
get { return "MySQL Asset storage engine"; }
}
#endregion
#region IAssetDataPlugin Members
/// <summary>
/// Fetch Asset <paramref name="assetID"/> from database
/// </summary>
/// <param name="assetID">Asset UUID to fetch</param>
/// <returns>Return the asset</returns>
/// <remarks>On failure : throw an exception and attempt to reconnect to database</remarks>
override public AssetBase GetAsset(UUID assetID)
{
AssetBase asset = null;
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = new MySqlCommand(
"SELECT name, description, assetType, local, temporary, asset_flags, CreatorID, data FROM assets WHERE id=?id",
dbcon))
{
cmd.Parameters.AddWithValue("?id", assetID.ToString());
try
{
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (dbReader.Read())
{
asset = new AssetBase(assetID, (string)dbReader["name"], (sbyte)dbReader["assetType"], dbReader["CreatorID"].ToString());
asset.Data = (byte[])dbReader["data"];
asset.Description = (string)dbReader["description"];
string local = dbReader["local"].ToString();
if (local.Equals("1") || local.Equals("true", StringComparison.InvariantCultureIgnoreCase))
asset.Local = true;
else
asset.Local = false;
asset.Temporary = Convert.ToBoolean(dbReader["temporary"]);
asset.Flags = (AssetFlags)Convert.ToInt32(dbReader["asset_flags"]);
}
}
}
catch (Exception e)
{
m_log.Error(
string.Format("[ASSETS DB]: MySql failure fetching asset {0}. Exception ", assetID), e);
}
}
dbcon.Close();
}
return asset;
}
/// <summary>
/// Create an asset in database, or update it if existing.
/// </summary>
/// <param name="asset">Asset UUID to create</param>
/// <remarks>On failure : Throw an exception and attempt to reconnect to database</remarks>
override public bool StoreAsset(AssetBase asset)
{
string assetName = asset.Name;
if (asset.Name.Length > AssetBase.MAX_ASSET_NAME)
{
assetName = asset.Name.Substring(0, AssetBase.MAX_ASSET_NAME);
m_log.WarnFormat(
"[ASSET DB]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add",
asset.Name, asset.ID, asset.Name.Length, assetName.Length);
}
string assetDescription = asset.Description;
if (asset.Description.Length > AssetBase.MAX_ASSET_DESC)
{
assetDescription = asset.Description.Substring(0, AssetBase.MAX_ASSET_DESC);
m_log.WarnFormat(
"[ASSET DB]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add",
asset.Description, asset.ID, asset.Description.Length, assetDescription.Length);
}
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd =
new MySqlCommand(
"replace INTO assets(id, name, description, assetType, local, temporary, create_time, access_time, asset_flags, CreatorID, data)" +
"VALUES(?id, ?name, ?description, ?assetType, ?local, ?temporary, ?create_time, ?access_time, ?asset_flags, ?CreatorID, ?data)",
dbcon))
{
try
{
// create unix epoch time
int now = (int)Utils.DateTimeToUnixTime(DateTime.UtcNow);
cmd.Parameters.AddWithValue("?id", asset.ID);
cmd.Parameters.AddWithValue("?name", assetName);
cmd.Parameters.AddWithValue("?description", assetDescription);
cmd.Parameters.AddWithValue("?assetType", asset.Type);
cmd.Parameters.AddWithValue("?local", asset.Local);
cmd.Parameters.AddWithValue("?temporary", asset.Temporary);
cmd.Parameters.AddWithValue("?create_time", now);
cmd.Parameters.AddWithValue("?access_time", now);
cmd.Parameters.AddWithValue("?CreatorID", asset.Metadata.CreatorID);
cmd.Parameters.AddWithValue("?asset_flags", (int)asset.Flags);
cmd.Parameters.AddWithValue("?data", asset.Data);
cmd.ExecuteNonQuery();
dbcon.Close();
return true;
}
catch (Exception e)
{
m_log.ErrorFormat("[ASSET DB]: MySQL failure creating asset {0} with name \"{1}\". Error: {2}",
asset.FullID, asset.Name, e.Message);
dbcon.Close();
return false;
}
}
}
}
private void UpdateAccessTime(AssetBase asset)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd
= new MySqlCommand("update assets set access_time=?access_time where id=?id", dbcon))
{
try
{
// create unix epoch time
int now = (int)Utils.DateTimeToUnixTime(DateTime.UtcNow);
cmd.Parameters.AddWithValue("?id", asset.ID);
cmd.Parameters.AddWithValue("?access_time", now);
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
m_log.Error(
string.Format(
"[ASSETS DB]: Failure updating access_time for asset {0} with name {1}. Exception ",
asset.FullID, asset.Name),
e);
}
}
dbcon.Close();
}
}
/// <summary>
/// Check if the assets exist in the database.
/// </summary>
/// <param name="uuidss">The assets' IDs</param>
/// <returns>For each asset: true if it exists, false otherwise</returns>
public override bool[] AssetsExist(UUID[] uuids)
{
if (uuids.Length == 0)
return new bool[0];
HashSet<UUID> exist = new HashSet<UUID>();
string ids = "'" + string.Join("','", uuids) + "'";
string sql = string.Format("SELECT id FROM assets WHERE id IN ({0})", ids);
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = new MySqlCommand(sql, dbcon))
{
using (MySqlDataReader dbReader = cmd.ExecuteReader())
{
while (dbReader.Read())
{
UUID id = DBGuid.FromDB(dbReader["id"]);
exist.Add(id);
}
}
}
dbcon.Close();
}
bool[] results = new bool[uuids.Length];
for (int i = 0; i < uuids.Length; i++)
results[i] = exist.Contains(uuids[i]);
return results;
}
/// <summary>
/// Returns a list of AssetMetadata objects. The list is a subset of
/// the entire data set offset by <paramref name="start" /> containing
/// <paramref name="count" /> elements.
/// </summary>
/// <param name="start">The number of results to discard from the total data set.</param>
/// <param name="count">The number of rows the returned list should contain.</param>
/// <returns>A list of AssetMetadata objects.</returns>
public override List<AssetMetadata> FetchAssetMetadataSet(int start, int count)
{
List<AssetMetadata> retList = new List<AssetMetadata>(count);
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd
= new MySqlCommand(
"SELECT name,description,assetType,temporary,id,asset_flags,CreatorID FROM assets LIMIT ?start, ?count",
dbcon))
{
cmd.Parameters.AddWithValue("?start", start);
cmd.Parameters.AddWithValue("?count", count);
try
{
using (MySqlDataReader dbReader = cmd.ExecuteReader())
{
while (dbReader.Read())
{
AssetMetadata metadata = new AssetMetadata();
metadata.Name = (string)dbReader["name"];
metadata.Description = (string)dbReader["description"];
metadata.Type = (sbyte)dbReader["assetType"];
metadata.Temporary = Convert.ToBoolean(dbReader["temporary"]); // Not sure if this is correct.
metadata.Flags = (AssetFlags)Convert.ToInt32(dbReader["asset_flags"]);
metadata.FullID = DBGuid.FromDB(dbReader["id"]);
metadata.CreatorID = dbReader["CreatorID"].ToString();
// Current SHA1s are not stored/computed.
metadata.SHA1 = new byte[] { };
retList.Add(metadata);
}
}
}
catch (Exception e)
{
m_log.Error(
string.Format(
"[ASSETS DB]: MySql failure fetching asset set from {0}, count {1}. Exception ",
start, count),
e);
}
}
dbcon.Close();
}
return retList;
}
public override bool Delete(string id)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = new MySqlCommand("delete from assets where id=?id", dbcon))
{
cmd.Parameters.AddWithValue("?id", id);
cmd.ExecuteNonQuery();
}
dbcon.Close();
}
return 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.
using System.Net.Http.Headers;
using Xunit;
namespace System.Net.Http.Tests
{
public class AuthenticationHeaderValueTest
{
[Fact]
public void Ctor_SetBothSchemeAndParameters_MatchExpectation()
{
AuthenticationHeaderValue auth = new AuthenticationHeaderValue("Basic", "realm=\"contoso.com\"");
Assert.Equal("Basic", auth.Scheme);
Assert.Equal("realm=\"contoso.com\"", auth.Parameter);
Assert.Throws<ArgumentException>(() => { new AuthenticationHeaderValue(null, "x"); });
Assert.Throws<ArgumentException>(() => { new AuthenticationHeaderValue("", "x"); });
Assert.Throws<FormatException>(() => { new AuthenticationHeaderValue(" x", "x"); });
Assert.Throws<FormatException>(() => { new AuthenticationHeaderValue("x ", "x"); });
Assert.Throws<FormatException>(() => { new AuthenticationHeaderValue("x y", "x"); });
}
[Fact]
public void Ctor_SetSchemeOnly_MatchExpectation()
{
// Just verify that this ctor forwards the call to the overload taking 2 parameters.
AuthenticationHeaderValue auth = new AuthenticationHeaderValue("NTLM");
Assert.Equal("NTLM", auth.Scheme);
Assert.Null(auth.Parameter);
}
[Fact]
public void ToString_UseBothNoParameterAndSetParameter_AllSerializedCorrectly()
{
HttpResponseMessage response = new HttpResponseMessage();
string input = string.Empty;
AuthenticationHeaderValue auth = new AuthenticationHeaderValue("Digest",
"qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\"");
Assert.Equal(
"Digest qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\"",
auth.ToString());
response.Headers.ProxyAuthenticate.Add(auth);
input += auth.ToString();
auth = new AuthenticationHeaderValue("Negotiate");
Assert.Equal("Negotiate", auth.ToString());
response.Headers.ProxyAuthenticate.Add(auth);
input += ", " + auth.ToString();
auth = new AuthenticationHeaderValue("Custom", ""); // empty string should be treated like 'null'.
Assert.Equal("Custom", auth.ToString());
response.Headers.ProxyAuthenticate.Add(auth);
input += ", " + auth.ToString();
string result = response.Headers.ProxyAuthenticate.ToString();
Assert.Equal(input, result);
}
[Fact]
public void Parse_GoodValues_Success()
{
HttpRequestMessage request = new HttpRequestMessage();
string input = " Digest qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8 ";
request.Headers.Authorization = AuthenticationHeaderValue.Parse(input);
Assert.Equal(input.Trim(), request.Headers.Authorization.ToString());
}
[Fact]
public void TryParse_GoodValues_Success()
{
HttpRequestMessage request = new HttpRequestMessage();
string input = " Digest qop=\"auth\",algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",realm=\"Digest\" ";
AuthenticationHeaderValue parsedValue;
Assert.True(AuthenticationHeaderValue.TryParse(input, out parsedValue));
request.Headers.Authorization = parsedValue;
Assert.Equal(input.Trim(), request.Headers.Authorization.ToString());
}
[Fact]
public void Parse_BadValues_Throws()
{
string input = "D\rigest qop=\"auth\",algorithm=MD5-sess,charset=utf-8,realm=\"Digest\"";
Assert.Throws<FormatException>(() => { AuthenticationHeaderValue.Parse(input); });
}
[Fact]
public void TryParse_BadValues_False()
{
string input = ", Digest qop=\"auth\",nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\"";
AuthenticationHeaderValue parsedValue;
Assert.False(AuthenticationHeaderValue.TryParse(input, out parsedValue));
}
[Fact]
public void Add_BadValues_Throws()
{
string x = SR.net_http_message_not_success_statuscode;
string input = "Digest algorithm=MD5-sess,nonce=\"+Upgraded+v109e309640b\",charset=utf-8,realm=\"Digest\", ";
HttpRequestMessage request = new HttpRequestMessage();
Assert.Throws<FormatException>(() => { request.Headers.Add(HttpKnownHeaderNames.Authorization, input); });
}
[Fact]
public void GetHashCode_UseSameAndDifferentAuth_SameOrDifferentHashCodes()
{
AuthenticationHeaderValue auth1 = new AuthenticationHeaderValue("A", "b");
AuthenticationHeaderValue auth2 = new AuthenticationHeaderValue("a", "b");
AuthenticationHeaderValue auth3 = new AuthenticationHeaderValue("A", "B");
AuthenticationHeaderValue auth4 = new AuthenticationHeaderValue("A");
AuthenticationHeaderValue auth5 = new AuthenticationHeaderValue("A", "");
AuthenticationHeaderValue auth6 = new AuthenticationHeaderValue("X", "b");
Assert.Equal(auth1.GetHashCode(), auth2.GetHashCode());
Assert.NotEqual(auth1.GetHashCode(), auth3.GetHashCode());
Assert.NotEqual(auth1.GetHashCode(), auth4.GetHashCode());
Assert.Equal(auth4.GetHashCode(), auth5.GetHashCode());
Assert.NotEqual(auth1.GetHashCode(), auth6.GetHashCode());
}
[Fact]
public void Equals_UseSameAndDifferentAuth_EqualOrNotEqualNoExceptions()
{
AuthenticationHeaderValue auth1 = new AuthenticationHeaderValue("A", "b");
AuthenticationHeaderValue auth2 = new AuthenticationHeaderValue("a", "b");
AuthenticationHeaderValue auth3 = new AuthenticationHeaderValue("A", "B");
AuthenticationHeaderValue auth4 = new AuthenticationHeaderValue("A");
AuthenticationHeaderValue auth5 = new AuthenticationHeaderValue("A", "");
AuthenticationHeaderValue auth6 = new AuthenticationHeaderValue("X", "b");
Assert.False(auth1.Equals(null));
Assert.True(auth1.Equals(auth2));
Assert.False(auth1.Equals(auth3));
Assert.False(auth1.Equals(auth4));
Assert.False(auth4.Equals(auth1));
Assert.False(auth1.Equals(auth5));
Assert.False(auth5.Equals(auth1));
Assert.True(auth4.Equals(auth5));
Assert.True(auth5.Equals(auth4));
Assert.False(auth1.Equals(auth6));
}
[Fact]
public void Clone_Call_CloneFieldsMatchSourceFields()
{
AuthenticationHeaderValue source = new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
AuthenticationHeaderValue clone = (AuthenticationHeaderValue)((ICloneable)source).Clone();
Assert.Equal(source.Scheme, clone.Scheme);
Assert.Equal(source.Parameter, clone.Parameter);
source = new AuthenticationHeaderValue("Kerberos");
clone = (AuthenticationHeaderValue)((ICloneable)source).Clone();
Assert.Equal(source.Scheme, clone.Scheme);
Assert.Null(clone.Parameter);
}
[Fact]
public void GetAuthenticationLength_DifferentValidScenarios_AllReturnNonZero()
{
CallGetAuthenticationLength(" Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== ", 1, 37,
new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="));
CallGetAuthenticationLength(" Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== , ", 1, 37,
new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="));
CallGetAuthenticationLength(" Basic realm=\"example.com\"", 1, 25,
new AuthenticationHeaderValue("Basic", "realm=\"example.com\""));
CallGetAuthenticationLength(" Basic realm=\"exam,,ple.com\",", 1, 27,
new AuthenticationHeaderValue("Basic", "realm=\"exam,,ple.com\""));
CallGetAuthenticationLength(" Basic realm=\"exam,ple.com\",", 1, 26,
new AuthenticationHeaderValue("Basic", "realm=\"exam,ple.com\""));
CallGetAuthenticationLength("NTLM ", 0, 7, new AuthenticationHeaderValue("NTLM"));
CallGetAuthenticationLength("Digest", 0, 6, new AuthenticationHeaderValue("Digest"));
CallGetAuthenticationLength("Digest,,", 0, 6, new AuthenticationHeaderValue("Digest"));
CallGetAuthenticationLength("Digest a=b, c=d,,", 0, 15, new AuthenticationHeaderValue("Digest", "a=b, c=d"));
CallGetAuthenticationLength("Kerberos,", 0, 8, new AuthenticationHeaderValue("Kerberos"));
CallGetAuthenticationLength("Basic,NTLM", 0, 5, new AuthenticationHeaderValue("Basic"));
CallGetAuthenticationLength("Digest a=b,c=\"d\", e=f, NTLM", 0, 21,
new AuthenticationHeaderValue("Digest", "a=b,c=\"d\", e=f"));
CallGetAuthenticationLength("Digest a = b , c = \"d\" , e = f ,NTLM", 0, 32,
new AuthenticationHeaderValue("Digest", "a = b , c = \"d\" , e = f"));
CallGetAuthenticationLength("Digest a = b , c = \"d\" , e = f , NTLM AbCdEf==", 0, 32,
new AuthenticationHeaderValue("Digest", "a = b , c = \"d\" , e = f"));
CallGetAuthenticationLength("Digest a = \"b\", c= \"d\" , e = f,NTLM AbC=,", 0, 31,
new AuthenticationHeaderValue("Digest", "a = \"b\", c= \"d\" , e = f"));
CallGetAuthenticationLength("Digest a=\"b\", c=d", 0, 17,
new AuthenticationHeaderValue("Digest", "a=\"b\", c=d"));
CallGetAuthenticationLength("Digest a=\"b\", c=d,", 0, 17,
new AuthenticationHeaderValue("Digest", "a=\"b\", c=d"));
CallGetAuthenticationLength("Digest a=\"b\", c=d ,", 0, 18,
new AuthenticationHeaderValue("Digest", "a=\"b\", c=d"));
CallGetAuthenticationLength("Digest a=\"b\", c=d ", 0, 19,
new AuthenticationHeaderValue("Digest", "a=\"b\", c=d"));
CallGetAuthenticationLength("Custom \"blob\", c=d,Custom2 \"blob\"", 0, 18,
new AuthenticationHeaderValue("Custom", "\"blob\", c=d"));
CallGetAuthenticationLength("Custom \"blob\", a=b,,,c=d,Custom2 \"blob\"", 0, 24,
new AuthenticationHeaderValue("Custom", "\"blob\", a=b,,,c=d"));
CallGetAuthenticationLength("Custom \"blob\", a=b,c=d,,,Custom2 \"blob\"", 0, 22,
new AuthenticationHeaderValue("Custom", "\"blob\", a=b,c=d"));
CallGetAuthenticationLength("Custom a=b, c=d,,,InvalidNextScheme\u670D", 0, 15,
new AuthenticationHeaderValue("Custom", "a=b, c=d"));
}
[Fact]
public void GetAuthenticationLength_DifferentInvalidScenarios_AllReturnZero()
{
CheckInvalidGetAuthenticationLength(" NTLM", 0); // no leading whitespace allowed
CheckInvalidGetAuthenticationLength("Basic=", 0);
CheckInvalidGetAuthenticationLength("=Basic", 0);
CheckInvalidGetAuthenticationLength("Digest a=b, \u670D", 0);
CheckInvalidGetAuthenticationLength("Digest a=b, c=d, \u670D", 0);
CheckInvalidGetAuthenticationLength("Digest a=b, c=", 0);
CheckInvalidGetAuthenticationLength("Digest a=\"b, c", 0);
CheckInvalidGetAuthenticationLength("Digest a=\"b", 0);
CheckInvalidGetAuthenticationLength("Digest a=b, c=\u670D", 0);
CheckInvalidGetAuthenticationLength("", 0);
CheckInvalidGetAuthenticationLength(null, 0);
}
#region Helper methods
private static void CallGetAuthenticationLength(string input, int startIndex, int expectedLength,
AuthenticationHeaderValue expectedResult)
{
object result = null;
Assert.Equal(expectedLength, AuthenticationHeaderValue.GetAuthenticationLength(input, startIndex, out result));
Assert.Equal(expectedResult, result);
}
private static void CheckInvalidGetAuthenticationLength(string input, int startIndex)
{
object result = null;
Assert.Equal(0, AuthenticationHeaderValue.GetAuthenticationLength(input, startIndex, out result));
Assert.Null(result);
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// Replace the unity default camera gameobject "Main Camera" with this object and you
/// can move your camera and look around the world with whatever keys you like
/// </summary>
[AddComponentMenu("Camera-Control/Smooth Mouse Look")]
public class FreeMouseLook : MonoBehaviour
{
#region Variables
public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityX = 15F;
public float sensitivityY = 15F;
public float movementSpeed = 5F;
public float secondaryMovementSpeed = 2.5f;
public float minimumX = -360F;
public float maximumX = 360F;
public float minimumY = -60F;
public float maximumY = 60F;
public bool m_CameraRotationOn = false;
protected float rotationX = 0F;
protected float rotationY = 0F;
public KeyCode[] m_MoveForwardKeys = new KeyCode[]{KeyCode.W, KeyCode.UpArrow};
public KeyCode[] m_MoveBackwardKeys = new KeyCode[] { KeyCode.S, KeyCode.DownArrow };
public KeyCode[] m_MoveLeftKeys = new KeyCode[] { KeyCode.A, KeyCode.LeftArrow };
public KeyCode[] m_MoveRightKeys = new KeyCode[] { KeyCode.D, KeyCode.RightArrow };
public KeyCode[] m_MoveUpKeys = new KeyCode[] { KeyCode.E };
public KeyCode[] m_MoveDownKeys = new KeyCode[] { KeyCode.Q };
public KeyCode[] m_ToggleMouseLookKeys = new KeyCode[] { KeyCode.J };
public delegate void MovementCallback();
#endregion
#region Properties
public bool CameraRotationOn
{
get { return m_CameraRotationOn; }
set { m_CameraRotationOn = value; }
}
#endregion
#region Functions
public virtual void Start()
{
if (GetComponent<Rigidbody>())
GetComponent<Rigidbody>().freezeRotation = true;
rotationX = transform.localRotation.eulerAngles.y;
rotationY = transform.localRotation.eulerAngles.x;
}
public virtual void Update()
{
if (VHUtils.DoesInputHaveFocus())
return;
if (CameraRotationOn)
{
if (axes == RotationAxes.MouseXAndY)
{
rotationY += Input.GetAxis("Mouse Y") * -sensitivityY;
rotationX += Input.GetAxis("Mouse X") * sensitivityX;
rotationY = ClampAngle(rotationY, minimumY, maximumY);
rotationX = ClampAngle(rotationX, minimumX, maximumX);
Quaternion yQuaternion = Quaternion.AngleAxis(rotationY, Vector3.right);
Quaternion xQuaternion = Quaternion.AngleAxis(rotationX, Vector3.up);
transform.localRotation = xQuaternion * yQuaternion;
}
else if (axes == RotationAxes.MouseX)
{
rotationX += Input.GetAxis("Mouse X") * sensitivityX;
rotationX = ClampAngle(rotationX, minimumX, maximumX);
Quaternion xQuaternion = Quaternion.AngleAxis(rotationX, Vector3.up);
transform.localRotation = xQuaternion;
}
else
{
rotationY += Input.GetAxis("Mouse Y") * -sensitivityY;
rotationY = ClampAngle(rotationY, minimumY, maximumY);
Quaternion yQuaternion = Quaternion.AngleAxis(rotationY, Vector3.right);
transform.localRotation = yQuaternion;
}
}
CheckKeyPress(m_MoveForwardKeys, MoveForward);
CheckKeyPress(m_MoveBackwardKeys, MoveBackward);
CheckKeyPress(m_MoveLeftKeys, MoveLeft);
CheckKeyPress(m_MoveRightKeys, MoveRight);
CheckKeyPress(m_MoveUpKeys, MoveUp);
CheckKeyPress(m_MoveDownKeys, MoveDown);
CheckKeyDown(m_ToggleMouseLookKeys, ToggleMouseLook);
}
protected float GetMovementSpeed()
{
return Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift) ? secondaryMovementSpeed : movementSpeed;
}
public virtual void MoveForward()
{
transform.localPosition += transform.forward * GetMovementSpeed() * Time.deltaTime;
}
public virtual void MoveBackward()
{
transform.localPosition += -transform.forward * GetMovementSpeed() * Time.deltaTime;
}
public virtual void MoveLeft()
{
transform.localPosition -= transform.right * GetMovementSpeed() * Time.deltaTime;
}
public virtual void MoveRight()
{
transform.localPosition += transform.right * GetMovementSpeed() * Time.deltaTime;
}
public virtual void MoveUp()
{
transform.localPosition += transform.up * GetMovementSpeed() * Time.deltaTime;
}
public virtual void MoveDown()
{
transform.localPosition -= transform.up * GetMovementSpeed() * Time.deltaTime;
}
public void ToggleMouseLook()
{
CameraRotationOn = !CameraRotationOn;
if (CameraRotationOn)
{
rotationX = transform.localRotation.eulerAngles.y;
if (rotationX > maximumX)
{
rotationX = -(360 - rotationX);
}
rotationY = transform.localRotation.eulerAngles.x;
if (rotationY > maximumY)
{
rotationY = -(360 - rotationY);
}
}
}
public void CheckKeyPress(KeyCode[] movementKeys, MovementCallback cb)
{
if (movementKeys == null)
{
return;
}
for (int i = 0; i < movementKeys.Length; i++)
{
if (Input.GetKey(movementKeys[i]))
{
cb();
break;
}
}
}
protected void CheckKeyDown(KeyCode[] movementKeys, MovementCallback cb)
{
if (movementKeys == null)
{
return;
}
for (int i = 0; i < movementKeys.Length; i++)
{
if (Input.GetKeyDown(movementKeys[i]))
{
cb();
break;
}
}
}
public static float ClampRot(float rot, float min, float max)
{
// unity isn't doing negative rotations anymore, so the angles have to clamped in a different way
if (rot < -max)
{
rot = -max;
}
else if (rot > -min)
{
rot = -min;
}
return rot;
}
public static float ClampAngle(float angle, float min, float max)
{
angle = angle % 360;
if ((angle >= -360F) && (angle <= 360F))
{
if (angle < -360F)
{
angle += 360F;
}
if (angle > 360F)
{
angle -= 360F;
}
}
return ClampRot(angle, min, max);
}
/*public static float ClampAngle(float angle, float min, float max)
{
angle = angle % 360;
if ((angle >= -360F) && (angle <= 360F))
{
if (angle < -360F)
{
angle += 360F;
}
if (angle > 360F)
{
angle -= 360F;
}
}
return Mathf.Clamp(angle, min, max);
}*/
#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 PartyHubAPI.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;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Table;
using Orleans.Runtime;
namespace Orleans.AzureUtils
{
internal class SiloInstanceTableEntry : TableEntity
{
public string DeploymentId { get; set; } // PartitionKey
public string Address { get; set; } // RowKey
public string Port { get; set; } // RowKey
public string Generation { get; set; } // RowKey
public string HostName { get; set; } // Mandatory
public string Status { get; set; } // Mandatory
public string ProxyPort { get; set; } // Optional
public string RoleName { get; set; } // Optional - only for Azure role
public string InstanceName { get; set; } // Optional - only for Azure role
public string UpdateZone { get; set; } // Optional - only for Azure role
public string FaultZone { get; set; } // Optional - only for Azure role
public string SuspectingSilos { get; set; } // For liveness
public string SuspectingTimes { get; set; } // For liveness
public string StartTime { get; set; } // Time this silo was started. For diagnostics.
public string IAmAliveTime { get; set; } // Time this silo updated it was alive. For diagnostics.
public string MembershipVersion { get; set; } // Special version row (for serializing table updates). // We'll have a designated row with only MembershipVersion column.
internal const string TABLE_VERSION_ROW = "VersionRow"; // Row key for version row.
internal const char Seperator = '-';
public static string ConstructRowKey(SiloAddress silo)
{
return String.Format("{0}-{1}-{2}", silo.Endpoint.Address, silo.Endpoint.Port, silo.Generation);
}
internal static SiloAddress UnpackRowKey(string rowKey)
{
var debugInfo = "UnpackRowKey";
try
{
#if DEBUG
debugInfo = String.Format("UnpackRowKey: RowKey={0}", rowKey);
Trace.TraceInformation(debugInfo);
#endif
int idx1 = rowKey.IndexOf(Seperator);
int idx2 = rowKey.LastIndexOf(Seperator);
#if DEBUG
debugInfo = String.Format("UnpackRowKey: RowKey={0} Idx1={1} Idx2={2}", rowKey, idx1, idx2);
#endif
var addressStr = rowKey.Substring(0, idx1);
var portStr = rowKey.Substring(idx1 + 1, idx2 - idx1 - 1);
var genStr = rowKey.Substring(idx2 + 1);
#if DEBUG
debugInfo = String.Format("UnpackRowKey: RowKey={0} -> Address={1} Port={2} Generation={3}", rowKey, addressStr, portStr, genStr);
Trace.TraceInformation(debugInfo);
#endif
IPAddress address = IPAddress.Parse(addressStr);
int port = Int32.Parse(portStr);
int generation = Int32.Parse(genStr);
return SiloAddress.New(new IPEndPoint(address, port), generation);
}
catch (Exception exc)
{
throw new AggregateException("Error from " + debugInfo, exc);
}
}
public override string ToString()
{
var sb = new StringBuilder();
if (RowKey.Equals(TABLE_VERSION_ROW))
{
sb.Append("VersionRow [").Append(DeploymentId);
sb.Append(" Deployment=").Append(DeploymentId);
sb.Append(" MembershipVersion=").Append(MembershipVersion);
sb.Append("]");
}
else
{
sb.Append("OrleansSilo [");
sb.Append(" Deployment=").Append(DeploymentId);
sb.Append(" LocalEndpoint=").Append(Address);
sb.Append(" LocalPort=").Append(Port);
sb.Append(" Generation=").Append(Generation);
sb.Append(" Host=").Append(HostName);
sb.Append(" Status=").Append(Status);
sb.Append(" ProxyPort=").Append(ProxyPort);
if (!string.IsNullOrEmpty(RoleName)) sb.Append(" RoleName=").Append(RoleName);
sb.Append(" Instance=").Append(InstanceName);
sb.Append(" UpgradeZone=").Append(UpdateZone);
sb.Append(" FaultZone=").Append(FaultZone);
if (!string.IsNullOrEmpty(SuspectingSilos)) sb.Append(" SuspectingSilos=").Append(SuspectingSilos);
if (!string.IsNullOrEmpty(SuspectingTimes)) sb.Append(" SuspectingTimes=").Append(SuspectingTimes);
sb.Append(" StartTime=").Append(StartTime);
sb.Append(" IAmAliveTime=").Append(IAmAliveTime);
sb.Append("]");
}
return sb.ToString();
}
}
internal class OrleansSiloInstanceManager
{
public string TableName { get { return INSTANCE_TABLE_NAME; } }
private const string INSTANCE_TABLE_NAME = "OrleansSiloInstances";
private readonly string INSTANCE_STATUS_CREATED = SiloStatus.Created.ToString(); //"Created";
private readonly string INSTANCE_STATUS_ACTIVE = SiloStatus.Active.ToString(); //"Active";
private readonly string INSTANCE_STATUS_DEAD = SiloStatus.Dead.ToString(); //"Dead";
private readonly AzureTableDataManager<SiloInstanceTableEntry> storage;
private readonly TraceLogger logger;
internal static TimeSpan initTimeout = AzureTableDefaultPolicies.TableCreationTimeout;
public string DeploymentId { get; private set; }
private OrleansSiloInstanceManager(string deploymentId, string storageConnectionString)
{
DeploymentId = deploymentId;
logger = TraceLogger.GetLogger(this.GetType().Name, TraceLogger.LoggerType.Runtime);
storage = new AzureTableDataManager<SiloInstanceTableEntry>(
INSTANCE_TABLE_NAME, storageConnectionString, logger);
}
public static async Task<OrleansSiloInstanceManager> GetManager(string deploymentId, string storageConnectionString)
{
var instance = new OrleansSiloInstanceManager(deploymentId, storageConnectionString);
try
{
await instance.storage.InitTableAsync()
.WithTimeout(initTimeout);
}
catch (TimeoutException te)
{
string errorMsg = String.Format("Unable to create or connect to the Azure table in {0}", initTimeout);
instance.logger.Error(ErrorCode.AzureTable_32, errorMsg, te);
throw new OrleansException(errorMsg, te);
}
catch (Exception ex)
{
string errorMsg = String.Format("Exception trying to create or connect to the Azure table: {0}", ex.Message);
instance.logger.Error(ErrorCode.AzureTable_33, errorMsg, ex);
throw new OrleansException(errorMsg, ex);
}
return instance;
}
public SiloInstanceTableEntry CreateTableVersionEntry(int tableVersion)
{
return new SiloInstanceTableEntry
{
DeploymentId = DeploymentId,
PartitionKey = DeploymentId,
RowKey = SiloInstanceTableEntry.TABLE_VERSION_ROW,
MembershipVersion = tableVersion.ToString(CultureInfo.InvariantCulture)
};
}
public void RegisterSiloInstance(SiloInstanceTableEntry entry)
{
entry.Status = INSTANCE_STATUS_CREATED;
logger.Info(ErrorCode.Runtime_Error_100270, "Registering silo instance: {0}", entry.ToString());
storage.UpsertTableEntryAsync(entry)
.WaitWithThrow(AzureTableDefaultPolicies.TableOperationTimeout);
}
public void UnregisterSiloInstance(SiloInstanceTableEntry entry)
{
entry.Status = INSTANCE_STATUS_DEAD;
logger.Info(ErrorCode.Runtime_Error_100271, "Unregistering silo instance: {0}", entry.ToString());
storage.UpsertTableEntryAsync(entry)
.WaitWithThrow(AzureTableDefaultPolicies.TableOperationTimeout);
}
public void ActivateSiloInstance(SiloInstanceTableEntry entry)
{
logger.Info(ErrorCode.Runtime_Error_100272, "Activating silo instance: {0}", entry.ToString());
entry.Status = INSTANCE_STATUS_ACTIVE;
storage.UpsertTableEntryAsync(entry)
.WaitWithThrow(AzureTableDefaultPolicies.TableOperationTimeout);
}
public async Task<IList<Uri>> FindAllGatewayProxyEndpoints()
{
IEnumerable<SiloInstanceTableEntry> gatewaySiloInstances = await FindAllGatewaySilos();
return gatewaySiloInstances.Select(ConvertToGatewayUri).ToList();
}
/// <summary>
/// Represent a silo instance entry in the gateway URI format.
/// </summary>
/// <param name="gateway">The input silo instance</param>
/// <returns></returns>
private static Uri ConvertToGatewayUri(SiloInstanceTableEntry gateway)
{
int proxyPort = 0;
if (!string.IsNullOrEmpty(gateway.ProxyPort))
int.TryParse(gateway.ProxyPort, out proxyPort);
int gen = 0;
if (!string.IsNullOrEmpty(gateway.Generation))
int.TryParse(gateway.Generation, out gen);
SiloAddress address = SiloAddress.New(new IPEndPoint(IPAddress.Parse(gateway.Address), proxyPort), gen);
return address.ToGatewayUri();
}
private async Task<IEnumerable<SiloInstanceTableEntry>> FindAllGatewaySilos()
{
if (logger.IsVerbose) logger.Verbose(ErrorCode.Runtime_Error_100277, "Searching for active gateway silos for deployment {0}.", this.DeploymentId);
const string zeroPort = "0";
try
{
Expression<Func<SiloInstanceTableEntry, bool>> query = instance =>
instance.PartitionKey == this.DeploymentId
&& instance.Status == INSTANCE_STATUS_ACTIVE
&& instance.ProxyPort != zeroPort;
var queryResults = await storage.ReadTableEntriesAndEtagsAsync(query)
.WithTimeout(AzureTableDefaultPolicies.TableOperationTimeout);
List<SiloInstanceTableEntry> gatewaySiloInstances = queryResults.Select(entity => entity.Item1).ToList();
logger.Info(ErrorCode.Runtime_Error_100278, "Found {0} active Gateway Silos for deployment {1}.", gatewaySiloInstances.Count, this.DeploymentId);
return gatewaySiloInstances;
}catch(Exception exc)
{
logger.Error(ErrorCode.Runtime_Error_100331, string.Format("Error searching for active gateway silos for deployment {0} ", this.DeploymentId), exc);
throw;
}
}
public async Task<string> DumpSiloInstanceTable()
{
var queryResults = await storage.ReadAllTableEntriesForPartitionAsync(this.DeploymentId);
SiloInstanceTableEntry[] entries = queryResults.Select(entry => entry.Item1).ToArray();
var sb = new StringBuilder();
sb.Append(String.Format("Deployment {0}. Silos: ", DeploymentId));
// Loop through the results, displaying information about the entity
Array.Sort(entries,
(e1, e2) =>
{
if (e1 == null) return (e2 == null) ? 0 : -1;
if (e2 == null) return (e1 == null) ? 0 : 1;
if (e1.InstanceName == null) return (e2.InstanceName == null) ? 0 : -1;
if (e2.InstanceName == null) return (e1.InstanceName == null) ? 0 : 1;
return String.CompareOrdinal(e1.InstanceName, e2.InstanceName);
});
foreach (SiloInstanceTableEntry entry in entries)
{
sb.AppendLine(String.Format("[IP {0}:{1}:{2}, {3}, Instance={4}, Status={5}]", entry.Address, entry.Port, entry.Generation,
entry.HostName, entry.InstanceName, entry.Status));
}
return sb.ToString();
}
#region Silo instance table storage operations
internal Task<string> MergeTableEntryAsync(SiloInstanceTableEntry data)
{
return storage.MergeTableEntryAsync(data, AzureStorageUtils.ANY_ETAG); // we merge this without checking eTags.
}
internal Task<Tuple<SiloInstanceTableEntry, string>> ReadSingleTableEntryAsync(string partitionKey, string rowKey)
{
return storage.ReadSingleTableEntryAsync(partitionKey, rowKey);
}
internal async Task<int> DeleteTableEntries(string deploymentId)
{
if (deploymentId == null) throw new ArgumentNullException("deploymentId");
var entries = await storage.ReadAllTableEntriesForPartitionAsync(deploymentId);
var entriesList = new List<Tuple<SiloInstanceTableEntry, string>>(entries);
if (entriesList.Count <= AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS)
{
await storage.DeleteTableEntriesAsync(entriesList);
}else
{
List<Task> tasks = new List<Task>();
foreach (var batch in entriesList.BatchIEnumerable(AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS))
{
tasks.Add(storage.DeleteTableEntriesAsync(batch));
}
await Task.WhenAll(tasks);
}
return entriesList.Count();
}
internal async Task<List<Tuple<SiloInstanceTableEntry, string>>> FindSiloEntryAndTableVersionRow(SiloAddress siloAddress)
{
string rowKey = SiloInstanceTableEntry.ConstructRowKey(siloAddress);
Expression<Func<SiloInstanceTableEntry, bool>> query = instance =>
instance.PartitionKey == DeploymentId
&& (instance.RowKey == rowKey || instance.RowKey == SiloInstanceTableEntry.TABLE_VERSION_ROW);
var queryResults = await storage.ReadTableEntriesAndEtagsAsync(query);
var asList = queryResults.ToList();
if (asList.Count < 1 || asList.Count > 2)
throw new KeyNotFoundException(string.Format("Could not find table version row or found too many entries. Was looking for key {0}, found = {1}", siloAddress.ToLongString(), Utils.EnumerableToString(asList)));
int numTableVersionRows = asList.Count(tuple => tuple.Item1.RowKey == SiloInstanceTableEntry.TABLE_VERSION_ROW);
if (numTableVersionRows < 1)
throw new KeyNotFoundException(string.Format("Did not read table version row. Read = {0}", Utils.EnumerableToString(asList)));
if (numTableVersionRows > 1)
throw new KeyNotFoundException(string.Format("Read {0} table version rows, while was expecting only 1. Read = {1}", numTableVersionRows, Utils.EnumerableToString(asList)));
return asList;
}
internal async Task<List<Tuple<SiloInstanceTableEntry, string>>> FindAllSiloEntries()
{
var queryResults = await storage.ReadAllTableEntriesForPartitionAsync(this.DeploymentId);
var asList = queryResults.ToList();
if (asList.Count < 1)
throw new KeyNotFoundException(string.Format("Could not find enough rows in the FindAllSiloEntries call. Found = {0}", Utils.EnumerableToString(asList)));
int numTableVersionRows = asList.Count(tuple => tuple.Item1.RowKey == SiloInstanceTableEntry.TABLE_VERSION_ROW);
if (numTableVersionRows < 1)
throw new KeyNotFoundException(string.Format("Did not find table version row. Read = {0}", Utils.EnumerableToString(asList)));
if (numTableVersionRows > 1)
throw new KeyNotFoundException(string.Format("Read {0} table version rows, while was expecting only 1. Read = {1}", numTableVersionRows, Utils.EnumerableToString(asList)));
return asList;
}
/// <summary>
/// Insert (create new) row entry
/// </summary>
internal async Task<bool> TryCreateTableVersionEntryAsync()
{
try
{
var versionRow = await storage.ReadSingleTableEntryAsync(DeploymentId, SiloInstanceTableEntry.TABLE_VERSION_ROW);
if (versionRow != null && versionRow.Item1 != null)
{
return false;
}
SiloInstanceTableEntry entry = CreateTableVersionEntry(0);
await storage.CreateTableEntryAsync(entry);
return true;
}
catch (Exception exc)
{
HttpStatusCode httpStatusCode;
string restStatus;
if (!AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) throw;
if (logger.IsVerbose2) logger.Verbose2("InsertSiloEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus);
if (AzureStorageUtils.IsContentionError(httpStatusCode)) return false;
throw;
}
}
/// <summary>
/// Insert (create new) row entry
/// </summary>
/// <param name="siloEntry">Silo Entry to be written</param>
/// <param name="tableVersionEntry">Version row to update</param>
/// <param name="tableVersionEtag">Version row eTag</param>
internal async Task<bool> InsertSiloEntryConditionally(SiloInstanceTableEntry siloEntry, SiloInstanceTableEntry tableVersionEntry, string tableVersionEtag)
{
try
{
await storage.InsertTwoTableEntriesConditionallyAsync(siloEntry, tableVersionEntry, tableVersionEtag);
return true;
}
catch (Exception exc)
{
HttpStatusCode httpStatusCode;
string restStatus;
if (!AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) throw;
if (logger.IsVerbose2) logger.Verbose2("InsertSiloEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus);
if (AzureStorageUtils.IsContentionError(httpStatusCode)) return false;
throw;
}
}
/// <summary>
/// Conditionally update the row for this entry, but only if the eTag matches with the current record in data store
/// </summary>
/// <param name="siloEntry">Silo Entry to be written</param>
/// <param name="entryEtag">ETag value for the entry being updated</param>
/// <param name="tableVersionEntry">Version row to update</param>
/// <param name="versionEtag">ETag value for the version row</param>
/// <returns></returns>
internal async Task<bool> UpdateSiloEntryConditionally(SiloInstanceTableEntry siloEntry, string entryEtag, SiloInstanceTableEntry tableVersionEntry, string versionEtag)
{
try
{
await storage.UpdateTwoTableEntriesConditionallyAsync(siloEntry, entryEtag, tableVersionEntry, versionEtag);
return true;
}
catch (Exception exc)
{
HttpStatusCode httpStatusCode;
string restStatus;
if (!AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) throw;
if (logger.IsVerbose2) logger.Verbose2("UpdateSiloEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus);
if (AzureStorageUtils.IsContentionError(httpStatusCode)) return false;
throw;
}
}
#endregion
}
}
| |
using System;
using ChainUtils.BouncyCastle.Crypto.Parameters;
using ChainUtils.BouncyCastle.Crypto.Utilities;
namespace ChainUtils.BouncyCastle.Crypto.Engines
{
/**
* Implementation of Bob Jenkin's ISAAC (Indirection Shift Accumulate Add and Count).
* see: http://www.burtleburtle.net/bob/rand/isaacafa.html
*/
public class IsaacEngine
: IStreamCipher
{
// Constants
private static readonly int sizeL = 8,
stateArraySize = sizeL<<5; // 256
// Cipher's internal state
private uint[] engineState = null, // mm
results = null; // randrsl
private uint a = 0, b = 0, c = 0;
// Engine state
private int index = 0;
private byte[] keyStream = new byte[stateArraySize<<2], // results expanded into bytes
workingKey = null;
private bool initialised = false;
/**
* initialise an ISAAC cipher.
*
* @param forEncryption whether or not we are for encryption.
* @param params the parameters required to set up the cipher.
* @exception ArgumentException if the params argument is
* inappropriate.
*/
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
if (!(parameters is KeyParameter))
throw new ArgumentException(
"invalid parameter passed to ISAAC Init - " + parameters.GetType().Name,
"parameters");
/*
* ISAAC encryption and decryption is completely
* symmetrical, so the 'forEncryption' is
* irrelevant.
*/
var p = (KeyParameter) parameters;
setKey(p.GetKey());
}
public byte ReturnByte(
byte input)
{
if (index == 0)
{
isaac();
keyStream = Pack.UInt32_To_BE(results);
}
var output = (byte)(keyStream[index]^input);
index = (index + 1) & 1023;
return output;
}
public void ProcessBytes(
byte[] input,
int inOff,
int len,
byte[] output,
int outOff)
{
if (!initialised)
throw new InvalidOperationException(AlgorithmName + " not initialised");
if ((inOff + len) > input.Length)
throw new DataLengthException("input buffer too short");
if ((outOff + len) > output.Length)
throw new DataLengthException("output buffer too short");
for (var i = 0; i < len; i++)
{
if (index == 0)
{
isaac();
keyStream = Pack.UInt32_To_BE(results);
}
output[i+outOff] = (byte)(keyStream[index]^input[i+inOff]);
index = (index + 1) & 1023;
}
}
public string AlgorithmName
{
get { return "ISAAC"; }
}
public void Reset()
{
setKey(workingKey);
}
// Private implementation
private void setKey(
byte[] keyBytes)
{
workingKey = keyBytes;
if (engineState == null)
{
engineState = new uint[stateArraySize];
}
if (results == null)
{
results = new uint[stateArraySize];
}
int i, j, k;
// Reset state
for (i = 0; i < stateArraySize; i++)
{
engineState[i] = results[i] = 0;
}
a = b = c = 0;
// Reset index counter for output
index = 0;
// Convert the key bytes to ints and put them into results[] for initialization
var t = new byte[keyBytes.Length + (keyBytes.Length & 3)];
Array.Copy(keyBytes, 0, t, 0, keyBytes.Length);
for (i = 0; i < t.Length; i+=4)
{
results[i >> 2] = Pack.LE_To_UInt32(t, i);
}
// It has begun?
var abcdefgh = new uint[sizeL];
for (i = 0; i < sizeL; i++)
{
abcdefgh[i] = 0x9e3779b9; // Phi (golden ratio)
}
for (i = 0; i < 4; i++)
{
mix(abcdefgh);
}
for (i = 0; i < 2; i++)
{
for (j = 0; j < stateArraySize; j+=sizeL)
{
for (k = 0; k < sizeL; k++)
{
abcdefgh[k] += (i<1) ? results[j+k] : engineState[j+k];
}
mix(abcdefgh);
for (k = 0; k < sizeL; k++)
{
engineState[j+k] = abcdefgh[k];
}
}
}
isaac();
initialised = true;
}
private void isaac()
{
uint x, y;
b += ++c;
for (var i = 0; i < stateArraySize; i++)
{
x = engineState[i];
switch (i & 3)
{
case 0: a ^= (a << 13); break;
case 1: a ^= (a >> 6); break;
case 2: a ^= (a << 2); break;
case 3: a ^= (a >> 16); break;
}
a += engineState[(i+128) & 0xFF];
engineState[i] = y = engineState[(int)((uint)x >> 2) & 0xFF] + a + b;
results[i] = b = engineState[(int)((uint)y >> 10) & 0xFF] + x;
}
}
private void mix(uint[] x)
{
x[0]^=x[1]<< 11; x[3]+=x[0]; x[1]+=x[2];
x[1]^=x[2]>> 2; x[4]+=x[1]; x[2]+=x[3];
x[2]^=x[3]<< 8; x[5]+=x[2]; x[3]+=x[4];
x[3]^=x[4]>> 16; x[6]+=x[3]; x[4]+=x[5];
x[4]^=x[5]<< 10; x[7]+=x[4]; x[5]+=x[6];
x[5]^=x[6]>> 4; x[0]+=x[5]; x[6]+=x[7];
x[6]^=x[7]<< 8; x[1]+=x[6]; x[7]+=x[0];
x[7]^=x[0]>> 9; x[2]+=x[7]; x[0]+=x[1];
}
}
}
| |
#region Copyright & License
// This is a modified copy of a file in the Apache Log4Net project.
// The primary change was to the namespace and comments.
// The remainder of this comment is taken verbatim from the original Apache file.
//
// Copyright 2001-2005 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.
//
#endregion
using System;
using System.IO;
using System.Collections;
namespace TracerX {
/// <summary>
/// This is the default object Renderer.
/// It renders most types by calling object.ToString().
/// However, it performs special formatting
/// for arrays, collections, and DictionaryEntry objects.
/// To create renderers for other types, implement IObjectRenderer
/// and add the new renderer class to RendererMap.
/// </summary>
internal sealed class DefaultRenderer : IObjectRenderer {
#region Constructors
/// <summary>
/// Default constructor
/// </summary>
/// <remarks>
/// <para>
/// Default constructor
/// </para>
/// </remarks>
public DefaultRenderer() {
}
#endregion
#region Implementation of IObjectRenderer
/// <summary>
/// Render the object <paramref name="obj"/> to a string
/// </summary>
/// <remarks>
/// <para>
/// Render the object <paramref name="obj"/> to a string.
/// </para>
/// <para>
/// The <paramref name="rendererMap"/> parameter is
/// provided to lookup and render other objects. This is
/// very useful where <paramref name="obj"/> contains
/// nested objects of unknown type. The <see cref="RendererMap.FindAndRender(object)"/>
/// method can be used to render these objects.
/// </para>
/// <para>
/// The default renderer supports rendering objects to strings as follows:
/// </para>
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <description>Rendered String</description>
/// </listheader>
/// <item>
/// <term><c>null</c></term>
/// <description>
/// <para>"(null)"</para>
/// </description>
/// </item>
/// <item>
/// <term><see cref="Array"/></term>
/// <description>
/// <para>
/// For a one dimensional array this is the
/// array type name, an open brace, followed by a comma
/// separated list of the elements (using the appropriate
/// renderer), followed by a close brace.
/// </para>
/// <para>
/// For example: <c>int[] {1, 2, 3}</c>.
/// </para>
/// <para>
/// If the array is not one dimensional the
/// <c>Array.ToString()</c> is returned.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term><see cref="IEnumerable"/>, <see cref="ICollection"/> & <see cref="IEnumerator"/></term>
/// <description>
/// <para>
/// Rendered as an open brace, followed by a comma
/// separated list of the elements (using the appropriate
/// renderer), followed by a close brace.
/// </para>
/// <para>
/// For example: <c>{a, b, c}</c>.
/// </para>
/// <para>
/// All collection classes that implement <see cref="ICollection"/> its subclasses,
/// or generic equivalents all implement the <see cref="IEnumerable"/> interface.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term><see cref="DictionaryEntry"/></term>
/// <description>
/// <para>
/// Rendered as the key, an equals sign ('='), and the value (using the appropriate
/// renderer).
/// </para>
/// <para>
/// For example: <c>key=value</c>.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>other</term>
/// <description>
/// <para><c>Object.ToString()</c></para>
/// </description>
/// </item>
/// </list>
/// </remarks>
public void RenderObject(object obj, TextWriter writer) {
if (obj == null) {
writer.Write("<null>");
return;
}
Array objArray = obj as Array;
if (objArray != null) {
RenderArray(objArray, writer);
return;
}
// Test if we are dealing with some form of collection object
IEnumerable objEnumerable = obj as IEnumerable;
if (objEnumerable != null) {
// Get a collection interface if we can as its .Count property may be more
// performant than getting the IEnumerator object and trying to advance it.
ICollection objCollection = obj as ICollection;
if (objCollection != null && objCollection.Count == 0) {
writer.Write("{}");
return;
}
// This is a special check to allow us to get the enumerator from the IDictionary
// interface as this guarantees us DictionaryEntry objects. Note that in .NET 2.0
// the generic IDictionary<> interface enumerates KeyValuePair objects rather than
// DictionaryEntry ones. However the implementation of the plain IDictionary
// interface on the generic Dictionary<> still returns DictionaryEntry objects.
IDictionary objDictionary = obj as IDictionary;
if (objDictionary != null) {
RenderEnumerator(objDictionary.GetEnumerator(), writer);
return;
}
RenderEnumerator(objEnumerable.GetEnumerator(), writer);
return;
}
IEnumerator objEnumerator = obj as IEnumerator;
if (objEnumerator != null) {
RenderEnumerator(objEnumerator, writer);
return;
}
if (obj is DictionaryEntry) {
RenderDictionaryEntry((DictionaryEntry)obj, writer);
return;
}
string str = obj.ToString();
writer.Write((str == null) ? "<null>" : str);
}
#endregion
/// <summary>
/// Render the array argument into a string
/// </summary>
/// <param name="array">the array to render</param>
/// <param name="writer">The writer to render to</param>
/// <remarks>
/// <para>
/// For a one dimensional array this is the
/// array type name, an open brace, followed by a comma
/// separated list of the elements (using the appropriate
/// renderer), followed by a close brace. For example:
/// <c>int[] {1, 2, 3}</c>.
/// </para>
/// <para>
/// If the array is not one dimensional the
/// <c>Array.ToString()</c> is returned.
/// </para>
/// </remarks>
private void RenderArray(Array array, TextWriter writer) {
if (array.Rank != 1) {
writer.Write(array.ToString());
} else {
writer.Write(array.GetType().Name + " {");
int len = array.Length;
if (len > 0) {
RendererMap.FindAndRender(array.GetValue(0), writer);
for (int i = 1; i < len; i++) {
writer.Write(", ");
RendererMap.FindAndRender(array.GetValue(i), writer);
}
}
writer.Write("}");
}
}
/// <summary>
/// Render the enumerator argument into a string
/// </summary>
/// <param name="enumerator">the enumerator to render</param>
/// <param name="writer">The writer to render to</param>
/// <remarks>
/// <para>
/// Rendered as an open brace, followed by a comma
/// separated list of the elements (using the appropriate
/// renderer), followed by a close brace. For example:
/// <c>{a, b, c}</c>.
/// </para>
/// </remarks>
private void RenderEnumerator(IEnumerator enumerator, TextWriter writer) {
writer.Write("{");
if (enumerator != null && enumerator.MoveNext()) {
RendererMap.FindAndRender(enumerator.Current, writer);
while (enumerator.MoveNext()) {
writer.Write(", ");
RendererMap.FindAndRender(enumerator.Current, writer);
}
}
writer.Write("}");
}
/// <summary>
/// Render the DictionaryEntry argument into a string
/// </summary>
/// <param name="entry">the DictionaryEntry to render</param>
/// <param name="writer">The writer to render to</param>
/// <remarks>
/// <para>
/// Render the key, an equals sign ('='), and the value (using the appropriate
/// renderer). For example: <c>key=value</c>.
/// </para>
/// </remarks>
private void RenderDictionaryEntry(DictionaryEntry entry, TextWriter writer) {
RendererMap.FindAndRender(entry.Key, writer);
writer.Write("=");
RendererMap.FindAndRender(entry.Value, writer);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
namespace System.Drawing
{
/// <summary>
/// Stores the location and size of a rectangular region.
/// </summary>
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public struct RectangleF : IEquatable<RectangleF>
{
/// <summary>
/// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/> class.
/// </summary>
public static readonly RectangleF Empty = new RectangleF();
private float x; // Do not rename (binary serialization)
private float y; // Do not rename (binary serialization)
private float width; // Do not rename (binary serialization)
private float height; // Do not rename (binary serialization)
/// <summary>
/// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/> class with the specified location
/// and size.
/// </summary>
public RectangleF(float x, float y, float width, float height)
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/// <summary>
/// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/> class with the specified location
/// and size.
/// </summary>
public RectangleF(PointF location, SizeF size)
{
x = location.X;
y = location.Y;
width = size.Width;
height = size.Height;
}
/// <summary>
/// Creates a new <see cref='System.Drawing.RectangleF'/> with the specified location and size.
/// </summary>
public static RectangleF FromLTRB(float left, float top, float right, float bottom) =>
new RectangleF(left, top, right - left, bottom - top);
/// <summary>
/// Gets or sets the coordinates of the upper-left corner of the rectangular region represented by this
/// <see cref='System.Drawing.RectangleF'/>.
/// </summary>
[Browsable(false)]
public PointF Location
{
readonly get => new PointF(X, Y);
set
{
X = value.X;
Y = value.Y;
}
}
/// <summary>
/// Gets or sets the size of this <see cref='System.Drawing.RectangleF'/>.
/// </summary>
[Browsable(false)]
public SizeF Size
{
readonly get => new SizeF(Width, Height);
set
{
Width = value.Width;
Height = value.Height;
}
}
/// <summary>
/// Gets or sets the x-coordinate of the upper-left corner of the rectangular region defined by this
/// <see cref='System.Drawing.RectangleF'/>.
/// </summary>
public float X
{
readonly get => x;
set => x = value;
}
/// <summary>
/// Gets or sets the y-coordinate of the upper-left corner of the rectangular region defined by this
/// <see cref='System.Drawing.RectangleF'/>.
/// </summary>
public float Y
{
readonly get => y;
set => y = value;
}
/// <summary>
/// Gets or sets the width of the rectangular region defined by this <see cref='System.Drawing.RectangleF'/>.
/// </summary>
public float Width
{
readonly get => width;
set => width = value;
}
/// <summary>
/// Gets or sets the height of the rectangular region defined by this <see cref='System.Drawing.RectangleF'/>.
/// </summary>
public float Height
{
readonly get => height;
set => height = value;
}
/// <summary>
/// Gets the x-coordinate of the upper-left corner of the rectangular region defined by this
/// <see cref='System.Drawing.RectangleF'/> .
/// </summary>
[Browsable(false)]
public readonly float Left => X;
/// <summary>
/// Gets the y-coordinate of the upper-left corner of the rectangular region defined by this
/// <see cref='System.Drawing.RectangleF'/>.
/// </summary>
[Browsable(false)]
public readonly float Top => Y;
/// <summary>
/// Gets the x-coordinate of the lower-right corner of the rectangular region defined by this
/// <see cref='System.Drawing.RectangleF'/>.
/// </summary>
[Browsable(false)]
public readonly float Right => X + Width;
/// <summary>
/// Gets the y-coordinate of the lower-right corner of the rectangular region defined by this
/// <see cref='System.Drawing.RectangleF'/>.
/// </summary>
[Browsable(false)]
public readonly float Bottom => Y + Height;
/// <summary>
/// Tests whether this <see cref='System.Drawing.RectangleF'/> has a <see cref='System.Drawing.RectangleF.Width'/> or a <see cref='System.Drawing.RectangleF.Height'/> of 0.
/// </summary>
[Browsable(false)]
public readonly bool IsEmpty => (Width <= 0) || (Height <= 0);
/// <summary>
/// Tests whether <paramref name="obj"/> is a <see cref='System.Drawing.RectangleF'/> with the same location and
/// size of this <see cref='System.Drawing.RectangleF'/>.
/// </summary>
public override readonly bool Equals(object? obj) => obj is RectangleF && Equals((RectangleF)obj);
public readonly bool Equals(RectangleF other) => this == other;
/// <summary>
/// Tests whether two <see cref='System.Drawing.RectangleF'/> objects have equal location and size.
/// </summary>
public static bool operator ==(RectangleF left, RectangleF right) =>
left.X == right.X && left.Y == right.Y && left.Width == right.Width && left.Height == right.Height;
/// <summary>
/// Tests whether two <see cref='System.Drawing.RectangleF'/> objects differ in location or size.
/// </summary>
public static bool operator !=(RectangleF left, RectangleF right) => !(left == right);
/// <summary>
/// Determines if the specified point is contained within the rectangular region defined by this
/// <see cref='System.Drawing.Rectangle'/> .
/// </summary>
public readonly bool Contains(float x, float y) => X <= x && x < X + Width && Y <= y && y < Y + Height;
/// <summary>
/// Determines if the specified point is contained within the rectangular region defined by this
/// <see cref='System.Drawing.Rectangle'/> .
/// </summary>
public readonly bool Contains(PointF pt) => Contains(pt.X, pt.Y);
/// <summary>
/// Determines if the rectangular region represented by <paramref name="rect"/> is entirely contained within
/// the rectangular region represented by this <see cref='System.Drawing.Rectangle'/> .
/// </summary>
public readonly bool Contains(RectangleF rect) =>
(X <= rect.X) && (rect.X + rect.Width <= X + Width) && (Y <= rect.Y) && (rect.Y + rect.Height <= Y + Height);
/// <summary>
/// Gets the hash code for this <see cref='System.Drawing.RectangleF'/>.
/// </summary>
public override readonly int GetHashCode() => HashCode.Combine(X, Y, Width, Height);
/// <summary>
/// Inflates this <see cref='System.Drawing.Rectangle'/> by the specified amount.
/// </summary>
public void Inflate(float x, float y)
{
X -= x;
Y -= y;
Width += 2 * x;
Height += 2 * y;
}
/// <summary>
/// Inflates this <see cref='System.Drawing.Rectangle'/> by the specified amount.
/// </summary>
public void Inflate(SizeF size) => Inflate(size.Width, size.Height);
/// <summary>
/// Creates a <see cref='System.Drawing.Rectangle'/> that is inflated by the specified amount.
/// </summary>
public static RectangleF Inflate(RectangleF rect, float x, float y)
{
RectangleF r = rect;
r.Inflate(x, y);
return r;
}
/// <summary>
/// Creates a Rectangle that represents the intersection between this Rectangle and rect.
/// </summary>
public void Intersect(RectangleF rect)
{
RectangleF result = Intersect(rect, this);
X = result.X;
Y = result.Y;
Width = result.Width;
Height = result.Height;
}
/// <summary>
/// Creates a rectangle that represents the intersection between a and b. If there is no intersection, an
/// empty rectangle is returned.
/// </summary>
public static RectangleF Intersect(RectangleF a, RectangleF b)
{
float x1 = Math.Max(a.X, b.X);
float x2 = Math.Min(a.X + a.Width, b.X + b.Width);
float y1 = Math.Max(a.Y, b.Y);
float y2 = Math.Min(a.Y + a.Height, b.Y + b.Height);
if (x2 >= x1 && y2 >= y1)
{
return new RectangleF(x1, y1, x2 - x1, y2 - y1);
}
return Empty;
}
/// <summary>
/// Determines if this rectangle intersects with rect.
/// </summary>
public bool IntersectsWith(RectangleF rect) =>
(rect.X < X + Width) && (X < rect.X + rect.Width) && (rect.Y < Y + Height) && (Y < rect.Y + rect.Height);
/// <summary>
/// Creates a rectangle that represents the union between a and b.
/// </summary>
public static RectangleF Union(RectangleF a, RectangleF b)
{
float x1 = Math.Min(a.X, b.X);
float x2 = Math.Max(a.X + a.Width, b.X + b.Width);
float y1 = Math.Min(a.Y, b.Y);
float y2 = Math.Max(a.Y + a.Height, b.Y + b.Height);
return new RectangleF(x1, y1, x2 - x1, y2 - y1);
}
/// <summary>
/// Adjusts the location of this rectangle by the specified amount.
/// </summary>
public void Offset(PointF pos) => Offset(pos.X, pos.Y);
/// <summary>
/// Adjusts the location of this rectangle by the specified amount.
/// </summary>
public void Offset(float x, float y)
{
X += x;
Y += y;
}
/// <summary>
/// Converts the specified <see cref='System.Drawing.Rectangle'/> to a
/// <see cref='System.Drawing.RectangleF'/>.
/// </summary>
public static implicit operator RectangleF(Rectangle r) => new RectangleF(r.X, r.Y, r.Width, r.Height);
/// <summary>
/// Converts the <see cref='System.Drawing.RectangleF.Location'/> and <see cref='System.Drawing.RectangleF.Size'/>
/// of this <see cref='System.Drawing.RectangleF'/> to a human-readable string.
/// </summary>
public override readonly string ToString() =>
"{X=" + X.ToString() + ",Y=" + Y.ToString() +
",Width=" + Width.ToString() + ",Height=" + Height.ToString() + "}";
}
}
| |
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 BI.Interface.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;
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Config
{
using System;
using System.Globalization;
using System.Text;
using NLog.Conditions;
using NLog.Config;
using NLog.LayoutRenderers;
using NLog.Layouts;
using NLog.Targets;
using NLog.Targets.Wrappers;
using Xunit;
public class TargetConfigurationTests : NLogTestBase
{
[Fact]
public void SimpleTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d' type='Debug' layout='${message}' />
</targets>
</nlog>");
DebugTarget t = c.FindTargetByName("d") as DebugTarget;
Assert.NotNull(t);
Assert.Equal(t.Name, "d");
SimpleLayout l = t.Layout as SimpleLayout;
Assert.Equal("${message}", l.Text);
Assert.NotNull(t.Layout);
Assert.Equal(1, l.Renderers.Count);
Assert.IsType(typeof(MessageLayoutRenderer), l.Renderers[0]);
}
[Fact]
public void SimpleElementSyntaxTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target type='Debug'>
<name>d</name>
<layout>${message}</layout>
</target>
</targets>
</nlog>");
DebugTarget t = c.FindTargetByName("d") as DebugTarget;
Assert.NotNull(t);
Assert.Equal(t.Name, "d");
SimpleLayout l = t.Layout as SimpleLayout;
Assert.Equal("${message}", l.Text);
Assert.NotNull(t.Layout);
Assert.Equal(1, l.Renderers.Count);
Assert.IsType(typeof(MessageLayoutRenderer), l.Renderers[0]);
}
[Fact]
public void ArrayParameterTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target type='MethodCall' name='mct'>
<parameter name='p1' layout='${message}' />
<parameter name='p2' layout='${level}' />
<parameter name='p3' layout='${logger}' />
</target>
</targets>
</nlog>");
var t = c.FindTargetByName("mct") as MethodCallTarget;
Assert.NotNull(t);
Assert.Equal(3, t.Parameters.Count);
Assert.Equal("p1", t.Parameters[0].Name);
Assert.Equal("'${message}'", t.Parameters[0].Layout.ToString());
Assert.Equal("p2", t.Parameters[1].Name);
Assert.Equal("'${level}'", t.Parameters[1].Layout.ToString());
Assert.Equal("p3", t.Parameters[2].Name);
Assert.Equal("'${logger}'", t.Parameters[2].Layout.ToString());
}
[Fact]
public void ArrayElementParameterTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target type='MethodCall' name='mct'>
<parameter>
<name>p1</name>
<layout>${message}</layout>
</parameter>
<parameter>
<name>p2</name>
<layout type='CsvLayout'>
<column name='x' layout='${message}' />
<column name='y' layout='${level}' />
</layout>
</parameter>
<parameter>
<name>p3</name>
<layout>${logger}</layout>
</parameter>
</target>
</targets>
</nlog>");
var t = c.FindTargetByName("mct") as MethodCallTarget;
Assert.NotNull(t);
Assert.Equal(3, t.Parameters.Count);
Assert.Equal("p1", t.Parameters[0].Name);
Assert.Equal("'${message}'", t.Parameters[0].Layout.ToString());
Assert.Equal("p2", t.Parameters[1].Name);
CsvLayout csvLayout = t.Parameters[1].Layout as CsvLayout;
Assert.NotNull(csvLayout);
Assert.Equal(2, csvLayout.Columns.Count);
Assert.Equal("x", csvLayout.Columns[0].Name);
Assert.Equal("y", csvLayout.Columns[1].Name);
Assert.Equal("p3", t.Parameters[2].Name);
Assert.Equal("'${logger}'", t.Parameters[2].Layout.ToString());
}
[Fact]
public void SimpleTest2()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d' type='Debug' layout='${message} ${level}' />
</targets>
</nlog>");
DebugTarget t = c.FindTargetByName("d") as DebugTarget;
Assert.NotNull(t);
Assert.Equal(t.Name, "d");
SimpleLayout l = t.Layout as SimpleLayout;
Assert.Equal("${message} ${level}", l.Text);
Assert.NotNull(l);
Assert.Equal(3, l.Renderers.Count);
Assert.IsType(typeof(MessageLayoutRenderer), l.Renderers[0]);
Assert.IsType(typeof(LiteralLayoutRenderer), l.Renderers[1]);
Assert.IsType(typeof(LevelLayoutRenderer), l.Renderers[2]);
Assert.Equal(" ", ((LiteralLayoutRenderer)l.Renderers[1]).Text);
}
[Fact]
public void WrapperTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<wrapper-target name='b' type='BufferingWrapper' bufferSize='19'>
<wrapper name='a' type='AsyncWrapper'>
<target name='c' type='Debug' layout='${message}' />
</wrapper>
</wrapper-target>
</targets>
</nlog>");
Assert.NotNull(c.FindTargetByName("a"));
Assert.NotNull(c.FindTargetByName("b"));
Assert.NotNull(c.FindTargetByName("c"));
Assert.IsType(typeof(BufferingTargetWrapper), c.FindTargetByName("b"));
Assert.IsType(typeof(AsyncTargetWrapper), c.FindTargetByName("a"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("c"));
BufferingTargetWrapper btw = c.FindTargetByName("b") as BufferingTargetWrapper;
AsyncTargetWrapper atw = c.FindTargetByName("a") as AsyncTargetWrapper;
DebugTarget dt = c.FindTargetByName("c") as DebugTarget;
Assert.Same(atw, btw.WrappedTarget);
Assert.Same(dt, atw.WrappedTarget);
Assert.Equal(19, btw.BufferSize);
}
[Fact]
public void WrapperRefTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='c' type='Debug' layout='${message}' />
<wrapper name='a' type='AsyncWrapper'>
<target-ref name='c' />
</wrapper>
<wrapper-target name='b' type='BufferingWrapper' bufferSize='19'>
<wrapper-target-ref name='a' />
</wrapper-target>
</targets>
</nlog>");
Assert.NotNull(c.FindTargetByName("a"));
Assert.NotNull(c.FindTargetByName("b"));
Assert.NotNull(c.FindTargetByName("c"));
Assert.IsType(typeof(BufferingTargetWrapper), c.FindTargetByName("b"));
Assert.IsType(typeof(AsyncTargetWrapper), c.FindTargetByName("a"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("c"));
BufferingTargetWrapper btw = c.FindTargetByName("b") as BufferingTargetWrapper;
AsyncTargetWrapper atw = c.FindTargetByName("a") as AsyncTargetWrapper;
DebugTarget dt = c.FindTargetByName("c") as DebugTarget;
Assert.Same(atw, btw.WrappedTarget);
Assert.Same(dt, atw.WrappedTarget);
Assert.Equal(19, btw.BufferSize);
}
[Fact]
public void CompoundTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<compound-target name='rr' type='RoundRobinGroup'>
<target name='d1' type='Debug' layout='${message}1' />
<target name='d2' type='Debug' layout='${message}2' />
<target name='d3' type='Debug' layout='${message}3' />
<target name='d4' type='Debug' layout='${message}4' />
</compound-target>
</targets>
</nlog>");
Assert.NotNull(c.FindTargetByName("rr"));
Assert.NotNull(c.FindTargetByName("d1"));
Assert.NotNull(c.FindTargetByName("d2"));
Assert.NotNull(c.FindTargetByName("d3"));
Assert.NotNull(c.FindTargetByName("d4"));
Assert.IsType(typeof(RoundRobinGroupTarget), c.FindTargetByName("rr"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d1"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d2"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d3"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d4"));
RoundRobinGroupTarget rr = c.FindTargetByName("rr") as RoundRobinGroupTarget;
DebugTarget d1 = c.FindTargetByName("d1") as DebugTarget;
DebugTarget d2 = c.FindTargetByName("d2") as DebugTarget;
DebugTarget d3 = c.FindTargetByName("d3") as DebugTarget;
DebugTarget d4 = c.FindTargetByName("d4") as DebugTarget;
Assert.Equal(4, rr.Targets.Count);
Assert.Same(d1, rr.Targets[0]);
Assert.Same(d2, rr.Targets[1]);
Assert.Same(d3, rr.Targets[2]);
Assert.Same(d4, rr.Targets[3]);
Assert.Equal(((SimpleLayout)d1.Layout).Text, "${message}1");
Assert.Equal(((SimpleLayout)d2.Layout).Text, "${message}2");
Assert.Equal(((SimpleLayout)d3.Layout).Text, "${message}3");
Assert.Equal(((SimpleLayout)d4.Layout).Text, "${message}4");
}
[Fact]
public void CompoundRefTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}1' />
<target name='d2' type='Debug' layout='${message}2' />
<target name='d3' type='Debug' layout='${message}3' />
<target name='d4' type='Debug' layout='${message}4' />
<compound-target name='rr' type='RoundRobinGroup'>
<target-ref name='d1' />
<target-ref name='d2' />
<target-ref name='d3' />
<target-ref name='d4' />
</compound-target>
</targets>
</nlog>");
Assert.NotNull(c.FindTargetByName("rr"));
Assert.NotNull(c.FindTargetByName("d1"));
Assert.NotNull(c.FindTargetByName("d2"));
Assert.NotNull(c.FindTargetByName("d3"));
Assert.NotNull(c.FindTargetByName("d4"));
Assert.IsType(typeof(RoundRobinGroupTarget), c.FindTargetByName("rr"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d1"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d2"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d3"));
Assert.IsType(typeof(DebugTarget), c.FindTargetByName("d4"));
RoundRobinGroupTarget rr = c.FindTargetByName("rr") as RoundRobinGroupTarget;
DebugTarget d1 = c.FindTargetByName("d1") as DebugTarget;
DebugTarget d2 = c.FindTargetByName("d2") as DebugTarget;
DebugTarget d3 = c.FindTargetByName("d3") as DebugTarget;
DebugTarget d4 = c.FindTargetByName("d4") as DebugTarget;
Assert.Equal(4, rr.Targets.Count);
Assert.Same(d1, rr.Targets[0]);
Assert.Same(d2, rr.Targets[1]);
Assert.Same(d3, rr.Targets[2]);
Assert.Same(d4, rr.Targets[3]);
Assert.Equal(((SimpleLayout)d1.Layout).Text, "${message}1");
Assert.Equal(((SimpleLayout)d2.Layout).Text, "${message}2");
Assert.Equal(((SimpleLayout)d3.Layout).Text, "${message}3");
Assert.Equal(((SimpleLayout)d4.Layout).Text, "${message}4");
}
[Fact]
public void AsyncWrappersTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets async='true'>
<target type='Debug' name='d' />
<target type='Debug' name='d2' />
</targets>
</nlog>");
var t = c.FindTargetByName("d") as AsyncTargetWrapper;
Assert.NotNull(t);
Assert.Equal(t.Name, "d");
var wrappedTarget = t.WrappedTarget as DebugTarget;
Assert.NotNull(wrappedTarget);
Assert.Equal("d_wrapped", wrappedTarget.Name);
t = c.FindTargetByName("d2") as AsyncTargetWrapper;
Assert.NotNull(t);
Assert.Equal(t.Name, "d2");
wrappedTarget = t.WrappedTarget as DebugTarget;
Assert.NotNull(wrappedTarget);
Assert.Equal("d2_wrapped", wrappedTarget.Name);
}
[Fact]
public void DefaultTargetParametersTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<default-target-parameters type='Debug' layout='x${message}x' />
<target type='Debug' name='d' />
<target type='Debug' name='d2' />
</targets>
</nlog>");
var t = c.FindTargetByName("d") as DebugTarget;
Assert.NotNull(t);
Assert.Equal("'x${message}x'", t.Layout.ToString());
t = c.FindTargetByName("d2") as DebugTarget;
Assert.NotNull(t);
Assert.Equal("'x${message}x'", t.Layout.ToString());
}
[Fact]
public void DefaultWrapperTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<targets>
<default-wrapper type='BufferingWrapper'>
<wrapper type='RetryingWrapper' />
</default-wrapper>
<target type='Debug' name='d' layout='${level}' />
<target type='Debug' name='d2' layout='${level}' />
</targets>
</nlog>");
var bufferingTargetWrapper = c.FindTargetByName("d") as BufferingTargetWrapper;
Assert.NotNull(bufferingTargetWrapper);
var retryingTargetWrapper = bufferingTargetWrapper.WrappedTarget as RetryingTargetWrapper;
Assert.NotNull(retryingTargetWrapper);
Assert.Null(retryingTargetWrapper.Name);
var debugTarget = retryingTargetWrapper.WrappedTarget as DebugTarget;
Assert.NotNull(debugTarget);
Assert.Equal("d_wrapped", debugTarget.Name);
Assert.Equal("'${level}'", debugTarget.Layout.ToString());
}
[Fact]
public void DataTypesTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<extensions>
<add type='" + typeof(MyTarget).AssemblyQualifiedName + @"' />
</extensions>
<targets>
<target type='MyTarget' name='myTarget'
byteProperty='42'
int16Property='42'
int32Property='42'
int64Property='42000000000'
stringProperty='foobar'
boolProperty='true'
doubleProperty='3.14159'
floatProperty='3.14159'
enumProperty='Value3'
flagsEnumProperty='Value1,Value3'
encodingProperty='utf-8'
cultureProperty='en-US'
typeProperty='System.Int32'
layoutProperty='${level}'
conditionProperty=""starts-with(message, 'x')""
uriProperty='http://nlog-project.org'
lineEndingModeProperty='default'
/>
</targets>
</nlog>");
var myTarget = c.FindTargetByName("myTarget") as MyTarget;
Assert.NotNull(myTarget);
Assert.Equal((byte)42, myTarget.ByteProperty);
Assert.Equal((short)42, myTarget.Int16Property);
Assert.Equal(42, myTarget.Int32Property);
Assert.Equal(42000000000L, myTarget.Int64Property);
Assert.Equal("foobar", myTarget.StringProperty);
Assert.Equal(true, myTarget.BoolProperty);
Assert.Equal(3.14159, myTarget.DoubleProperty);
Assert.Equal(3.14159f, myTarget.FloatProperty);
Assert.Equal(MyEnum.Value3, myTarget.EnumProperty);
Assert.Equal(MyFlagsEnum.Value1 | MyFlagsEnum.Value3, myTarget.FlagsEnumProperty);
Assert.Equal(Encoding.UTF8, myTarget.EncodingProperty);
Assert.Equal("en-US", myTarget.CultureProperty.Name);
Assert.Equal(typeof(int), myTarget.TypeProperty);
Assert.Equal("'${level}'", myTarget.LayoutProperty.ToString());
Assert.Equal("starts-with(message, 'x')", myTarget.ConditionProperty.ToString());
Assert.Equal(new Uri("http://nlog-project.org"), myTarget.UriProperty);
Assert.Equal(LineEndingMode.Default, myTarget.LineEndingModeProperty);
}
[Fact]
public void NullableDataTypesTest()
{
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog>
<extensions>
<add type='" + typeof(MyNullableTarget).AssemblyQualifiedName + @"' />
</extensions>
<targets>
<target type='MyNullableTarget' name='myTarget'
byteProperty='42'
int16Property='42'
int32Property='42'
int64Property='42000000000'
stringProperty='foobar'
boolProperty='true'
doubleProperty='3.14159'
floatProperty='3.14159'
enumProperty='Value3'
flagsEnumProperty='Value1,Value3'
encodingProperty='utf-8'
cultureProperty='en-US'
typeProperty='System.Int32'
layoutProperty='${level}'
conditionProperty=""starts-with(message, 'x')""
/>
</targets>
</nlog>");
var myTarget = c.FindTargetByName("myTarget") as MyNullableTarget;
Assert.NotNull(myTarget);
Assert.Equal((byte)42, myTarget.ByteProperty);
Assert.Equal((short)42, myTarget.Int16Property);
Assert.Equal(42, myTarget.Int32Property);
Assert.Equal(42000000000L, myTarget.Int64Property);
Assert.Equal("foobar", myTarget.StringProperty);
Assert.Equal(true, myTarget.BoolProperty);
Assert.Equal(3.14159, myTarget.DoubleProperty);
Assert.Equal(3.14159f, myTarget.FloatProperty);
Assert.Equal(MyEnum.Value3, myTarget.EnumProperty);
Assert.Equal(MyFlagsEnum.Value1 | MyFlagsEnum.Value3, myTarget.FlagsEnumProperty);
Assert.Equal(Encoding.UTF8, myTarget.EncodingProperty);
Assert.Equal("en-US", myTarget.CultureProperty.Name);
Assert.Equal(typeof(int), myTarget.TypeProperty);
Assert.Equal("'${level}'", myTarget.LayoutProperty.ToString());
Assert.Equal("starts-with(message, 'x')", myTarget.ConditionProperty.ToString());
}
[Target("MyTarget")]
public class MyTarget : Target
{
public byte ByteProperty { get; set; }
public short Int16Property { get; set; }
public int Int32Property { get; set; }
public long Int64Property { get; set; }
public string StringProperty { get; set; }
public bool BoolProperty { get; set; }
public double DoubleProperty { get; set; }
public float FloatProperty { get; set; }
public MyEnum EnumProperty { get; set; }
public MyFlagsEnum FlagsEnumProperty { get; set; }
public Encoding EncodingProperty { get; set; }
public CultureInfo CultureProperty { get; set; }
public Type TypeProperty { get; set; }
public Layout LayoutProperty { get; set; }
public ConditionExpression ConditionProperty { get; set; }
public Uri UriProperty { get; set; }
public LineEndingMode LineEndingModeProperty { get; set; }
}
[Target("MyNullableTarget")]
public class MyNullableTarget : Target
{
public byte? ByteProperty { get; set; }
public short? Int16Property { get; set; }
public int? Int32Property { get; set; }
public long? Int64Property { get; set; }
public string StringProperty { get; set; }
public bool? BoolProperty { get; set; }
public double? DoubleProperty { get; set; }
public float? FloatProperty { get; set; }
public MyEnum? EnumProperty { get; set; }
public MyFlagsEnum? FlagsEnumProperty { get; set; }
public Encoding EncodingProperty { get; set; }
public CultureInfo CultureProperty { get; set; }
public Type TypeProperty { get; set; }
public Layout LayoutProperty { get; set; }
public ConditionExpression ConditionProperty { get; set; }
}
public enum MyEnum
{
Value1,
Value2,
Value3,
}
[Flags]
public enum MyFlagsEnum
{
Value1 = 1,
Value2 = 2,
Value3 = 4,
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Cache;
using System.Net.Security;
using System.Runtime.Serialization;
using System.Security.Principal;
using System.Threading.Tasks;
namespace System.Net
{
[Serializable]
public abstract class WebRequest : MarshalByRefObject, ISerializable
{
internal class WebRequestPrefixElement
{
public readonly string Prefix;
public readonly IWebRequestCreate Creator;
public WebRequestPrefixElement(string prefix, IWebRequestCreate creator)
{
Prefix = prefix;
Creator = creator;
}
}
private static volatile List<WebRequestPrefixElement> s_prefixList;
private static readonly object s_internalSyncObject = new object();
internal const int DefaultTimeoutMilliseconds = 100 * 1000;
protected WebRequest() { }
protected WebRequest(SerializationInfo serializationInfo, StreamingContext streamingContext) { }
void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
GetObjectData(serializationInfo, streamingContext);
}
protected virtual void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) { }
// Create a WebRequest.
//
// This is the main creation routine. We take a Uri object, look
// up the Uri in the prefix match table, and invoke the appropriate
// handler to create the object. We also have a parameter that
// tells us whether or not to use the whole Uri or just the
// scheme portion of it.
//
// Input:
// requestUri - Uri object for request.
// useUriBase - True if we're only to look at the scheme portion of the Uri.
//
// Returns:
// Newly created WebRequest.
private static WebRequest Create(Uri requestUri, bool useUriBase)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, requestUri);
string LookupUri;
WebRequestPrefixElement Current = null;
bool Found = false;
if (!useUriBase)
{
LookupUri = requestUri.AbsoluteUri;
}
else
{
// schemes are registered as <schemeName>":", so add the separator
// to the string returned from the Uri object
LookupUri = requestUri.Scheme + ':';
}
int LookupLength = LookupUri.Length;
// Copy the prefix list so that if it is updated it will
// not affect us on this thread.
List<WebRequestPrefixElement> prefixList = PrefixList;
// Look for the longest matching prefix.
// Walk down the list of prefixes. The prefixes are kept longest
// first. When we find a prefix that is shorter or the same size
// as this Uri, we'll do a compare to see if they match. If they
// do we'll break out of the loop and call the creator.
for (int i = 0; i < prefixList.Count; i++)
{
Current = prefixList[i];
// See if this prefix is short enough.
if (LookupLength >= Current.Prefix.Length)
{
// It is. See if these match.
if (String.Compare(Current.Prefix,
0,
LookupUri,
0,
Current.Prefix.Length,
StringComparison.OrdinalIgnoreCase) == 0)
{
// These match. Remember that we found it and break
// out.
Found = true;
break;
}
}
}
WebRequest webRequest = null;
if (Found)
{
// We found a match, so just call the creator and return what it does.
webRequest = Current.Creator.Create(requestUri);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, webRequest);
return webRequest;
}
// Otherwise no match, throw an exception.
if (NetEventSource.IsEnabled) NetEventSource.Exit(null);
throw new NotSupportedException(SR.net_unknown_prefix);
}
// Create - Create a WebRequest.
//
// An overloaded utility version of the real Create that takes a
// string instead of an Uri object.
//
// Input:
// RequestString - Uri string to create.
//
// Returns:
// Newly created WebRequest.
public static WebRequest Create(string requestUriString)
{
if (requestUriString == null)
{
throw new ArgumentNullException(nameof(requestUriString));
}
return Create(new Uri(requestUriString), false);
}
// Create - Create a WebRequest.
//
// Another overloaded version of the Create function that doesn't
// take the UseUriBase parameter.
//
// Input:
// requestUri - Uri object for request.
//
// Returns:
// Newly created WebRequest.
public static WebRequest Create(Uri requestUri)
{
if (requestUri == null)
{
throw new ArgumentNullException(nameof(requestUri));
}
return Create(requestUri, false);
}
// CreateDefault - Create a default WebRequest.
//
// This is the creation routine that creates a default WebRequest.
// We take a Uri object and pass it to the base create routine,
// setting the useUriBase parameter to true.
//
// Input:
// RequestUri - Uri object for request.
//
// Returns:
// Newly created WebRequest.
public static WebRequest CreateDefault(Uri requestUri)
{
if (requestUri == null)
{
throw new ArgumentNullException(nameof(requestUri));
}
return Create(requestUri, true);
}
public static HttpWebRequest CreateHttp(string requestUriString)
{
if (requestUriString == null)
{
throw new ArgumentNullException(nameof(requestUriString));
}
return CreateHttp(new Uri(requestUriString));
}
public static HttpWebRequest CreateHttp(Uri requestUri)
{
if (requestUri == null)
{
throw new ArgumentNullException(nameof(requestUri));
}
if ((requestUri.Scheme != "http") && (requestUri.Scheme != "https"))
{
throw new NotSupportedException(SR.net_unknown_prefix);
}
return (HttpWebRequest)CreateDefault(requestUri);
}
// RegisterPrefix - Register an Uri prefix for creating WebRequests.
//
// This function registers a prefix for creating WebRequests. When an
// user wants to create a WebRequest, we scan a table looking for a
// longest prefix match for the Uri they're passing. We then invoke
// the sub creator for that prefix. This function puts entries in
// that table.
//
// We don't allow duplicate entries, so if there is a dup this call
// will fail.
//
// Input:
// Prefix - Represents Uri prefix being registered.
// Creator - Interface for sub creator.
//
// Returns:
// True if the registration worked, false otherwise.
public static bool RegisterPrefix(string prefix, IWebRequestCreate creator)
{
bool Error = false;
int i;
WebRequestPrefixElement Current;
if (prefix == null)
{
throw new ArgumentNullException(nameof(prefix));
}
if (creator == null)
{
throw new ArgumentNullException(nameof(creator));
}
// Lock this object, then walk down PrefixList looking for a place to
// to insert this prefix.
lock (s_internalSyncObject)
{
// Clone the object and update the clone, thus
// allowing other threads to still read from the original.
List<WebRequestPrefixElement> prefixList = new List<WebRequestPrefixElement>(PrefixList);
// As AbsoluteUri is used later for Create, account for formating changes
// like Unicode escaping, default ports, etc.
Uri tempUri;
if (Uri.TryCreate(prefix, UriKind.Absolute, out tempUri))
{
String cookedUri = tempUri.AbsoluteUri;
// Special case for when a partial host matching is requested, drop the added trailing slash
// IE: http://host could match host or host.domain
if (!prefix.EndsWith("/", StringComparison.Ordinal)
&& tempUri.GetComponents(UriComponents.PathAndQuery | UriComponents.Fragment, UriFormat.UriEscaped)
.Equals("/"))
{
cookedUri = cookedUri.Substring(0, cookedUri.Length - 1);
}
prefix = cookedUri;
}
i = 0;
// The prefix list is sorted with longest entries at the front. We
// walk down the list until we find a prefix shorter than this
// one, then we insert in front of it. Along the way we check
// equal length prefixes to make sure this isn't a dupe.
while (i < prefixList.Count)
{
Current = prefixList[i];
// See if the new one is longer than the one we're looking at.
if (prefix.Length > Current.Prefix.Length)
{
// It is. Break out of the loop here.
break;
}
// If these are of equal length, compare them.
if (prefix.Length == Current.Prefix.Length)
{
// They're the same length.
if (string.Equals(Current.Prefix, prefix, StringComparison.OrdinalIgnoreCase))
{
// ...and the strings are identical. This is an error.
Error = true;
break;
}
}
i++;
}
// When we get here either i contains the index to insert at or
// we've had an error, in which case Error is true.
if (!Error)
{
// No error, so insert.
prefixList.Insert(i, new WebRequestPrefixElement(prefix, creator));
// Assign the clone to the static object. Other threads using it
// will have copied the original object already.
PrefixList = prefixList;
}
}
return !Error;
}
internal class HttpRequestCreator : IWebRequestCreate
{
// Create - Create an HttpWebRequest.
//
// This is our method to create an HttpWebRequest. We register
// for HTTP and HTTPS Uris, and this method is called when a request
// needs to be created for one of those.
//
//
// Input:
// uri - Uri for request being created.
//
// Returns:
// The newly created HttpWebRequest.
public WebRequest Create(Uri Uri)
{
return new HttpWebRequest(Uri);
}
}
// PrefixList - Returns And Initialize our prefix list.
//
//
// This is the method that initializes the prefix list. We create
// an List for the PrefixList, then each of the request creators,
// and then we register them with the associated prefixes.
//
// Returns:
// true
internal static List<WebRequestPrefixElement> PrefixList
{
get
{
// GetConfig() might use us, so we have a circular dependency issue
// that causes us to nest here. We grab the lock only if we haven't
// initialized.
if (s_prefixList == null)
{
lock (s_internalSyncObject)
{
if (s_prefixList == null)
{
var httpRequestCreator = new HttpRequestCreator();
var ftpRequestCreator = new FtpWebRequestCreator();
var fileRequestCreator = new FileWebRequestCreator();
const int Count = 4;
var prefixList = new List<WebRequestPrefixElement>(Count)
{
new WebRequestPrefixElement("http:", httpRequestCreator),
new WebRequestPrefixElement("https:", httpRequestCreator),
new WebRequestPrefixElement("ftp:", ftpRequestCreator),
new WebRequestPrefixElement("file:", fileRequestCreator),
};
Debug.Assert(prefixList.Count == Count, $"Expected {Count}, got {prefixList.Count}");
s_prefixList = prefixList;
}
}
}
return s_prefixList;
}
set
{
s_prefixList = value;
}
}
public static RequestCachePolicy DefaultCachePolicy { get; set; } = new RequestCachePolicy(RequestCacheLevel.BypassCache);
public virtual RequestCachePolicy CachePolicy { get; set; }
public AuthenticationLevel AuthenticationLevel { get; set; } = AuthenticationLevel.MutualAuthRequested;
public TokenImpersonationLevel ImpersonationLevel { get; set; } = TokenImpersonationLevel.Delegation;
public virtual string ConnectionGroupName
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual string Method
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual Uri RequestUri
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual WebHeaderCollection Headers
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual long ContentLength
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual string ContentType
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual ICredentials Credentials
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual int Timeout
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual bool UseDefaultCredentials
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual Stream GetRequestStream()
{
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
public virtual WebResponse GetResponse()
{
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
public virtual IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
{
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
public virtual WebResponse EndGetResponse(IAsyncResult asyncResult)
{
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
public virtual IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
{
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
public virtual Stream EndGetRequestStream(IAsyncResult asyncResult)
{
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
public virtual Task<Stream> GetRequestStreamAsync()
{
// Offload to a different thread to avoid blocking the caller during request submission.
// We use Task.Run rather than Task.Factory.StartNew even though StartNew would let us pass 'this'
// as a state argument to avoid the closure to capture 'this' and the associated delegate.
// This is because the task needs to call FromAsync and marshal the inner Task out, and
// Task.Run's implementation of this is sufficiently more efficient than what we can do with
// Unwrap() that it's worth it to just rely on Task.Run and accept the closure/delegate.
return Task.Run(() =>
Task<Stream>.Factory.FromAsync(
(callback, state) => ((WebRequest)state).BeginGetRequestStream(callback, state),
iar => ((WebRequest)iar.AsyncState).EndGetRequestStream(iar),
this));
}
public virtual Task<WebResponse> GetResponseAsync()
{
// See comment in GetRequestStreamAsync(). Same logic applies here.
return Task.Run(() =>
Task<WebResponse>.Factory.FromAsync(
(callback, state) => ((WebRequest)state).BeginGetResponse(callback, state),
iar => ((WebRequest)iar.AsyncState).EndGetResponse(iar),
this));
}
public virtual void Abort()
{
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
// Default Web Proxy implementation.
private static IWebProxy s_DefaultWebProxy;
private static bool s_DefaultWebProxyInitialized;
public static IWebProxy GetSystemWebProxy() => SystemWebProxy.Get();
public static IWebProxy DefaultWebProxy
{
get
{
lock (s_internalSyncObject)
{
if (!s_DefaultWebProxyInitialized)
{
s_DefaultWebProxy = SystemWebProxy.Get();
s_DefaultWebProxyInitialized = true;
}
return s_DefaultWebProxy;
}
}
set
{
lock (s_internalSyncObject)
{
s_DefaultWebProxy = value;
s_DefaultWebProxyInitialized = true;
}
}
}
public virtual bool PreAuthenticate
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual IWebProxy Proxy
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Routing;
using Nop.Core;
using Nop.Core.Domain.Directory;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Payments;
using Nop.Core.Domain.Shipping;
using Nop.Core.Plugins;
using Nop.Plugin.Payments.GoCoin.Controllers;
using Nop.Services.Configuration;
using Nop.Services.Directory;
using Nop.Services.Localization;
using Nop.Services.Orders;
using Nop.Services.Payments;
using Nop.Services.Tax;
using GoCoinAPI;
namespace Nop.Plugin.Payments.GoCoin
{
/// <summary>
/// GoCoin payment processor
/// </summary>
public class GoCoinPaymentProcessor : BasePlugin, IPaymentMethod
{
#region Fields
private readonly GoCoinPaymentSettings _GoCoinPaymentSettings;
private readonly ISettingService _settingService;
private readonly ICurrencyService _currencyService;
private readonly CurrencySettings _currencySettings;
private readonly IWebHelper _webHelper;
private readonly ICheckoutAttributeParser _checkoutAttributeParser;
private readonly ITaxService _taxService;
private readonly IOrderTotalCalculationService _orderTotalCalculationService;
private readonly HttpContextBase _httpContext;
#endregion
#region Ctor
public GoCoinPaymentProcessor(GoCoinPaymentSettings GoCoinPaymentSettings,
ISettingService settingService, ICurrencyService currencyService,
CurrencySettings currencySettings, IWebHelper webHelper,
ICheckoutAttributeParser checkoutAttributeParser, ITaxService taxService,
IOrderTotalCalculationService orderTotalCalculationService, HttpContextBase httpContext)
{
this._GoCoinPaymentSettings = GoCoinPaymentSettings;
this._settingService = settingService;
this._currencyService = currencyService;
this._currencySettings = currencySettings;
this._webHelper = webHelper;
this._checkoutAttributeParser = checkoutAttributeParser;
this._taxService = taxService;
this._orderTotalCalculationService = orderTotalCalculationService;
this._httpContext = httpContext;
}
#endregion
#region Utilities
/// <summary>
/// Verifies IPN
/// </summary>
/// <param name="formString">Form string</param>
/// <param name="values">Values</param>
/// <returns>Result</returns>
public bool VerifyIPN(string formString, out Dictionary<string, string> values)
{
bool success = true;
values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (string l in formString.Split('&'))
{
string line = l.Trim();
int equalPox = line.IndexOf('=');
if (equalPox >= 0)
values.Add(line.Substring(0, equalPox), line.Substring(equalPox + 1));
}
return success;
}
#endregion
#region Methods
/// <summary>
/// Process a payment
/// </summary>
/// <param name="processPaymentRequest">Payment info required for an order processing</param>
/// <returns>Process payment result</returns>
public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
{
var result = new ProcessPaymentResult();
result.NewPaymentStatus = PaymentStatus.Pending;
return result;
}
/// <summary>
/// Post process payment (used by payment gateways that require redirecting to a third-party URL)
/// </summary>
/// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
{
Client client = new Client(_GoCoinPaymentSettings.APIKey);
string callback_url;
callback_url = _webHelper.GetStoreLocation(false) + "Plugins/PaymentGoCoin/IPNHandler";
var invoice1 = new Invoices
{
type="bill",
customer_name = postProcessPaymentRequest.Order.BillingAddress.FirstName + ' ' + postProcessPaymentRequest.Order.BillingAddress.LastName,
customer_address_1 = postProcessPaymentRequest.Order.BillingAddress.Address1,
customer_address_2 = postProcessPaymentRequest.Order.BillingAddress.Address2,
customer_city = postProcessPaymentRequest.Order.BillingAddress.City,
customer_country = postProcessPaymentRequest.Order.BillingAddress.Country != null ? postProcessPaymentRequest.Order.BillingAddress.Country.TwoLetterIsoCode : "",
customer_email = postProcessPaymentRequest.Order.BillingAddress.Email,
customer_postal_code = postProcessPaymentRequest.Order.BillingAddress.ZipPostalCode,
customer_phone = postProcessPaymentRequest.Order.BillingAddress.PhoneNumber,
//price_currency = "BTC",
order_id = postProcessPaymentRequest.Order.Id.ToString(),
base_price = (float)Math.Round(postProcessPaymentRequest.Order.OrderTotal, 2),
base_price_currency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode,
confirmations_required = 6,
notification_level = "all",
callback_url = callback_url,
redirect_url = _webHelper.GetStoreLocation(false) + "checkout/completed/",
user_defined_7 = _webHelper.GetCurrentIpAddress(),
user_defined_8 = postProcessPaymentRequest.Order.OrderGuid.ToString(),
};
GoCoinAPI.Invoices inv = client.api.invoices.create(_GoCoinPaymentSettings.MerchantID, invoice1);
_httpContext.Response.Redirect("https://gateway.gocoin.com/invoices/" + inv.id);
}
/// <summary>
/// Gets additional handling fee
/// </summary>
/// <param name="cart">Shoping cart</param>
/// <returns>Additional handling fee</returns>
public decimal GetAdditionalHandlingFee(IList<ShoppingCartItem> cart)
{
//var result = this.CalculateAdditionalFee(_orderTotalCalculationService, cart,
// _GoCoinPaymentSettings.AdditionalFee, _GoCoinPaymentSettings.AdditionalFeePercentage);
return 0;
}
/// <summary>
/// Captures payment
/// </summary>
/// <param name="capturePaymentRequest">Capture payment request</param>
/// <returns>Capture payment result</returns>
public CapturePaymentResult Capture(CapturePaymentRequest capturePaymentRequest)
{
var result = new CapturePaymentResult();
result.AddError("Capture method not supported");
return result;
}
/// <summary>
/// Refunds a payment
/// </summary>
/// <param name="refundPaymentRequest">Request</param>
/// <returns>Result</returns>
public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest)
{
var result = new RefundPaymentResult();
result.AddError("Refund method not supported");
return result;
}
/// <summary>
/// Voids a payment
/// </summary>
/// <param name="voidPaymentRequest">Request</param>
/// <returns>Result</returns>
public VoidPaymentResult Void(VoidPaymentRequest voidPaymentRequest)
{
var result = new VoidPaymentResult();
result.AddError("Void method not supported");
return result;
}
/// <summary>
/// Process recurring payment
/// </summary>
/// <param name="processPaymentRequest">Payment info required for an order processing</param>
/// <returns>Process payment result</returns>
public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
{
var result = new ProcessPaymentResult();
result.AddError("Recurring payment not supported");
return result;
}
/// <summary>
/// Cancels a recurring payment
/// </summary>
/// <param name="cancelPaymentRequest">Request</param>
/// <returns>Result</returns>
public CancelRecurringPaymentResult CancelRecurringPayment(CancelRecurringPaymentRequest cancelPaymentRequest)
{
var result = new CancelRecurringPaymentResult();
result.AddError("Recurring payment not supported");
return result;
}
/// <summary>
/// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for redirection payment methods)
/// </summary>
/// <param name="order">Order</param>
/// <returns>Result</returns>
public bool CanRePostProcessPayment(Order order)
{
if (order == null)
throw new ArgumentNullException("order");
//let's ensure that at least 5 seconds passed after order is placed
//P.S. there's no any particular reason for that. we just do it
if ((DateTime.UtcNow - order.CreatedOnUtc).TotalSeconds < 5)
return false;
return true;
}
/// <summary>
/// Gets a route for provider configuration
/// </summary>
/// <param name="actionName">Action name</param>
/// <param name="controllerName">Controller name</param>
/// <param name="routeValues">Route values</param>
public void GetConfigurationRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues)
{
actionName = "Configure";
controllerName = "PaymentGoCoin";
routeValues = new RouteValueDictionary() { { "Namespaces", "Nop.Plugin.Payments.GoCoin.Controllers" }, { "area", null } };
}
/// <summary>
/// Gets a route for payment info
/// </summary>
/// <param name="actionName">Action name</param>
/// <param name="controllerName">Controller name</param>
/// <param name="routeValues">Route values</param>
public void GetPaymentInfoRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues)
{
actionName = "PaymentInfo";
controllerName = "PaymentGoCoin";
routeValues = new RouteValueDictionary() { { "Namespaces", "Nop.Plugin.Payments.GoCoin.Controllers" }, { "area", null } };
}
public Type GetControllerType()
{
return typeof(PaymentGoCoinController);
}
public override void Install()
{
//settings
var settings = new GoCoinPaymentSettings()
{
MerchantID = "",
APIKey = "",
DescriptionText = "Once you confirm the order you will be taken to the GoCoin gateway. Where You can select the virtual currency and proceed to checkout..",
};
_settingService.SaveSetting(settings);
//locales
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.GoCoin.DescriptionText", "Description");
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.GoCoin.DescriptionText.Hint", "Enter info that will be shown to customers during checkout");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.GoCoin.Notes", "If you're using this gateway, ensure that your primary store currency is supported by GoCoin");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.GoCoin.Fields.MerchantID", "Merchant ID");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.GoCoin.Fields.MerchantID.Hint", "Specify MerchantID");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.GoCoin.Fields.APIKey", "API Key");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.GoCoin.Fields.APIKey.Hint", "Specify API key");
base.Install();
}
public override void Uninstall()
{
//settings
_settingService.DeleteSetting<GoCoinPaymentSettings>();
//locales
this.DeletePluginLocaleResource("Plugins.Payment.GoCoin.DescriptionText");
this.DeletePluginLocaleResource("Plugins.Payment.GoCoin.DescriptionText.Hint");
this.DeletePluginLocaleResource("Plugins.Payments.GoCoin.Notes");
this.DeletePluginLocaleResource("Plugins.Payments.GoCoin.Fields.MerchantID");
this.DeletePluginLocaleResource("Plugins.Payments.GoCoin.Fields.MerchantID.Hint");
this.DeletePluginLocaleResource("Plugins.Payments.GoCoin.Fields.APIKey");
this.DeletePluginLocaleResource("Plugins.Payments.GoCoin.Fields.APIKey.Hint");
base.Uninstall();
}
#endregion
#region Properies
/// <summary>
/// Gets a value indicating whether capture is supported
/// </summary>
public bool SupportCapture
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether partial refund is supported
/// </summary>
public bool SupportPartiallyRefund
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether refund is supported
/// </summary>
public bool SupportRefund
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether void is supported
/// </summary>
public bool SupportVoid
{
get
{
return false;
}
}
/// <summary>
/// Gets a recurring payment type of payment method
/// </summary>
public RecurringPaymentType RecurringPaymentType
{
get
{
return RecurringPaymentType.NotSupported;
}
}
/// <summary>
/// Gets a payment method type
/// </summary>
public PaymentMethodType PaymentMethodType
{
get
{
return PaymentMethodType.Redirection;
}
}
/// <summary>
/// Gets a value indicating whether we should display a payment information page for this plugin
/// </summary>
public bool SkipPaymentInfo
{
get
{
return false;
}
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using System;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Framework;
using OpenMetaverse;
namespace OpenSim.Region.Physics.Manager
{
public delegate void PositionUpdate(Vector3 position);
public delegate void VelocityUpdate(Vector3 velocity);
public delegate void OrientationUpdate(Quaternion orientation);
public enum ActorTypes : int
{
Unknown = 0,
Agent = 1,
Prim = 2,
Ground = 3
}
public enum PIDHoverType
{
Ground,
GroundAndWater,
Water,
Absolute
}
public struct ContactPoint
{
public Vector3 Position;
public Vector3 SurfaceNormal;
public float PenetrationDepth;
public ContactPoint(Vector3 position, Vector3 surfaceNormal, float penetrationDepth)
{
Position = position;
SurfaceNormal = surfaceNormal;
PenetrationDepth = penetrationDepth;
}
}
/// <summary>
/// Used to pass collision information to OnCollisionUpdate listeners.
/// </summary>
public class CollisionEventUpdate : EventArgs
{
/// <summary>
/// Number of collision events in this update.
/// </summary>
public int Count { get { return m_objCollisionList.Count; } }
public bool CollisionsOnPreviousFrame { get; private set; }
public Dictionary<uint, ContactPoint> m_objCollisionList;
public CollisionEventUpdate(Dictionary<uint, ContactPoint> objCollisionList)
{
m_objCollisionList = objCollisionList;
}
public CollisionEventUpdate()
{
m_objCollisionList = new Dictionary<uint, ContactPoint>();
}
public void AddCollider(uint localID, ContactPoint contact)
{
if (!m_objCollisionList.ContainsKey(localID))
{
m_objCollisionList.Add(localID, contact);
}
else
{
if (m_objCollisionList[localID].PenetrationDepth < contact.PenetrationDepth)
m_objCollisionList[localID] = contact;
}
}
/// <summary>
/// Clear added collision events.
/// </summary>
public void Clear()
{
m_objCollisionList.Clear();
}
}
public abstract class PhysicsActor
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public delegate void RequestTerseUpdate();
public delegate void CollisionUpdate(EventArgs e);
public delegate void OutOfBounds(Vector3 pos);
// disable warning: public events
#pragma warning disable 67
public event PositionUpdate OnPositionUpdate;
public event VelocityUpdate OnVelocityUpdate;
public event OrientationUpdate OnOrientationUpdate;
public event RequestTerseUpdate OnRequestTerseUpdate;
/// <summary>
/// Subscribers to this event must synchronously handle the dictionary of collisions received, since the event
/// object is reused in subsequent physics frames.
/// </summary>
public event CollisionUpdate OnCollisionUpdate;
public event OutOfBounds OnOutOfBounds;
#pragma warning restore 67
public static PhysicsActor Null
{
get { return new NullPhysicsActor(); }
}
public abstract bool Stopped { get; }
public abstract Vector3 Size { get; set; }
public virtual byte PhysicsShapeType { get; set; }
public abstract PrimitiveBaseShape Shape { set; }
uint m_baseLocalID;
public virtual uint LocalID
{
set { m_baseLocalID = value; }
get { return m_baseLocalID; }
}
public abstract bool Grabbed { set; }
public abstract bool Selected { set; }
/// <summary>
/// Name of this actor.
/// </summary>
/// <remarks>
/// XXX: Bizarrely, this cannot be "Terrain" or "Water" right now unless it really is simulating terrain or
/// water. This is not a problem due to the formatting of names given by prims and avatars.
/// </remarks>
public string Name { get; protected set; }
/// <summary>
/// This is being used by ODE joint code.
/// </summary>
public string SOPName;
public abstract void CrossingFailure();
public abstract void link(PhysicsActor obj);
public abstract void delink();
public abstract void LockAngularMotion(Vector3 axis);
public virtual void RequestPhysicsterseUpdate()
{
// Make a temporary copy of the event to avoid possibility of
// a race condition if the last subscriber unsubscribes
// immediately after the null check and before the event is raised.
RequestTerseUpdate handler = OnRequestTerseUpdate;
if (handler != null)
{
handler();
}
}
public virtual void RaiseOutOfBounds(Vector3 pos)
{
// Make a temporary copy of the event to avoid possibility of
// a race condition if the last subscriber unsubscribes
// immediately after the null check and before the event is raised.
OutOfBounds handler = OnOutOfBounds;
if (handler != null)
{
handler(pos);
}
}
public virtual void SendCollisionUpdate(EventArgs e)
{
CollisionUpdate handler = OnCollisionUpdate;
// m_log.DebugFormat("[PHYSICS ACTOR]: Sending collision for {0}", LocalID);
if (handler != null)
handler(e);
}
public virtual void SetMaterial (int material) { }
public virtual float Density { get; set; }
public virtual float GravModifier { get; set; }
public virtual float Friction { get; set; }
public virtual float Restitution { get; set; }
/// <summary>
/// Position of this actor.
/// </summary>
/// <remarks>
/// Setting this directly moves the actor to a given position.
/// Getting this retrieves the position calculated by physics scene updates, using factors such as velocity and
/// collisions.
/// </remarks>
public abstract Vector3 Position { get; set; }
public abstract float Mass { get; }
public abstract Vector3 Force { get; set; }
public abstract int VehicleType { get; set; }
public abstract void VehicleFloatParam(int param, float value);
public abstract void VehicleVectorParam(int param, Vector3 value);
public abstract void VehicleRotationParam(int param, Quaternion rotation);
public abstract void VehicleFlags(int param, bool remove);
/// <summary>
/// Allows the detection of collisions with inherently non-physical prims. see llVolumeDetect for more
/// </summary>
public abstract void SetVolumeDetect(int param);
public abstract Vector3 GeometricCenter { get; }
public abstract Vector3 CenterOfMass { get; }
/// <summary>
/// The desired velocity of this actor.
/// </summary>
/// <remarks>
/// Setting this provides a target velocity for physics scene updates.
/// Getting this returns the last set target. Fetch Velocity to get the current velocity.
/// </remarks>
protected Vector3 m_targetVelocity;
public virtual Vector3 TargetVelocity
{
get { return m_targetVelocity; }
set {
m_targetVelocity = value;
Velocity = m_targetVelocity;
}
}
public abstract Vector3 Velocity { get; set; }
public abstract Vector3 Torque { get; set; }
public abstract float CollisionScore { get; set;}
public abstract Vector3 Acceleration { get; set; }
public abstract Quaternion Orientation { get; set; }
public abstract int PhysicsActorType { get; set; }
public abstract bool IsPhysical { get; set; }
public abstract bool Flying { get; set; }
public abstract bool SetAlwaysRun { get; set; }
public abstract bool ThrottleUpdates { get; set; }
public abstract bool IsColliding { get; set; }
public abstract bool CollidingGround { get; set; }
public abstract bool CollidingObj { get; set; }
public abstract bool FloatOnWater { set; }
public abstract Vector3 RotationalVelocity { get; set; }
public abstract bool Kinematic { get; set; }
public abstract float Buoyancy { get; set; }
// Used for MoveTo
public abstract Vector3 PIDTarget { set; }
public abstract bool PIDActive { get; set; }
public abstract float PIDTau { set; }
// Used for llSetHoverHeight and maybe vehicle height
// Hover Height will override MoveTo target's Z
public abstract bool PIDHoverActive { set;}
public abstract float PIDHoverHeight { set;}
public abstract PIDHoverType PIDHoverType { set;}
public abstract float PIDHoverTau { set;}
// For RotLookAt
public abstract Quaternion APIDTarget { set;}
public abstract bool APIDActive { set;}
public abstract float APIDStrength { set;}
public abstract float APIDDamping { set;}
public abstract void AddForce(Vector3 force, bool pushforce);
public abstract void AddAngularForce(Vector3 force, bool pushforce);
public abstract void SetMomentum(Vector3 momentum);
public abstract void SubscribeEvents(int ms);
public abstract void UnSubscribeEvents();
public abstract bool SubscribedEvents();
// Extendable interface for new, physics engine specific operations
public virtual object Extension(string pFunct, params object[] pParams)
{
// A NOP of the physics engine does not implement this feature
return null;
}
}
public class NullPhysicsActor : PhysicsActor
{
public override bool Stopped
{
get{ return false; }
}
public override Vector3 Position
{
get { return Vector3.Zero; }
set { return; }
}
public override bool SetAlwaysRun
{
get { return false; }
set { return; }
}
public override uint LocalID
{
set { return; }
}
public override bool Grabbed
{
set { return; }
}
public override bool Selected
{
set { return; }
}
public override float Buoyancy
{
get { return 0f; }
set { return; }
}
public override bool FloatOnWater
{
set { return; }
}
public override bool CollidingGround
{
get { return false; }
set { return; }
}
public override bool CollidingObj
{
get { return false; }
set { return; }
}
public override Vector3 Size
{
get { return Vector3.Zero; }
set { return; }
}
public override float Mass
{
get { return 0f; }
}
public override Vector3 Force
{
get { return Vector3.Zero; }
set { return; }
}
public override int VehicleType
{
get { return 0; }
set { return; }
}
public override void VehicleFloatParam(int param, float value)
{
}
public override void VehicleVectorParam(int param, Vector3 value)
{
}
public override void VehicleRotationParam(int param, Quaternion rotation)
{
}
public override void VehicleFlags(int param, bool remove)
{
}
public override void SetVolumeDetect(int param)
{
}
public override void SetMaterial(int material)
{
}
public override Vector3 CenterOfMass
{
get { return Vector3.Zero; }
}
public override Vector3 GeometricCenter
{
get { return Vector3.Zero; }
}
public override PrimitiveBaseShape Shape
{
set { return; }
}
public override Vector3 Velocity
{
get { return Vector3.Zero; }
set { return; }
}
public override Vector3 Torque
{
get { return Vector3.Zero; }
set { return; }
}
public override float CollisionScore
{
get { return 0f; }
set { }
}
public override void CrossingFailure()
{
}
public override Quaternion Orientation
{
get { return Quaternion.Identity; }
set { }
}
public override Vector3 Acceleration
{
get { return Vector3.Zero; }
set { }
}
public override bool IsPhysical
{
get { return false; }
set { return; }
}
public override bool Flying
{
get { return false; }
set { return; }
}
public override bool ThrottleUpdates
{
get { return false; }
set { return; }
}
public override bool IsColliding
{
get { return false; }
set { return; }
}
public override int PhysicsActorType
{
get { return (int) ActorTypes.Unknown; }
set { return; }
}
public override bool Kinematic
{
get { return true; }
set { return; }
}
public override void link(PhysicsActor obj)
{
}
public override void delink()
{
}
public override void LockAngularMotion(Vector3 axis)
{
}
public override void AddForce(Vector3 force, bool pushforce)
{
}
public override void AddAngularForce(Vector3 force, bool pushforce)
{
}
public override Vector3 RotationalVelocity
{
get { return Vector3.Zero; }
set { return; }
}
public override Vector3 PIDTarget { set { return; } }
public override bool PIDActive
{
get { return false; }
set { return; }
}
public override float PIDTau { set { return; } }
public override float PIDHoverHeight { set { return; } }
public override bool PIDHoverActive { set { return; } }
public override PIDHoverType PIDHoverType { set { return; } }
public override float PIDHoverTau { set { return; } }
public override Quaternion APIDTarget { set { return; } }
public override bool APIDActive { set { return; } }
public override float APIDStrength { set { return; } }
public override float APIDDamping { set { return; } }
public override void SetMomentum(Vector3 momentum)
{
}
public override void SubscribeEvents(int ms)
{
}
public override void UnSubscribeEvents()
{
}
public override bool SubscribedEvents()
{
return false;
}
}
}
| |
// $ANTLR 2.7.5 (20050128): "tinyc.g" -> "TinyCLexer.cs"$
using antlr;
// Generate header specific to lexer CSharp file
using System;
using Stream = System.IO.Stream;
using TextReader = System.IO.TextReader;
using Hashtable = System.Collections.Hashtable;
using Comparer = System.Collections.Comparer;
using TokenStreamException = antlr.TokenStreamException;
using TokenStreamIOException = antlr.TokenStreamIOException;
using TokenStreamRecognitionException = antlr.TokenStreamRecognitionException;
using CharStreamException = antlr.CharStreamException;
using CharStreamIOException = antlr.CharStreamIOException;
using ANTLRException = antlr.ANTLRException;
using CharScanner = antlr.CharScanner;
using InputBuffer = antlr.InputBuffer;
using ByteBuffer = antlr.ByteBuffer;
using CharBuffer = antlr.CharBuffer;
using Token = antlr.Token;
using IToken = antlr.IToken;
using CommonToken = antlr.CommonToken;
using SemanticException = antlr.SemanticException;
using RecognitionException = antlr.RecognitionException;
using NoViableAltForCharException = antlr.NoViableAltForCharException;
using MismatchedCharException = antlr.MismatchedCharException;
using TokenStream = antlr.TokenStream;
using LexerSharedInputState = antlr.LexerSharedInputState;
using BitSet = antlr.collections.impl.BitSet;
public class TinyCLexer : antlr.CharScanner , TokenStream
{
public const int EOF = 1;
public const int NULL_TREE_LOOKAHEAD = 3;
public const int NULL_NODE = 4;
public const int PROG_LIST = 5;
public const int FUNC = 6;
public const int STRUCT = 7;
public const int STRUCTLIST = 8;
public const int GLOBA = 9;
public const int GLOBD = 10;
public const int DECLA = 11;
public const int FUNC_HEAD = 12;
public const int FUNC_APP = 13;
public const int FORMAL_LIST = 14;
public const int DECL = 15;
public const int ARRAY_DEF = 16;
public const int TYPE_DEF = 17;
public const int VAR = 18;
public const int VAL_INTEGER = 19;
public const int VAL_STRING = 20;
public const int VAL_CHAR = 21;
public const int CONSTRUCT = 22;
public const int CONSARRAY = 23;
public const int NULLCONS = 24;
public const int LOOKUP = 25;
public const int ASSIGN_EVAL = 26;
public const int FOR_DECL = 27;
public const int BLOCK = 28;
public const int IDENT = 29;
public const int LPAREN = 30;
public const int LITERAL_struct = 31;
public const int SEMICOLON = 32;
public const int ASSIGN = 33;
public const int LCURL = 34;
public const int RCURL = 35;
public const int RPAREN = 36;
public const int COMMA = 37;
public const int LBRACKET = 38;
public const int RBRACKET = 39;
public const int LITERAL_if = 40;
public const int LITERAL_else = 41;
public const int LITERAL_for = 42;
public const int LITERAL_while = 43;
public const int LITERAL_return = 44;
public const int LITERAL_delete = 45;
public const int LITERAL_null = 46;
public const int LITERAL_new = 47;
public const int DOT = 48;
public const int LITERAL_not = 49;
public const int MINUS = 50;
public const int TIMES = 51;
public const int DIVIDE = 52;
public const int MOD = 53;
public const int PLUS = 54;
public const int SHIFT_LEFT = 55;
public const int SHIFT_RIGHT = 56;
public const int LTHAN = 57;
public const int GTHAN = 58;
public const int GEQ = 59;
public const int LEQ = 60;
public const int EQ = 61;
public const int NEQ = 62;
public const int LITERAL_and = 63;
public const int LITERAL_or = 64;
public const int ICON = 65;
public const int STCON = 66;
public const int CHCON = 67;
public const int WS_ = 68;
public const int ESC = 69;
public TinyCLexer(Stream ins) : this(new ByteBuffer(ins))
{
}
public TinyCLexer(TextReader r) : this(new CharBuffer(r))
{
}
public TinyCLexer(InputBuffer ib) : this(new LexerSharedInputState(ib))
{
}
public TinyCLexer(LexerSharedInputState state) : base(state)
{
initialize();
}
private void initialize()
{
caseSensitiveLiterals = true;
setCaseSensitive(true);
literals = new Hashtable(100, (float) 0.4, null, Comparer.Default);
literals.Add("for", 42);
literals.Add("if", 40);
literals.Add("delete", 45);
literals.Add("while", 43);
literals.Add("null", 46);
literals.Add("or", 64);
literals.Add("else", 41);
literals.Add("and", 63);
literals.Add("not", 49);
literals.Add("return", 44);
literals.Add("new", 47);
literals.Add("struct", 31);
}
override public IToken nextToken() //throws TokenStreamException
{
IToken theRetToken = null;
tryAgain:
for (;;)
{
IToken _token = null;
int _ttype = Token.INVALID_TYPE;
resetText();
try // for char stream error handling
{
try // for lexical error handling
{
switch ( cached_LA1 )
{
case '\t': case '\n': case '\r': case ' ':
{
mWS_(true);
theRetToken = returnToken_;
break;
}
case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F': case 'G': case 'H':
case 'I': case 'J': case 'K': case 'L':
case 'M': case 'N': case 'O': case 'P':
case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X':
case 'Y': case 'Z': case '_': case 'a':
case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i':
case 'j': case 'k': case 'l': case 'm':
case 'n': case 'o': case 'p': case 'q':
case 'r': case 's': case 't': case 'u':
case 'v': case 'w': case 'x': case 'y':
case 'z':
{
mIDENT(true);
theRetToken = returnToken_;
break;
}
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
case '8': case '9':
{
mICON(true);
theRetToken = returnToken_;
break;
}
case '\\':
{
mESC(true);
theRetToken = returnToken_;
break;
}
case '\'':
{
mCHCON(true);
theRetToken = returnToken_;
break;
}
case '"':
{
mSTCON(true);
theRetToken = returnToken_;
break;
}
case ',':
{
mCOMMA(true);
theRetToken = returnToken_;
break;
}
case ';':
{
mSEMICOLON(true);
theRetToken = returnToken_;
break;
}
case '(':
{
mLPAREN(true);
theRetToken = returnToken_;
break;
}
case '[':
{
mLBRACKET(true);
theRetToken = returnToken_;
break;
}
case ']':
{
mRBRACKET(true);
theRetToken = returnToken_;
break;
}
case ')':
{
mRPAREN(true);
theRetToken = returnToken_;
break;
}
case '{':
{
mLCURL(true);
theRetToken = returnToken_;
break;
}
case '}':
{
mRCURL(true);
theRetToken = returnToken_;
break;
}
case '+':
{
mPLUS(true);
theRetToken = returnToken_;
break;
}
case '-':
{
mMINUS(true);
theRetToken = returnToken_;
break;
}
case '*':
{
mTIMES(true);
theRetToken = returnToken_;
break;
}
case '.':
{
mDOT(true);
theRetToken = returnToken_;
break;
}
case '/':
{
mDIVIDE(true);
theRetToken = returnToken_;
break;
}
case '%':
{
mMOD(true);
theRetToken = returnToken_;
break;
}
case '!':
{
mNEQ(true);
theRetToken = returnToken_;
break;
}
default:
if ((cached_LA1=='=') && (cached_LA2=='='))
{
mEQ(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='<') && (cached_LA2=='=')) {
mLEQ(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='>') && (cached_LA2=='=')) {
mGEQ(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='<') && (cached_LA2=='<')) {
mSHIFT_LEFT(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='>') && (cached_LA2=='>')) {
mSHIFT_RIGHT(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='=') && (true)) {
mASSIGN(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='<') && (true)) {
mLTHAN(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='>') && (true)) {
mGTHAN(true);
theRetToken = returnToken_;
}
else
{
if (cached_LA1==EOF_CHAR) { uponEOF(); returnToken_ = makeToken(Token.EOF_TYPE); }
else {throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());}
}
break; }
if ( null==returnToken_ ) goto tryAgain; // found SKIP token
_ttype = returnToken_.Type;
_ttype = testLiteralsTable(_ttype);
returnToken_.Type = _ttype;
return returnToken_;
}
catch (RecognitionException e) {
throw new TokenStreamRecognitionException(e);
}
}
catch (CharStreamException cse) {
if ( cse is CharStreamIOException ) {
throw new TokenStreamIOException(((CharStreamIOException)cse).io);
}
else {
throw new TokenStreamException(cse.Message);
}
}
}
}
public void mWS_(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = WS_;
{
switch ( cached_LA1 )
{
case ' ':
{
match(' ');
break;
}
case '\t':
{
match('\t');
break;
}
case '\n':
{
match('\n');
newline();
break;
}
case '\r':
{
match('\r');
break;
}
default:
{
throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());
}
}
}
_ttype = Token.SKIP;
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mIDENT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = IDENT;
{
switch ( cached_LA1 )
{
case 'a': case 'b': case 'c': case 'd':
case 'e': case 'f': case 'g': case 'h':
case 'i': case 'j': case 'k': case 'l':
case 'm': case 'n': case 'o': case 'p':
case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x':
case 'y': case 'z':
{
matchRange('a','z');
break;
}
case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F': case 'G': case 'H':
case 'I': case 'J': case 'K': case 'L':
case 'M': case 'N': case 'O': case 'P':
case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X':
case 'Y': case 'Z':
{
matchRange('A','Z');
break;
}
case '_':
{
match('_');
break;
}
default:
{
throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());
}
}
}
{ // ( ... )*
for (;;)
{
switch ( cached_LA1 )
{
case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F': case 'G': case 'H':
case 'I': case 'J': case 'K': case 'L':
case 'M': case 'N': case 'O': case 'P':
case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X':
case 'Y': case 'Z': case '_': case 'a':
case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i':
case 'j': case 'k': case 'l': case 'm':
case 'n': case 'o': case 'p': case 'q':
case 'r': case 's': case 't': case 'u':
case 'v': case 'w': case 'x': case 'y':
case 'z':
{
{
switch ( cached_LA1 )
{
case 'a': case 'b': case 'c': case 'd':
case 'e': case 'f': case 'g': case 'h':
case 'i': case 'j': case 'k': case 'l':
case 'm': case 'n': case 'o': case 'p':
case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x':
case 'y': case 'z':
{
matchRange('a','z');
break;
}
case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F': case 'G': case 'H':
case 'I': case 'J': case 'K': case 'L':
case 'M': case 'N': case 'O': case 'P':
case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X':
case 'Y': case 'Z':
{
matchRange('A','Z');
break;
}
case '_':
{
match('_');
break;
}
default:
{
throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());
}
}
}
break;
}
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
case '8': case '9':
{
{
matchRange('0','9');
}
break;
}
default:
{
goto _loop123_breakloop;
}
}
}
_loop123_breakloop: ;
} // ( ... )*
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mICON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = ICON;
matchRange('0','9');
{ // ( ... )*
for (;;)
{
if (((cached_LA1 >= '0' && cached_LA1 <= '9')))
{
matchRange('0','9');
}
else
{
goto _loop126_breakloop;
}
}
_loop126_breakloop: ;
} // ( ... )*
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mESC(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = ESC;
match('\\');
{
switch ( cached_LA1 )
{
case 'n':
{
match('n');
break;
}
case 'r':
{
match('r');
break;
}
case 't':
{
match('t');
break;
}
case 'b':
{
match('b');
break;
}
case 'f':
{
match('f');
break;
}
case '"':
{
match('"');
break;
}
case '\'':
{
match('\'');
break;
}
case '\\':
{
match('\\');
break;
}
default:
{
throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());
}
}
}
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mCHCON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = CHCON;
int _saveIndex = 0;
_saveIndex = text.Length;
match("'");
text.Length = _saveIndex;
{
switch ( cached_LA1 )
{
case '\\':
{
mESC(false);
break;
}
case '\u0000': case '\u0001': case '\u0002': case '\u0003':
case '\u0004': case '\u0005': case '\u0006': case '\u0007':
case '\u0008': case '\t': case '\n': case '\u000b':
case '\u000c': case '\r': case '\u000e': case '\u000f':
case '\u0010': case '\u0011': case '\u0012': case '\u0013':
case '\u0014': case '\u0015': case '\u0016': case '\u0017':
case '\u0018': case '\u0019': case '\u001a': case '\u001b':
case '\u001c': case '\u001d': case '\u001e': case '\u001f':
case ' ': case '!': case '"': case '#':
case '$': case '%': case '&': case '(':
case ')': case '*': case '+': case ',':
case '-': case '.': case '/': case '0':
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8':
case '9': case ':': case ';': case '<':
case '=': case '>': case '?': case '@':
case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F': case 'G': case 'H':
case 'I': case 'J': case 'K': case 'L':
case 'M': case 'N': case 'O': case 'P':
case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X':
case 'Y': case 'Z': case '[': case ']':
case '^': case '_': case '`': case 'a':
case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i':
case 'j': case 'k': case 'l': case 'm':
case 'n': case 'o': case 'p': case 'q':
case 'r': case 's': case 't': case 'u':
case 'v': case 'w': case 'x': case 'y':
case 'z': case '{': case '|': case '}':
case '~': case '\u007f':
{
matchNot('\'');
break;
}
default:
{
throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());
}
}
}
_saveIndex = text.Length;
match("'");
text.Length = _saveIndex;
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mSTCON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = STCON;
match('"');
{ // ( ... )*
for (;;)
{
switch ( cached_LA1 )
{
case '\\':
{
mESC(false);
break;
}
case '\u0000': case '\u0001': case '\u0002': case '\u0003':
case '\u0004': case '\u0005': case '\u0006': case '\u0007':
case '\u0008': case '\t': case '\n': case '\u000b':
case '\u000c': case '\r': case '\u000e': case '\u000f':
case '\u0010': case '\u0011': case '\u0012': case '\u0013':
case '\u0014': case '\u0015': case '\u0016': case '\u0017':
case '\u0018': case '\u0019': case '\u001a': case '\u001b':
case '\u001c': case '\u001d': case '\u001e': case '\u001f':
case ' ': case '!': case '#': case '$':
case '%': case '&': case '\'': case '(':
case ')': case '*': case '+': case ',':
case '-': case '.': case '/': case '0':
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8':
case '9': case ':': case ';': case '<':
case '=': case '>': case '?': case '@':
case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F': case 'G': case 'H':
case 'I': case 'J': case 'K': case 'L':
case 'M': case 'N': case 'O': case 'P':
case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X':
case 'Y': case 'Z': case '[': case ']':
case '^': case '_': case '`': case 'a':
case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i':
case 'j': case 'k': case 'l': case 'm':
case 'n': case 'o': case 'p': case 'q':
case 'r': case 's': case 't': case 'u':
case 'v': case 'w': case 'x': case 'y':
case 'z': case '{': case '|': case '}':
case '~': case '\u007f':
{
matchNot('"');
break;
}
default:
{
goto _loop133_breakloop;
}
}
}
_loop133_breakloop: ;
} // ( ... )*
match('"');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mCOMMA(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = COMMA;
match(',');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mSEMICOLON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = SEMICOLON;
match(';');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mLPAREN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = LPAREN;
match('(');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mLBRACKET(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = LBRACKET;
match('[');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mRBRACKET(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = RBRACKET;
match(']');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mRPAREN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = RPAREN;
match(')');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mLCURL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = LCURL;
match('{');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mRCURL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = RCURL;
match('}');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mPLUS(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = PLUS;
match('+');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mMINUS(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = MINUS;
match('-');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mTIMES(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = TIMES;
match('*');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mDOT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = DOT;
match('.');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mDIVIDE(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = DIVIDE;
match('/');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mMOD(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = MOD;
match('%');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = ASSIGN;
match('=');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mEQ(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = EQ;
match("==");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mNEQ(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = NEQ;
match("!=");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mLTHAN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = LTHAN;
match('<');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mGTHAN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = GTHAN;
match('>');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mLEQ(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = LEQ;
match("<=");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mGEQ(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = GEQ;
match(">=");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mSHIFT_LEFT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = SHIFT_LEFT;
match("<<");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mSHIFT_RIGHT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = SHIFT_RIGHT;
match(">>");
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Positioning.dll
// Description: A library for managing GPS connections.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from http://geoframework.codeplex.com/ version 2.0
//
// The Initial Developer of this original code is Jon Pearson. Submitted Oct. 21, 2010 by Ben Tombs (tidyup)
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// -------------------------------------------------------------------------------------------------------
// | Developer | Date | Comments
// |--------------------------|------------|--------------------------------------------------------------
// | Tidyup (Ben Tombs) | 10/21/2010 | Original copy submitted from modified GeoFrameworks 2.0
// | Shade1974 (Ted Dunsford) | 10/21/2010 | Added file headers reviewed formatting with resharper.
// ********************************************************************************************************
using System;
using System.Globalization;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using DotSpatial.Positioning.Properties;
#if !PocketPC || DesignTime
using System.ComponentModel;
#endif
namespace DotSpatial.Positioning
{
#if !PocketPC || DesignTime
/// <summary>
/// Represents a highly-precise two-dimensional size.
/// </summary>
/// <remarks><para>This structure is a <em>DotSpatial.Positioning</em> "parseable type" whose value can
/// be freely converted to and from <strong>String</strong> objects via the
/// <strong>ToString</strong> and <strong>Parse</strong> methods.</para>
/// <para>Instances of this structure are guaranteed to be thread-safe because it is
/// immutable (its properties can only be modified via constructors).</para></remarks>
[TypeConverter("DotSpatial.Positioning.Design.SizeDConverter, DotSpatial.Positioning.Design, Culture=neutral, Version=1.0.0.0, PublicKeyToken=b4b0b185210c9dae")]
#endif
public struct SizeD : IFormattable, IEquatable<SizeD>, IXmlSerializable
{
/// <summary>
///
/// </summary>
private double _width;
/// <summary>
///
/// </summary>
private double _height;
#region Fields
/// <summary>
/// Represents a size with no value.
/// </summary>
public static readonly SizeD Empty = new SizeD(0.0, 0.0);
/// <summary>
/// Represents an infinite size.
/// </summary>
public static readonly SizeD Infinity = new SizeD(Double.PositiveInfinity, Double.PositiveInfinity);
/// <summary>
/// Represents the smallest possible size.
/// </summary>
public static readonly SizeD Minimum = new SizeD(Double.MinValue, Double.MinValue);
/// <summary>
/// Represents the largest possible size.
/// </summary>
public static readonly SizeD Maximum = new SizeD(Double.MaxValue, Double.MaxValue);
#endregion Fields
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="SizeD"/> struct.
/// </summary>
/// <param name="pt">The pt.</param>
public SizeD(PointD pt)
{
_width = pt.X;
_height = pt.Y;
}
/// <summary>
/// Initializes a new instance of the <see cref="SizeD"/> struct.
/// </summary>
/// <param name="size">The size.</param>
public SizeD(SizeD size)
{
_width = size.Width;
_height = size.Height;
}
/// <summary>
/// Creates a new instance.
/// </summary>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
public SizeD(double width, double height)
{
_width = width;
_height = height;
}
/// <summary>
/// Initializes a new instance of the <see cref="SizeD"/> struct.
/// </summary>
/// <param name="value">The value.</param>
public SizeD(string value)
: this(value, CultureInfo.CurrentCulture)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="SizeD"/> struct.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="culture">The culture.</param>
public SizeD(string value, CultureInfo culture)
{
// Split out the values
string[] values = value.Trim().Split(culture.TextInfo.ListSeparator.ToCharArray());
// There should be two values
if (values.Length != 2)
throw new FormatException(Resources.SizeD_InvalidFormat);
// PArse it out
_width = double.Parse(values[0].Trim(), culture);
_height = double.Parse(values[1].Trim(), culture);
}
/// <summary>
/// Initializes a new instance of the <see cref="SizeD"/> struct.
/// </summary>
/// <param name="reader">The reader.</param>
public SizeD(XmlReader reader)
{
// Initialize all fields
_width = Double.NaN;
_height = Double.NaN;
// Deserialize the object from XML
ReadXml(reader);
}
#endregion Constructors
#region Public Properties
/// <summary>
/// Returns the horizontal size.
/// </summary>
public double Width
{
get
{
return _width;
}
}
/// <summary>
/// Returns the vertical size.
/// </summary>
public double Height
{
get
{
return _height;
}
}
/// <summary>
/// Returns the ratio width to height.
/// </summary>
public double AspectRatio
{
get
{
return _width / _height;
}
}
/// <summary>
/// Indicates if the instance has any value.
/// </summary>
public bool IsEmpty
{
get
{
return (_width == 0 && _height == 0);
}
}
#endregion Public Properties
#region Public Methods
/// <summary>
/// Toes the aspect ratio.
/// </summary>
/// <param name="size">The size.</param>
/// <returns></returns>
public SizeD ToAspectRatio(SizeD size)
{
// Calculate the aspect ratio
return ToAspectRatio(size.Width / size.Height);
}
/// <summary>
/// Toes the aspect ratio.
/// </summary>
/// <param name="aspectRatio">The aspect ratio.</param>
/// <returns></returns>
public SizeD ToAspectRatio(double aspectRatio)
{
double currentAspect = AspectRatio;
// Do the values already match?
if (currentAspect == aspectRatio) return this;
// Is the new ratio higher or lower?
if (aspectRatio > currentAspect)
{
// Inflate the GeographicRectangle to the new height minus the current height
// TESTS OK
return new SizeD(_width +
(aspectRatio * Height - Width), _height);
}
// Inflate the GeographicRectangle to the new height minus the current height
return new SizeD(_width,
_height + (Width / aspectRatio - Height));
}
/// <summary>
/// Returns a copy of the current instance.
/// </summary>
/// <returns></returns>
public SizeD Clone()
{
return new SizeD(_width, _height);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <param name="format">The format.</param>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public string ToString(string format)
{
return ToString(format, CultureInfo.CurrentCulture);
}
#endregion Public Methods
#region Overrides
/// <summary>
/// Compares the current instance to the specified object.
/// </summary>
/// <param name="obj">An <strong>Object</strong> to compare with.</param>
/// <returns>A <strong>Boolean</strong>, True if the values are equivalent.</returns>
public override bool Equals(object obj)
{
// Only compare similar objects
if (obj is SizeD)
return Equals((SizeD)obj);
return false;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
public override int GetHashCode()
{
return Convert.ToInt32(_width) ^ Convert.ToInt32(_height);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public override string ToString()
{
return ToString("G", CultureInfo.CurrentCulture);
}
#endregion Overrides
#region Static Methods
/// <summary>
/// Parses the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public static SizeD Parse(string value)
{
return new SizeD(value, CultureInfo.CurrentCulture);
}
/// <summary>
/// Parses the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="culture">The culture.</param>
/// <returns></returns>
public static SizeD Parse(string value, CultureInfo culture)
{
return new SizeD(value, culture);
}
#endregion Static Methods
#region Operators
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(SizeD left, SizeD right)
{
return left.Equals(right);
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(SizeD left, SizeD right)
{
return !(left.Equals(right));
}
/// <summary>
/// Implements the operator +.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static SizeD operator +(SizeD left, SizeD right)
{
return left.Add(right);
}
/// <summary>
/// Implements the operator -.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static SizeD operator -(SizeD left, SizeD right)
{
return left.Subtract(right);
}
/// <summary>
/// Implements the operator *.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static SizeD operator *(SizeD left, SizeD right)
{
return left.Multiply(right);
}
/// <summary>
/// Implements the operator /.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static SizeD operator /(SizeD left, SizeD right)
{
return left.Divide(right);
}
/// <summary>
/// Returns the sum of the current instance with the specified size.
/// </summary>
/// <param name="size">The size.</param>
/// <returns></returns>
public SizeD Add(SizeD size)
{
return new SizeD(_width + size.Width, _height + size.Height);
}
/// <summary>
/// Returns the current instance decreased by the specified value.
/// </summary>
/// <param name="size">The size.</param>
/// <returns></returns>
public SizeD Subtract(SizeD size)
{
return new SizeD(_width - size.Width, _height - size.Height);
}
/// <summary>
/// Returns the product of the current instance with the specified value.
/// </summary>
/// <param name="size">The size.</param>
/// <returns></returns>
public SizeD Multiply(SizeD size)
{
return new SizeD(_width * size.Width, _height * size.Height);
}
/// <summary>
/// Returns the current instance divided by the specified value.
/// </summary>
/// <param name="size">The size.</param>
/// <returns></returns>
public SizeD Divide(SizeD size)
{
return new SizeD(_width / size.Width, _height / size.Height);
}
#endregion Operators
#region IEquatable<SizeD> Members
/// <summary>
/// Compares the current instance to the specified object.
/// </summary>
/// <param name="other">A <strong>SizeD</strong> object to compare with.</param>
/// <returns>A <strong>Boolean</strong>, True if the values are equivalent.</returns>
public bool Equals(SizeD other)
{
return _width.Equals(other.Width) && _height.Equals(other.Height);
}
#endregion IEquatable<SizeD> Members
#region IFormattable Members
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <param name="format">The format to use.-or- A null reference (Nothing in Visual Basic) to use the default format defined for the type of the <see cref="T:System.IFormattable"/> implementation.</param>
/// <param name="formatProvider">The provider to use to format the value.-or- A null reference (Nothing in Visual Basic) to obtain the numeric format information from the current locale setting of the operating system.</param>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public string ToString(string format, IFormatProvider formatProvider)
{
CultureInfo culture = (CultureInfo)formatProvider ?? CultureInfo.CurrentCulture;
if (string.IsNullOrEmpty(format))
format = "G";
return Width.ToString(format, culture)
+ culture.TextInfo.ListSeparator + " "
+ Height.ToString(format, culture);
}
#endregion IFormattable Members
#region IXmlSerializable Members
/// <summary>
/// This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"/> to the class.
/// </summary>
/// <returns>An <see cref="T:System.Xml.Schema.XmlSchema"/> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"/> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"/> method.</returns>
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
/// <summary>
/// Converts an object into its XML representation.
/// </summary>
/// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized.</param>
public void WriteXml(XmlWriter writer)
{
writer.WriteAttributeString("Width",
_width.ToString("G17", CultureInfo.InvariantCulture));
writer.WriteAttributeString("Height",
_height.ToString("G17", CultureInfo.InvariantCulture));
}
/// <summary>
/// Generates an object from its XML representation.
/// </summary>
/// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized.</param>
public void ReadXml(XmlReader reader)
{
double.TryParse(reader.GetAttribute("Width"), NumberStyles.Any, CultureInfo.InvariantCulture, out _width);
double.TryParse(reader.GetAttribute("Height"), NumberStyles.Any, CultureInfo.InvariantCulture, out _height);
reader.Read();
}
#endregion IXmlSerializable Members
}
}
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
//with contributions by Andrew Bradnan
#endregion
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Xml;
using Irony.Parsing;
using Irony.Ast;
using Irony.Interpreter;
using Irony.GrammarExplorer.Properties;
namespace Irony.GrammarExplorer {
public partial class fmGrammarExplorer : Form {
public fmGrammarExplorer() {
InitializeComponent();
}
//fields
Grammar _grammar;
LanguageData _language;
Parser _parser;
ParseTree _parseTree;
RuntimeException _runtimeError;
bool _loaded;
#region Form load/unload events
private void fmExploreGrammar_Load(object sender, EventArgs e) {
ClearLanguageInfo();
try {
txtSource.Text = Settings.Default.SourceSample;
txtSearch.Text = Settings.Default.SearchPattern;
GrammarItemList grammars = GrammarItemList.FromXml(Settings.Default.Grammars);
grammars.ShowIn(cboGrammars);
chkParserTrace.Checked = Settings.Default.EnableTrace;
chkDisableHili.Checked = Settings.Default.DisableHili;
cboGrammars.SelectedIndex = Settings.Default.LanguageIndex; //this will build parser and start colorizer
} catch { }
_loaded = true;
}
private void fmExploreGrammar_FormClosing(object sender, FormClosingEventArgs e) {
Settings.Default.SourceSample = txtSource.Text;
Settings.Default.LanguageIndex = cboGrammars.SelectedIndex;
Settings.Default.SearchPattern = txtSearch.Text;
Settings.Default.EnableTrace = chkParserTrace.Checked;
Settings.Default.DisableHili = chkDisableHili.Checked;
var grammars = GrammarItemList.FromCombo(cboGrammars);
Settings.Default.Grammars = grammars.ToXml();
Settings.Default.Save();
}//method
#endregion
#region Show... methods
//Show... methods ######################################################################################################################
private void ClearLanguageInfo() {
lblLanguage.Text = string.Empty;
lblLanguageVersion.Text = string.Empty;
lblLanguageDescr.Text = string.Empty;
txtGrammarComments.Text = string.Empty;
}
private void ClearParserOutput() {
lblSrcLineCount.Text = string.Empty;
lblSrcTokenCount.Text = "";
lblParseTime.Text = "";
lblParseErrorCount.Text = "";
lstTokens.Items.Clear();
gridCompileErrors.Rows.Clear();
gridParserTrace.Rows.Clear();
lstTokens.Items.Clear();
tvParseTree.Nodes.Clear();
tvAst.Nodes.Clear();
Application.DoEvents();
}
private void ShowLanguageInfo() {
if (_grammar == null) return;
var langAttr = LanguageAttribute.GetValue(_grammar.GetType());
if (langAttr == null) return;
lblLanguage.Text = langAttr.LanguageName;
lblLanguageVersion.Text = langAttr.Version;
lblLanguageDescr.Text = langAttr.Description;
txtGrammarComments.Text = _grammar.GrammarComments;
}
private void ShowCompilerErrors() {
gridCompileErrors.Rows.Clear();
if (_parseTree == null || _parseTree.ParserMessages.Count == 0) return;
foreach (var err in _parseTree.ParserMessages)
gridCompileErrors.Rows.Add(err.Location, err, err.ParserState);
var needPageSwitch = tabBottom.SelectedTab != pageParserOutput &&
!(tabBottom.SelectedTab == pageParserTrace && chkParserTrace.Checked);
if (needPageSwitch)
tabBottom.SelectedTab = pageParserOutput;
}
private void ShowParseTrace() {
gridParserTrace.Rows.Clear();
foreach (var entry in _parser.Context.ParserTrace) {
int index = gridParserTrace.Rows.Add(entry.State, entry.StackTop, entry.Input, entry.Message);
if (entry.IsError)
gridParserTrace.Rows[gridParserTrace.Rows.Count - 1].DefaultCellStyle.ForeColor = Color.Red;
}
//Show tokens
foreach (Token tkn in _parseTree.Tokens) {
if (chkExcludeComments.Checked && tkn.Category == TokenCategory.Comment) continue;
lstTokens.Items.Add(tkn);
}
}//method
private void ShowCompileStats() {
if (_parseTree == null) return;
lblSrcLineCount.Text = string.Empty;
if (_parseTree.Tokens.Count > 0)
lblSrcLineCount.Text = (_parseTree.Tokens[_parseTree.Tokens.Count - 1].Location.Line + 1).ToString();
lblSrcTokenCount.Text = _parseTree.Tokens.Count.ToString();
lblParseTime.Text = _parseTree.ParseTime.ToString();
lblParseErrorCount.Text = _parseTree.ParserMessages.Count.ToString();
Application.DoEvents();
//Note: this time is "pure" parse time; actual delay after cliking "Compile" includes time to fill ParseTree, AstTree controls
}
private void ShowParseTree() {
tvParseTree.Nodes.Clear();
if (_parseTree == null) return;
AddParseNodeRec(null, _parseTree.Root);
}
private void AddParseNodeRec(TreeNode parent, ParseTreeNode node) {
if (node == null) return;
string txt = node.ToString();
TreeNode tvNode = (parent == null? tvParseTree.Nodes.Add(txt) : parent.Nodes.Add(txt) );
tvNode.Tag = node;
foreach(var child in node.ChildNodes)
AddParseNodeRec(tvNode, child);
}
private void ShowAstTree() {
tvAst.Nodes.Clear();
if (_parseTree == null || _parseTree.Root == null || _parseTree.Root.AstNode == null) return;
AddAstNodeRec(null, _parseTree.Root.AstNode);
}
private void AddAstNodeRec(TreeNode parent, object astNode) {
if (astNode == null) return;
string txt = astNode.ToString();
TreeNode newNode = (parent == null ?
tvAst.Nodes.Add(txt) : parent.Nodes.Add(txt));
newNode.Tag = astNode;
var iBrowsable = astNode as IBrowsableAstNode;
if (iBrowsable == null) return;
var childList = iBrowsable.GetChildNodes();
foreach (var child in childList)
AddAstNodeRec(newNode, child);
}
private void ShowParserConstructionResults() {
lblParserStateCount.Text = _language.ParserData.States.Count.ToString();
lblParserConstrTime.Text = _language.ConstructionTime.ToString();
txtParserStates.Text = string.Empty;
gridGrammarErrors.Rows.Clear();
txtTerms.Text = string.Empty;
txtNonTerms.Text = string.Empty;
txtParserStates.Text = string.Empty;
tabBottom.SelectedTab = pageLanguage;
if (_parser == null) return;
txtTerms.Text = ParserDataPrinter.PrintTerminals(_parser.Language);
txtNonTerms.Text = ParserDataPrinter.PrintNonTerminals(_parser.Language);
txtParserStates.Text = ParserDataPrinter.PrintStateList(_parser.Language);
ShowGrammarErrors();
}//method
private void ShowGrammarErrors() {
gridGrammarErrors.Rows.Clear();
var errors = _parser.Language.Errors;
if (errors.Count == 0) return;
foreach (var err in errors)
gridGrammarErrors.Rows.Add(err.Level.ToString(), err.Message, err.State);
if (tabBottom.SelectedTab != pageGrammarErrors)
tabBottom.SelectedTab = pageGrammarErrors;
}
private void ShowSourceLocation(SourceLocation location, int length) {
if (location.Position < 0) return;
txtSource.SelectionStart = location.Position;
txtSource.SelectionLength = length;
//txtSource.Select(location.Position, length);
txtSource.ScrollToCaret();
if (tabGrammar.SelectedTab != pageTest)
tabGrammar.SelectedTab = pageTest;
txtSource.Focus();
//lblLoc.Text = location.ToString();
}
private void ShowSourceLocationAndTraceToken(SourceLocation location, int length) {
ShowSourceLocation(location, length);
//find token in trace
for (int i = 0; i < lstTokens.Items.Count; i++) {
var tkn = lstTokens.Items[i] as Token;
if (tkn.Location.Position == location.Position) {
lstTokens.SelectedIndex = i;
return;
}//if
}//for i
}
private void LocateParserState(ParserState state) {
if (state == null) return;
if (tabGrammar.SelectedTab != pageParserStates)
tabGrammar.SelectedTab = pageParserStates;
//first scroll to the bottom, so that scrolling to needed position brings it to top
txtParserStates.SelectionStart = txtParserStates.Text.Length - 1;
txtParserStates.ScrollToCaret();
DoSearch(txtParserStates, "State " + state.Name, 0);
}
private void ShowRuntimeError(RuntimeException error){
_runtimeError = error;
lnkShowErrLocation.Enabled = _runtimeError != null;
lnkShowErrStack.Enabled = lnkShowErrLocation.Enabled;
if (_runtimeError != null) {
//the exception was caught and processed by Interpreter
WriteOutput("Error: " + error.Message + " At " + _runtimeError.Location.ToUiString() + ".");
ShowSourceLocation(_runtimeError.Location, 1);
} else {
//the exception was not caught by interpreter/AST node. Show full exception info
WriteOutput("Error: " + error.Message);
fmShowException.ShowException(error);
}
tabBottom.SelectedTab = pageOutput;
}
private void ClearRuntimeInfo() {
lnkShowErrLocation.Enabled = false;
lnkShowErrStack.Enabled = false;
_runtimeError = null;
txtOutput.Text = string.Empty;
}
#endregion
#region Grammar combo menu commands
private void menuGrammars_Opening(object sender, CancelEventArgs e) {
miRemove.Enabled = cboGrammars.Items.Count > 0;
}
private void miAdd_Click(object sender, EventArgs e) {
if (dlgSelectAssembly.ShowDialog() != DialogResult.OK) return;
string location = dlgSelectAssembly.FileName;
if (string.IsNullOrEmpty(location)) return;
var oldGrammars = new GrammarItemList();
foreach(var item in cboGrammars.Items)
oldGrammars.Add((GrammarItem) item);
var grammars = fmSelectGrammars.SelectGrammars(location, oldGrammars);
if (grammars == null) return;
foreach (GrammarItem item in grammars)
cboGrammars.Items.Add(item);
}
private void miRemove_Click(object sender, EventArgs e) {
if (MessageBox.Show("Are you sure you want to remove grammmar " + cboGrammars.SelectedItem + "?",
"Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) {
cboGrammars.Items.RemoveAt(cboGrammars.SelectedIndex);
_parser = null;
if (cboGrammars.Items.Count > 0)
cboGrammars.SelectedIndex = 0;
}
}
private void miRemoveAll_Click(object sender, EventArgs e) {
if (MessageBox.Show("Are you sure you want to remove all grammmars in the list?",
"Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) {
cboGrammars.Items.Clear();
_parser = null;
}
}
#endregion
#region Parsing and running
private void CreateGrammar() {
GrammarItem selItem = cboGrammars.SelectedItem as GrammarItem;
_grammar = selItem.CreateGrammar();
}
private void CreateParser() {
StopHighlighter();
btnRun.Enabled = false;
txtOutput.Text = string.Empty;
_parseTree = null;
btnRun.Enabled = _grammar.FlagIsSet(LanguageFlags.CanRunSample);
_language = new LanguageData(_grammar);
_parser = new Parser (_language);
ShowParserConstructionResults();
StartHighligter();
}
private void ParseSample() {
ClearParserOutput();
if (_parser == null || !_parser.Language.CanParse()) return;
_parseTree = null;
GC.Collect(); //to avoid disruption of perf times with occasional collections
_parser.Context.SetOption(ParseOptions.TraceParser, chkParserTrace.Checked);
try {
_parser.Parse(txtSource.Text, "<source>");
} catch (Exception ex) {
gridCompileErrors.Rows.Add(null, ex.Message, null);
tabBottom.SelectedTab = pageParserOutput;
throw;
} finally {
_parseTree = _parser.Context.CurrentParseTree;
ShowCompilerErrors();
if (chkParserTrace.Checked) {
ShowParseTrace();
}
ShowCompileStats();
ShowParseTree();
ShowAstTree();
}
}
private void RunSample() {
ClearRuntimeInfo();
Stopwatch sw = new Stopwatch();
txtOutput.Text = "";
try {
if (_parseTree == null)
ParseSample();
if (_parseTree.ParserMessages.Count > 0) return;
GC.Collect(); //to avoid disruption of perf times with occasional collections
sw.Start();
string output = _grammar.RunSample(_parseTree);
sw.Stop();
lblRunTime.Text = sw.ElapsedMilliseconds.ToString();
WriteOutput(output);
tabBottom.SelectedTab = pageOutput;
} catch (RuntimeException ex) {
ShowRuntimeError(ex);
} finally {
sw.Stop();
}//finally
}//method
private void WriteOutput(string text) {
if (string.IsNullOrEmpty(text)) return;
txtOutput.Text += text + Environment.NewLine;
txtOutput.Select(txtOutput.Text.Length - 1, 0);
}
#endregion
#region miscellaneous: LoadSourceFile, Search, Source highlighting
private void LoadSourceFile(string path) {
_parseTree = null;
StreamReader reader = null;
try {
reader = new StreamReader(path);
txtSource.Text = null; //to clear any old formatting
txtSource.Text = reader.ReadToEnd();
txtSource.Select(0, 0);
} catch (Exception e) {
MessageBox.Show(e.Message);
} finally {
if (reader != null)
reader.Close();
}
}
//Source highlighting
RichTextBoxHighligter _highlighter;
private void StartHighligter() {
if (_highlighter != null)
StopHighlighter();
if (chkDisableHili.Checked) return;
if (!_parser.Language.CanParse()) return;
_highlighter = new RichTextBoxHighligter(txtSource, _language);
_highlighter.Adapter.Activate();
}
private void StopHighlighter() {
if (_highlighter == null) return;
_highlighter.Dispose();
_highlighter = null;
ClearHighlighting();
}
private void ClearHighlighting() {
var txt = txtSource.Text;
txtSource.Clear();
txtSource.Text = txt; //remove all old highlighting
}
private void EnableHighligter(bool enable) {
if (_highlighter != null)
StopHighlighter();
if (enable)
StartHighligter();
}
//The following methods are contributed by Andrew Bradnan; pasted here with minor changes
private void DoSearch() {
lblSearchError.Visible = false;
TextBoxBase textBox = GetSearchContentBox();
if (textBox == null) return;
int idxStart = textBox.SelectionStart + textBox.SelectionLength;
if (!DoSearch(textBox, txtSearch.Text, idxStart)) {
lblSearchError.Text = "Not found.";
lblSearchError.Visible = true;
}
}//method
private bool DoSearch(TextBoxBase textBox, string fragment, int start) {
textBox.SelectionLength = 0;
// Compile the regular expression.
Regex r = new Regex(fragment, RegexOptions.IgnoreCase);
// Match the regular expression pattern against a text string.
Match m = r.Match(textBox.Text.Substring(start));
if (m.Success) {
int i = 0;
Group g = m.Groups[i];
CaptureCollection cc = g.Captures;
Capture c = cc[0];
textBox.SelectionStart = c.Index + start;
textBox.SelectionLength = c.Length;
textBox.Focus();
textBox.ScrollToCaret();
return true;
}
return false;
}//method
public TextBoxBase GetSearchContentBox() {
switch (tabGrammar.SelectedIndex) {
case 0:
return txtTerms;
case 1:
return txtNonTerms;
case 2:
return txtParserStates;
case 4:
return txtSource;
default:
return null;
}//switch
}
#endregion
#region Controls event handlers
//Controls event handlers ###################################################################################################
private void btnParse_Click(object sender, EventArgs e) {
ParseSample();
}
private void btnRun_Click(object sender, EventArgs e) {
RunSample();
}
private void tvParseTree_AfterSelect(object sender, TreeViewEventArgs e) {
var vtreeNode = tvParseTree.SelectedNode;
if (vtreeNode == null) return;
var parseNode = vtreeNode.Tag as ParseTreeNode;
if (parseNode == null) return;
ShowSourceLocation(parseNode.Span.Location, 1);
}
private void tvAst_AfterSelect(object sender, TreeViewEventArgs e) {
var treeNode = tvAst.SelectedNode;
if (treeNode == null) return;
var iBrowsable = treeNode.Tag as IBrowsableAstNode;
if (iBrowsable == null) return;
ShowSourceLocation(iBrowsable.Location, 1);
}
bool _changingGrammar;
private void cboGrammars_SelectedIndexChanged(object sender, EventArgs e) {
try {
ClearLanguageInfo();
ClearParserOutput();
ClearRuntimeInfo();
_changingGrammar = true;
CreateGrammar();
ShowLanguageInfo();
CreateParser();
} finally {
_changingGrammar = false; //in case of exception
}
}
private void btnFileOpen_Click(object sender, EventArgs e) {
if (dlgOpenFile.ShowDialog() != DialogResult.OK) return;
LoadSourceFile(dlgOpenFile.FileName);
}
private void txtSource_TextChanged(object sender, EventArgs e) {
_parseTree = null; //force it to recompile on run
}
private void btnManageGrammars_Click(object sender, EventArgs e) {
menuGrammars.Show(btnManageGrammars, 0, btnManageGrammars.Height);
}
private void btnToXml_Click(object sender, EventArgs e) {
txtOutput.Text = string.Empty;
if (_parseTree == null)
ParseSample();
if (_parseTree == null) return;
txtOutput.Text += _parseTree.ToXml();
txtOutput.Select(0, 0);
tabBottom.SelectedTab = pageOutput;
}
private void cboParseMethod_SelectedIndexChanged(object sender, EventArgs e) {
//changing grammar causes setting of parse method combo, so to prevent double-call to ConstructParser
// we don't do it here if _changingGrammar is set
if (!_changingGrammar)
CreateParser();
}
private void gridParserTrace_CellDoubleClick(object sender, DataGridViewCellEventArgs e) {
if (_parser.Context == null || e.RowIndex < 0 || e.RowIndex >= _parser.Context.ParserTrace.Count) return;
var entry = _parser.Context.ParserTrace[e.RowIndex];
switch (e.ColumnIndex) {
case 0: //state
case 3: //action
LocateParserState(entry.State);
break;
case 1: //stack top
if (entry.StackTop != null)
ShowSourceLocationAndTraceToken(entry.StackTop.Span.Location, entry.StackTop.Span.Length);
break;
case 2: //input
if (entry.Input != null)
ShowSourceLocationAndTraceToken(entry.Input.Span.Location, entry.Input.Span.Length);
break;
}//switch
}
private void lstTokens_Click(object sender, EventArgs e) {
if (lstTokens.SelectedIndex < 0)
return;
Token token = (Token)lstTokens.SelectedItem;
ShowSourceLocation(token.Location, token.Length);
}
private void gridCompileErrors_CellDoubleClick(object sender, DataGridViewCellEventArgs e) {
if (e.RowIndex < 0 || e.RowIndex >= gridCompileErrors.Rows.Count) return;
var err = gridCompileErrors.Rows[e.RowIndex].Cells[1].Value as ParserMessage;
switch (e.ColumnIndex) {
case 0: //state
case 1: //stack top
ShowSourceLocation(err.Location, 1);
break;
case 2: //input
if (err.ParserState != null)
LocateParserState(err.ParserState);
break;
}//switch
}
private void gridGrammarErrors_CellDoubleClick(object sender, DataGridViewCellEventArgs e) {
if (e.RowIndex < 0 || e.RowIndex >= gridGrammarErrors.Rows.Count) return;
var state = gridGrammarErrors.Rows[e.RowIndex].Cells[2].Value as ParserState;
if (state != null)
LocateParserState(state);
}
private void btnSearch_Click(object sender, EventArgs e) {
DoSearch();
}//method
private void txtSearch_KeyPress(object sender, KeyPressEventArgs e) {
if (e.KeyChar == '\r') // <Enter> key
DoSearch();
}
private void lnkShowErrLocation_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
if (_runtimeError != null)
ShowSourceLocation(_runtimeError.Location, 1);
}
private void lnkShowErrStack_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
if (_runtimeError == null) return;
if (_runtimeError.InnerException != null)
fmShowException.ShowException(_runtimeError.InnerException);
else
fmShowException.ShowException(_runtimeError);
}
#endregion
private void chkDisableHili_CheckedChanged(object sender, EventArgs e) {
if (!_loaded) return;
EnableHighligter(!chkDisableHili.Checked);
}
}//class
}
| |
/**
* Author: Jon Maken
* Revision: 12/02/2010 8:41:04 PM
* License: Modified BSD License (3-clause)
*/
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;
namespace XValid
{
/// <summary>
/// XCheck exit codes
/// </summary>
enum ExitCode
{
OK = 0, // XML is well-formed and valid
CmdErr = -1, // incorrect command line invocation
IOErr = -2, // I/O error
ParseErr = -3, // XML parsing error
ValErr = -4, // Validation error
}
internal struct XValidContext
{
internal string xmlFile;
internal string dtdFile;
internal string xmlRoot;
internal string xsdFile;
internal bool error;
public override string ToString()
{
string s = String.Format(
"<#XValidContext => xmlFile:{0}, dtdFile:{1}, xmlRoot:{2}, xsdFile:{3}>",
xmlFile,
dtdFile,
xmlRoot,
xsdFile);
return s;
}
}
/// <summary>
/// <para>Console app that checks if the specified XML file is well formed.
/// If the XML file has an embedded DTD/XSD schema reference or a DTD/XSD
/// schema location is given on the command line, the XML file will be
/// validated against the specified schema.</para>
/// <para>NOTE: only a DTD or an XSD location can be provided as a command
/// line argument; both can not be specified.
/// </para>
/// <example>Example command line invocations:
/// Well-formed? <c>xval test.xml</c>
/// Well-formed and valid (DTD)? <c>xval --dtd valid.dtd RootElement test.xml</c>
/// Well-formed and valid (XSD)? <c>xval --xsd valid.xsd test.xml</c>
/// </example>
/// <returns>simple error message to StdErr and integer exit code.</returns>
/// </summary>
class XValid
{
private static string _VERSION = "0.5.0";
private static XValidContext _context = new XValidContext();
private static int _start;
private static XmlParserContext _parserCtx;
public static int Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine(Usage());
return (int) ExitCode.CmdErr;
}
ParseArgs(args, out _start);
CheckConfig();
// configure the XmlReader for validation
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
if (_context.xsdFile != null)
{
// add specified schema to the reader's XmlSchemaCollection using the
// namespace defined in the targetNamespace attribute of the schema by
// passing null as 1st arg to Add()
XmlSchemaSet sc = new XmlSchemaSet();
sc.Add(null, _context.xsdFile);
settings.ValidationType = ValidationType.Schema;
settings.Schemas = sc;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
}
else if (_context.dtdFile != null)
{
InitParserContext(_context.xmlRoot, _context.dtdFile, out _parserCtx);
}
// validate the files
for (int i = _start; i < args.Length; i++)
{
string f = _context.xmlFile = args[i];
if (!File.Exists(f))
{
Console.WriteLine("File {0} does not exist", f);
continue;
}
Console.WriteLine("Processing {0}...", f);
// TODO replace obsolete XmlValidatingReader with XmlReader?
if (_context.dtdFile != null)
{
using (FileStream s = new FileStream(f, FileMode.Open, FileAccess.Read))
{
using (XmlValidatingReader vr = new XmlValidatingReader(s, XmlNodeType.Document, _parserCtx))
{
vr.ValidationType = ValidationType.Auto;
vr.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
while (vr.Read());
}
}
}
else if (_context.xsdFile != null)
{
using (XmlReader r = XmlReader.Create(f, settings))
while (r.Read());
}
else
{
using (XmlTextReader tr = new XmlTextReader(f))
{
using (XmlValidatingReader vr = new XmlValidatingReader(tr))
{
vr.ValidationType = ValidationType.Auto;
vr.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
while (vr.Read());
}
}
}
}
return (int) ExitCode.OK;
}
private static void ValidationCallback(object sender, ValidationEventArgs e)
{
XmlSchemaException xse = e.Exception;
if (e.Severity == XmlSeverityType.Warning)
{
Console.Error.WriteLine("VALIDATION WARNING:\n[{0}:{1}] {2}",
xse.LineNumber,
xse.LinePosition,
xse.Message);
}
else
{
//valErrFlag = true;
Console.Error.WriteLine("VALIDATION ERROR:\n[{0}:{1}] {2}",
xse.LineNumber,
xse.LinePosition,
xse.Message);
}
}
private static string Usage()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(String.Format("XValid {0} - validate XML documents", _VERSION));
sb.AppendLine("Usage: xval [options] XML_FILE ...\n");
sb.AppendLine("where validation options are:");
sb.AppendLine(" --dtd FILE ROOT validate with DTD FILE at ROOT element");
sb.AppendLine(" --xsd FILE validate with XSD FILE");
return sb.ToString();
}
private static void ParseArgs(string[] args, out int start)
{
int i;
for (i = 0; i < args.Length; i++)
{
if (args[i].Equals("-dtd") || args[i].Equals("--dtd"))
{
i++;
_context.dtdFile = args[i];
i++;
_context.xmlRoot = args[i];
continue;
}
else if (args[i].Equals("-xsd") || args[i].Equals("--xsd"))
{
i++;
_context.xsdFile = args[i];
continue;
}
else break;
}
start = i;
}
private static void CheckConfig()
{
if ((_context.dtdFile != null) && (_context.xsdFile != null))
throw new ArgumentException("choose one of --dtd or --xsd, not both");
if ((_context.dtdFile != null) && (_context.xmlRoot == null))
throw new ArgumentException("must provide both a DTD file and a root XML element");
if ((_context.dtdFile != null) && !File.Exists(_context.dtdFile))
throw new ArgumentException("given DTD file doesn't exist");
if ((_context.xsdFile != null) && !File.Exists(_context.xsdFile))
throw new ArgumentException("given XSD file doesn't exist");
}
// build context for parser in order to validate with the specified DTD
private static void InitParserContext(
string xmlRoot,
string dtdFile,
out XmlParserContext ctx)
{
ctx = new XmlParserContext(
null, // XmlNameTable
null, // XmlNamespaceManager
xmlRoot, // docTypeName
String.Empty, // pubId
dtdFile, // sysId
String.Empty, // internalSubset
String.Empty, // baseURI
String.Empty, // xmlLang
XmlSpace.Default, // xmlSpace
Encoding.UTF8); // Encoding
}
}
}
| |
//-----------------------------------------------------------------------------
// Texture.cs
//
// Spooker Open Source Game Framework
// Copyright (C) Indie Armory. All rights reserved.
// Website: http://indiearmory.com
// Other Contributors: None
// License: MIT
//-----------------------------------------------------------------------------
using System.IO;
namespace Spooker.Graphics
{
/// <summary>
/// Texture.
/// </summary>
public class Texture
{
#region Private fields
private SFML.Graphics.Texture _texture;
private SFML.Graphics.Image _image;
private bool _needsUpdate;
#endregion
#region Properties
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Spooker.Graphics.Texture"/> is smooth.
/// </summary>
/// <value><c>true</c> if smooth; otherwise, <c>false</c>.</value>
public bool Smooth
{
get { return _texture.Smooth; }
set { _texture.Smooth = value; }
}
/// <summary>
/// Gets the size.
/// </summary>
/// <value>The size.</value>
public Vector2 Size
{
get { return new Vector2(_texture.Size.X, _texture.Size.Y); }
}
/// <summary>
/// Gets or sets the array of pixels in the texture in bytes.
/// </summary>
/// <value>The pixels.</value>
public byte[] Pixels {
get { CreateImage(); return _image.Pixels; }
set { _image = new SFML.Graphics.Image((uint)Size.X, (uint)Size.Y, value); Update(); }
}
#endregion
#region SFML Helpers
internal Texture (SFML.Graphics.Texture copy)
{
_texture = new SFML.Graphics.Texture (copy);
}
internal SFML.Graphics.Texture ToSfml()
{
return _texture;
}
#endregion
#region Constructors/Destructors
/// <summary>
/// Initializes a new instance of the <see cref="Spooker.Graphics.Texture"/> class.
/// </summary>
/// <param name="copy">Copy.</param>
public Texture (Texture copy)
{
_texture = new SFML.Graphics.Texture (copy._texture);
}
/// <summary>
/// Initializes a new instance of the <see cref="Spooker.Graphics.Texture"/> class.
/// </summary>
/// <param name="filename">Filename.</param>
public Texture (string filename)
: this(new FileStream(filename, FileMode.Open))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Spooker.Graphics.Texture"/> class.
/// </summary>
/// <param name="stream">Stream.</param>
public Texture (Stream stream)
{
_texture = new SFML.Graphics.Texture (stream);
}
/// <summary>
/// Initializes a new instance of the <see cref="Spooker.Graphics.Texture"/> class.
/// </summary>
/// <param name="pixels">Pixels.</param>
public Texture (Color[,] pixels)
{
var pix = new SFML.Graphics.Color[pixels.GetUpperBound(0),pixels.GetUpperBound(1)];
for (var x = 0; x < pixels.GetUpperBound(0); x++)
{
for (var y = 0; y < pixels.GetUpperBound(1); y++)
{
pix [x, y] = pixels [x, y].ToSfml();
}
}
_texture = new SFML.Graphics.Texture (new SFML.Graphics.Image (pix));
}
/// <summary>
/// Initializes a new instance of the <see cref="Spooker.Graphics.Texture"/> class.
/// </summary>
/// <param name="size">Size.</param>
public Texture (Vector2 size)
{
_texture = new SFML.Graphics.Texture (
(uint)size.X,
(uint)size.Y);
}
/// <summary>
/// Initializes a new instance of the <see cref="Spooker.Graphics.Texture"/> class.
/// </summary>
/// <param name="size">Size.</param>
/// <param name="color">Color.</param>
public Texture (Vector2 size, Color color)
{
_texture = new SFML.Graphics.Texture (
new SFML.Graphics.Image (
(uint)size.X,
(uint)size.Y,
color.ToSfml()));
}
/// <summary>
/// Initializes a new instance of the <see cref="Spooker.Graphics.Texture"/> class.
/// </summary>
/// <param name="size">Size.</param>
/// <param name="pixels">Pixels.</param>
public Texture (Vector2 size, byte[] pixels)
{
_texture = new SFML.Graphics.Texture (
new SFML.Graphics.Image (
(uint)size.X,
(uint)size.Y,
pixels));
}
#endregion
#region Functions
/// <summary>
/// Gets the pixel.
/// </summary>
/// <returns>The pixel.</returns>
/// <param name="x">The x coordinate.</param>
/// <param name="y">The y coordinate.</param>
public Color GetPixel(int x, int y)
{
CreateImage();
return new Color(_image.GetPixel((uint)x, (uint)y));
}
/// <summary>
/// Sets the pixel.
/// </summary>
/// <param name="x">The x coordinate.</param>
/// <param name="y">The y coordinate.</param>
/// <param name="color">Color.</param>
public void SetPixel(int x, int y, Color color)
{
CreateImage();
_image.SetPixel((uint)x, (uint)y, color.ToSfml());
_texture = new SFML.Graphics.Texture(_image);
_needsUpdate = true;
}
/// <summary>
/// Copies the pixels.
/// </summary>
/// <param name="from">From.</param>
/// <param name="fromX">From x.</param>
/// <param name="fromY">From y.</param>
/// <param name="toX">To x.</param>
/// <param name="toY">To y.</param>
public void CopyPixels(Texture from, int fromX, int fromY, int toX, int toY)
{
CreateImage();
_image.Copy(
from._image,
(uint)toX,
(uint)toY,
new SFML.Graphics.IntRect(
fromX,
fromY,
(int)from.Size.X,
(int)from.Size.Y));
}
/// <summary>
/// Saves to file.
/// </summary>
/// <param name="path">Path.</param>
public void SaveToFile(string path)
{
CreateImage();
_image.SaveToFile(path);
}
/// <summary>
/// Creates the image.
/// </summary>
public void CreateImage()
{
if (_image == null)
_image = _texture.CopyToImage();
}
/// <summary>
/// Update this instance.
/// </summary>
public void Update()
{
if (_needsUpdate)
{
_texture.Update(_image);
_needsUpdate = false;
}
}
#endregion
}
}
| |
using Lucene.Net.Analysis.Tokenattributes;
using Lucene.Net.Documents;
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 Lucene.Net.Analysis;
using NUnit.Framework;
using System.Collections.Generic;
using System.IO;
using Directory = Lucene.Net.Store.Directory;
using DirectoryReader = Lucene.Net.Index.DirectoryReader;
using Document = Documents.Document;
using Field = Field;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MultiFields = Lucene.Net.Index.MultiFields;
using OpenMode = Lucene.Net.Index.IndexWriterConfig.OpenMode_e;
using Terms = Lucene.Net.Index.Terms;
[TestFixture]
public class TestTermRangeQuery : LuceneTestCase
{
private int DocCount = 0;
private Directory Dir;
[SetUp]
public override void SetUp()
{
base.SetUp();
Dir = NewDirectory();
}
[TearDown]
public override void TearDown()
{
Dir.Dispose();
base.TearDown();
}
[Test]
public virtual void TestExclusive()
{
Query query = TermRangeQuery.NewStringRange("content", "A", "C", false, false);
InitializeIndex(new string[] { "A", "B", "C", "D" });
IndexReader reader = DirectoryReader.Open(Dir);
IndexSearcher searcher = NewSearcher(reader);
ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length, "A,B,C,D, only B in range");
reader.Dispose();
InitializeIndex(new string[] { "A", "B", "D" });
reader = DirectoryReader.Open(Dir);
searcher = NewSearcher(reader);
hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length, "A,B,D, only B in range");
reader.Dispose();
AddDoc("C");
reader = DirectoryReader.Open(Dir);
searcher = NewSearcher(reader);
hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length, "C added, still only B in range");
reader.Dispose();
}
[Test]
public virtual void TestInclusive()
{
Query query = TermRangeQuery.NewStringRange("content", "A", "C", true, true);
InitializeIndex(new string[] { "A", "B", "C", "D" });
IndexReader reader = DirectoryReader.Open(Dir);
IndexSearcher searcher = NewSearcher(reader);
ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(3, hits.Length, "A,B,C,D - A,B,C in range");
reader.Dispose();
InitializeIndex(new string[] { "A", "B", "D" });
reader = DirectoryReader.Open(Dir);
searcher = NewSearcher(reader);
hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(2, hits.Length, "A,B,D - A and B in range");
reader.Dispose();
AddDoc("C");
reader = DirectoryReader.Open(Dir);
searcher = NewSearcher(reader);
hits = searcher.Search(query, null, 1000).ScoreDocs;
Assert.AreEqual(3, hits.Length, "C added - A, B, C in range");
reader.Dispose();
}
[Test]
public virtual void TestAllDocs()
{
InitializeIndex(new string[] { "A", "B", "C", "D" });
IndexReader reader = DirectoryReader.Open(Dir);
IndexSearcher searcher = NewSearcher(reader);
TermRangeQuery query = new TermRangeQuery("content", null, null, true, true);
Terms terms = MultiFields.GetTerms(searcher.IndexReader, "content");
Assert.IsFalse(query.GetTermsEnum(terms) is TermRangeTermsEnum);
Assert.AreEqual(4, searcher.Search(query, null, 1000).ScoreDocs.Length);
query = new TermRangeQuery("content", null, null, false, false);
Assert.IsFalse(query.GetTermsEnum(terms) is TermRangeTermsEnum);
Assert.AreEqual(4, searcher.Search(query, null, 1000).ScoreDocs.Length);
query = TermRangeQuery.NewStringRange("content", "", null, true, false);
Assert.IsFalse(query.GetTermsEnum(terms) is TermRangeTermsEnum);
Assert.AreEqual(4, searcher.Search(query, null, 1000).ScoreDocs.Length);
// and now anothe one
query = TermRangeQuery.NewStringRange("content", "B", null, true, false);
Assert.IsTrue(query.GetTermsEnum(terms) is TermRangeTermsEnum);
Assert.AreEqual(3, searcher.Search(query, null, 1000).ScoreDocs.Length);
reader.Dispose();
}
/// <summary>
/// this test should not be here, but it tests the fuzzy query rewrite mode (TOP_TERMS_SCORING_BOOLEAN_REWRITE)
/// with constant score and checks, that only the lower end of terms is put into the range
/// </summary>
[Test]
public virtual void TestTopTermsRewrite()
{
InitializeIndex(new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K" });
IndexReader reader = DirectoryReader.Open(Dir);
IndexSearcher searcher = NewSearcher(reader);
TermRangeQuery query = TermRangeQuery.NewStringRange("content", "B", "J", true, true);
CheckBooleanTerms(searcher, query, "B", "C", "D", "E", "F", "G", "H", "I", "J");
int savedClauseCount = BooleanQuery.MaxClauseCount;
try
{
BooleanQuery.MaxClauseCount = 3;
CheckBooleanTerms(searcher, query, "B", "C", "D");
}
finally
{
BooleanQuery.MaxClauseCount = savedClauseCount;
}
reader.Dispose();
}
private void CheckBooleanTerms(IndexSearcher searcher, TermRangeQuery query, params string[] terms)
{
query.SetRewriteMethod(new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(50));
BooleanQuery bq = (BooleanQuery)searcher.Rewrite(query);
var allowedTerms = AsSet(terms);
Assert.AreEqual(allowedTerms.Count, bq.Clauses.Length);
foreach (BooleanClause c in bq.Clauses)
{
Assert.IsTrue(c.Query is TermQuery);
TermQuery tq = (TermQuery)c.Query;
string term = tq.Term.Text();
Assert.IsTrue(allowedTerms.Contains(term), "invalid term: " + term);
allowedTerms.Remove(term); // remove to fail on double terms
}
Assert.AreEqual(0, allowedTerms.Count);
}
[Test]
public virtual void TestEqualsHashcode()
{
Query query = TermRangeQuery.NewStringRange("content", "A", "C", true, true);
query.Boost = 1.0f;
Query other = TermRangeQuery.NewStringRange("content", "A", "C", true, true);
other.Boost = 1.0f;
Assert.AreEqual(query, query, "query equals itself is true");
Assert.AreEqual(query, other, "equivalent queries are equal");
Assert.AreEqual(query.GetHashCode(), other.GetHashCode(), "hashcode must return same value when equals is true");
other.Boost = 2.0f;
Assert.IsFalse(query.Equals(other), "Different boost queries are not equal");
other = TermRangeQuery.NewStringRange("notcontent", "A", "C", true, true);
Assert.IsFalse(query.Equals(other), "Different fields are not equal");
other = TermRangeQuery.NewStringRange("content", "X", "C", true, true);
Assert.IsFalse(query.Equals(other), "Different lower terms are not equal");
other = TermRangeQuery.NewStringRange("content", "A", "Z", true, true);
Assert.IsFalse(query.Equals(other), "Different upper terms are not equal");
query = TermRangeQuery.NewStringRange("content", null, "C", true, true);
other = TermRangeQuery.NewStringRange("content", null, "C", true, true);
Assert.AreEqual(query, other, "equivalent queries with null lowerterms are equal()");
Assert.AreEqual(query.GetHashCode(), other.GetHashCode(), "hashcode must return same value when equals is true");
query = TermRangeQuery.NewStringRange("content", "C", null, true, true);
other = TermRangeQuery.NewStringRange("content", "C", null, true, true);
Assert.AreEqual(query, other, "equivalent queries with null upperterms are equal()");
Assert.AreEqual(query.GetHashCode(), other.GetHashCode(), "hashcode returns same value");
query = TermRangeQuery.NewStringRange("content", null, "C", true, true);
other = TermRangeQuery.NewStringRange("content", "C", null, true, true);
Assert.IsFalse(query.Equals(other), "queries with different upper and lower terms are not equal");
query = TermRangeQuery.NewStringRange("content", "A", "C", false, false);
other = TermRangeQuery.NewStringRange("content", "A", "C", true, true);
Assert.IsFalse(query.Equals(other), "queries with different inclusive are not equal");
}
private class SingleCharAnalyzer : Analyzer
{
private class SingleCharTokenizer : Tokenizer
{
internal char[] Buffer = new char[1];
internal bool Done = false;
internal ICharTermAttribute TermAtt;
public SingleCharTokenizer(TextReader r)
: base(r)
{
TermAtt = AddAttribute<ICharTermAttribute>();
}
public override sealed bool IncrementToken()
{
if (Done)
{
return false;
}
else
{
int count = input.Read(Buffer, 0, Buffer.Length);
ClearAttributes();
Done = true;
if (count == 1)
{
TermAtt.CopyBuffer(Buffer, 0, 1);
}
return true;
}
}
public override void Reset()
{
base.Reset();
Done = false;
}
}
public override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
return new TokenStreamComponents(new SingleCharTokenizer(reader));
}
}
private void InitializeIndex(string[] values)
{
InitializeIndex(values, new MockAnalyzer(Random(), MockTokenizer.WHITESPACE, false));
}
private void InitializeIndex(string[] values, Analyzer analyzer)
{
IndexWriter writer = new IndexWriter(Dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer).SetOpenMode(OpenMode.CREATE));
for (int i = 0; i < values.Length; i++)
{
InsertDoc(writer, values[i]);
}
writer.Dispose();
}
// shouldnt create an analyzer for every doc?
private void AddDoc(string content)
{
IndexWriter writer = new IndexWriter(Dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random(), MockTokenizer.WHITESPACE, false)).SetOpenMode(OpenMode.APPEND));
InsertDoc(writer, content);
writer.Dispose();
}
private void InsertDoc(IndexWriter writer, string content)
{
Document doc = new Document();
doc.Add(NewStringField("id", "id" + DocCount, Field.Store.YES));
doc.Add(NewTextField("content", content, Field.Store.NO));
writer.AddDocument(doc);
DocCount++;
}
// LUCENE-38
[Test]
public virtual void TestExclusiveLowerNull()
{
Analyzer analyzer = new SingleCharAnalyzer();
//http://issues.apache.org/jira/browse/LUCENE-38
Query query = TermRangeQuery.NewStringRange("content", null, "C", false, false);
InitializeIndex(new string[] { "A", "B", "", "C", "D" }, analyzer);
IndexReader reader = DirectoryReader.Open(Dir);
IndexSearcher searcher = NewSearcher(reader);
int numHits = searcher.Search(query, null, 1000).TotalHits;
// When Lucene-38 is fixed, use the assert on the next line:
Assert.AreEqual(3, numHits, "A,B,<empty string>,C,D => A, B & <empty string> are in range");
// until Lucene-38 is fixed, use this assert:
//Assert.AreEqual(2, hits.Length(), "A,B,<empty string>,C,D => A, B & <empty string> are in range");
reader.Dispose();
InitializeIndex(new string[] { "A", "B", "", "D" }, analyzer);
reader = DirectoryReader.Open(Dir);
searcher = NewSearcher(reader);
numHits = searcher.Search(query, null, 1000).TotalHits;
// When Lucene-38 is fixed, use the assert on the next line:
Assert.AreEqual(3, numHits, "A,B,<empty string>,D => A, B & <empty string> are in range");
// until Lucene-38 is fixed, use this assert:
//Assert.AreEqual(2, hits.Length(), "A,B,<empty string>,D => A, B & <empty string> are in range");
reader.Dispose();
AddDoc("C");
reader = DirectoryReader.Open(Dir);
searcher = NewSearcher(reader);
numHits = searcher.Search(query, null, 1000).TotalHits;
// When Lucene-38 is fixed, use the assert on the next line:
Assert.AreEqual(3, numHits, "C added, still A, B & <empty string> are in range");
// until Lucene-38 is fixed, use this assert
//Assert.AreEqual(2, hits.Length(), "C added, still A, B & <empty string> are in range");
reader.Dispose();
}
// LUCENE-38
[Test]
public virtual void TestInclusiveLowerNull()
{
//http://issues.apache.org/jira/browse/LUCENE-38
Analyzer analyzer = new SingleCharAnalyzer();
Query query = TermRangeQuery.NewStringRange("content", null, "C", true, true);
InitializeIndex(new string[] { "A", "B", "", "C", "D" }, analyzer);
IndexReader reader = DirectoryReader.Open(Dir);
IndexSearcher searcher = NewSearcher(reader);
int numHits = searcher.Search(query, null, 1000).TotalHits;
// When Lucene-38 is fixed, use the assert on the next line:
Assert.AreEqual(4, numHits, "A,B,<empty string>,C,D => A,B,<empty string>,C in range");
// until Lucene-38 is fixed, use this assert
//Assert.AreEqual(3, hits.Length(), "A,B,<empty string>,C,D => A,B,<empty string>,C in range");
reader.Dispose();
InitializeIndex(new string[] { "A", "B", "", "D" }, analyzer);
reader = DirectoryReader.Open(Dir);
searcher = NewSearcher(reader);
numHits = searcher.Search(query, null, 1000).TotalHits;
// When Lucene-38 is fixed, use the assert on the next line:
Assert.AreEqual(3, numHits, "A,B,<empty string>,D - A, B and <empty string> in range");
// until Lucene-38 is fixed, use this assert
//Assert.AreEqual(2, hits.Length(), "A,B,<empty string>,D => A, B and <empty string> in range");
reader.Dispose();
AddDoc("C");
reader = DirectoryReader.Open(Dir);
searcher = NewSearcher(reader);
numHits = searcher.Search(query, null, 1000).TotalHits;
// When Lucene-38 is fixed, use the assert on the next line:
Assert.AreEqual(4, numHits, "C added => A,B,<empty string>,C in range");
// until Lucene-38 is fixed, use this assert
//Assert.AreEqual(3, hits.Length(), "C added => A,B,<empty string>,C in range");
reader.Dispose();
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2010-2014 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using NUnit.Framework.Interfaces;
namespace NUnit.Framework.Internal
{
/// <summary>
/// The TestResult class represents the result of a test.
/// </summary>
public abstract class TestResult : 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 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");
/// <summary>
/// List of child results
/// </summary>
private System.Collections.Generic.List<ITestResult> _children;
private StringWriter _outWriter;
private double _duration;
#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)
{
this.Test = test;
this.ResultState = ResultState.Inconclusive;
}
#endregion
#region ITestResult Members
/// <summary>
/// Gets the test with which this result is associated.
/// </summary>
public ITest Test { get; private set; }
/// <summary>
/// Gets the ResultState of the test result, which
/// indicates the success or failure of the test.
/// </summary>
public ResultState ResultState { get; private set; }
/// <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>
/// Gets the message associated with a test
/// failure or with not running the test
/// </summary>
public string Message { get; private set; }
/// <summary>
/// Gets any stacktrace associated with an
/// error or failure.
/// </summary>
public virtual string StackTrace { get; private set; }
/// <summary>
/// Gets or sets the count of asserts executed
/// when running the test.
/// </summary>
public int AssertCount { get; set; }
/// <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 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.
/// Test HasChildren before accessing Children to avoid
/// the creation of an empty collection.
/// </summary>
public bool HasChildren
{
get { return _children != null && _children.Count > 0; }
}
/// <summary>
/// Gets the collection of child results.
/// </summary>
public System.Collections.Generic.IList<ITestResult> Children
{
get
{
if (_children == null)
_children = new System.Collections.Generic.List<ITestResult>();
return _children;
}
}
/// <summary>
/// Gets a TextWriter, which will write output to be included in the result.
/// </summary>
public StringWriter OutWriter
{
get
{
if (_outWriter == null)
_outWriter = new StringWriter();
return _outWriter;
}
}
/// <summary>
/// Gets any text output written to this result.
/// </summary>
public string Output
{
get { return _outWriter == null
? string.Empty
: _outWriter.ToString(); }
}
#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 = this.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 (this.Test is TestSuite)
{
thisNode.AddAttribute("total", (PassCount + FailCount + SkipCount + InconclusiveCount).ToString());
thisNode.AddAttribute("passed", PassCount.ToString());
thisNode.AddAttribute("failed", FailCount.ToString());
thisNode.AddAttribute("inconclusive", InconclusiveCount.ToString());
thisNode.AddAttribute("skipped", SkipCount.ToString());
}
thisNode.AddAttribute("asserts", this.AssertCount.ToString());
switch (ResultState.Status)
{
case TestStatus.Failed:
AddFailureElement(thisNode);
break;
case TestStatus.Skipped:
AddReasonElement(thisNode);
break;
case TestStatus.Passed:
case TestStatus.Inconclusive:
if (this.Message != null)
AddReasonElement(thisNode);
break;
}
if (Output.Length > 0)
AddOutputElement(thisNode);
if (recursive && HasChildren)
foreach (TestResult child in Children)
child.AddToXml(thisNode, recursive);
return thisNode;
}
#endregion
/// <summary>
/// Adds a child result to this result, setting this result's
/// ResultState to Failure if the child result failed.
/// </summary>
/// <param name="result">The result to be added</param>
public virtual void AddResult(ITestResult result)
{
this.Children.Add(result);
//this.AssertCount += result.AssertCount;
// If this result is marked cancelled, don't change it
if (this.ResultState != ResultState.Cancelled)
switch (result.ResultState.Status)
{
case TestStatus.Passed:
if (this.ResultState.Status == TestStatus.Inconclusive)
this.SetResult(ResultState.Success);
break;
case TestStatus.Failed:
if (this.ResultState.Status != TestStatus.Failed)
this.SetResult(ResultState.ChildFailure, CHILD_ERRORS_MESSAGE);
break;
case TestStatus.Skipped:
if (result.ResultState.Label == "Ignored")
if (this.ResultState.Status == TestStatus.Inconclusive || this.ResultState.Status == TestStatus.Passed)
this.SetResult(ResultState.Ignored, CHILD_IGNORE_MESSAGE);
break;
default:
break;
}
}
#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)
{
this.ResultState = resultState;
this.Message = message;
this.StackTrace = stackTrace;
// Set pseudo-counts for a test case
//if (IsTestCase(this.test))
//{
// this.passCount = 0;
// this.failCount = 0;
// this.skipCount = 0;
// this.inconclusiveCount = 0;
// switch (this.ResultState.Status)
// {
// case TestStatus.Passed:
// this.passCount++;
// break;
// case TestStatus.Failed:
// this.failCount++;
// break;
// case TestStatus.Skipped:
// this.skipCount++;
// break;
// default:
// case TestStatus.Inconclusive:
// this.inconclusiveCount++;
// break;
// }
//}
}
/// <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)
{
if (ex is NUnitException)
ex = ex.InnerException;
if (ex is ResultStateException)
SetResult(((ResultStateException)ex).ResultState,
ex.Message,
StackFilter.Filter(ex.StackTrace));
#if !PORTABLE
else if (ex is System.Threading.ThreadAbortException)
SetResult(ResultState.Cancelled,
"Test cancelled by user",
ex.StackTrace);
#endif
else
SetResult(ResultState.Error,
ExceptionHelper.BuildMessage(ex),
ExceptionHelper.BuildStackTrace(ex));
}
/// <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)
{
if (ex is NUnitException)
ex = ex.InnerException;
if (ex is ResultStateException)
SetResult(((ResultStateException)ex).ResultState.WithSite(site),
ex.Message,
StackFilter.Filter(ex.StackTrace));
#if !PORTABLE
else if (ex is System.Threading.ThreadAbortException)
SetResult(ResultState.Cancelled.WithSite(site),
"Test cancelled by user",
ex.StackTrace);
#endif
else
SetResult(ResultState.Error.WithSite(site),
ExceptionHelper.BuildMessage(ex),
ExceptionHelper.BuildStackTrace(ex));
}
/// <summary>
/// RecordTearDownException appends the message and stacktrace
/// 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)
{
if (ex is NUnitException)
ex = ex.InnerException;
ResultState resultState = this.ResultState == ResultState.Cancelled
? ResultState.Cancelled
: ResultState.Error;
if (Test.IsSuite)
resultState = resultState.WithSite(FailureSite.TearDown);
string message = "TearDown : " + ExceptionHelper.BuildMessage(ex);
if (this.Message != null)
message = this.Message + NUnit.Env.NewLine + message;
string stackTrace = "--TearDown" + NUnit.Env.NewLine + ExceptionHelper.BuildStackTrace(ex);
if (this.StackTrace != null)
stackTrace = this.StackTrace + NUnit.Env.NewLine + stackTrace;
SetResult(resultState, message, stackTrace);
}
#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)
failureNode.AddElementWithCDATA("message", Message);
if (StackTrace != null)
failureNode.AddElementWithCDATA("stack-trace", StackTrace);
return failureNode;
}
private TNode AddOutputElement(TNode targetNode)
{
return targetNode.AddElementWithCDATA("output", Output);
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Sql
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ServerKeysOperations.
/// </summary>
public static partial class ServerKeysOperationsExtensions
{
/// <summary>
/// Gets a list of server keys.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
public static IPage<ServerKey> ListByServer(this IServerKeysOperations operations, string resourceGroupName, string serverName)
{
return operations.ListByServerAsync(resourceGroupName, serverName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of server keys.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ServerKey>> ListByServerAsync(this IServerKeysOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByServerWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a server key.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='keyName'>
/// The name of the server key to be retrieved.
/// </param>
public static ServerKey Get(this IServerKeysOperations operations, string resourceGroupName, string serverName, string keyName)
{
return operations.GetAsync(resourceGroupName, serverName, keyName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a server key.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='keyName'>
/// The name of the server key to be retrieved.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ServerKey> GetAsync(this IServerKeysOperations operations, string resourceGroupName, string serverName, string keyName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, serverName, keyName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a server key.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='keyName'>
/// The name of the server key to be operated on (updated or created). The key
/// name is required to be in the format of 'vault_key_version'. For example,
/// if the keyId is
/// https://YourVaultName.vault.azure.net/keys/YourKeyName/01234567890123456789012345678901,
/// then the server key name should be formatted as:
/// YourVaultName_YourKeyName_01234567890123456789012345678901
/// </param>
/// <param name='parameters'>
/// The requested server key resource state.
/// </param>
public static ServerKey CreateOrUpdate(this IServerKeysOperations operations, string resourceGroupName, string serverName, string keyName, ServerKey parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, serverName, keyName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a server key.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='keyName'>
/// The name of the server key to be operated on (updated or created). The key
/// name is required to be in the format of 'vault_key_version'. For example,
/// if the keyId is
/// https://YourVaultName.vault.azure.net/keys/YourKeyName/01234567890123456789012345678901,
/// then the server key name should be formatted as:
/// YourVaultName_YourKeyName_01234567890123456789012345678901
/// </param>
/// <param name='parameters'>
/// The requested server key resource state.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ServerKey> CreateOrUpdateAsync(this IServerKeysOperations operations, string resourceGroupName, string serverName, string keyName, ServerKey parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, keyName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the server key with the given name.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='keyName'>
/// The name of the server key to be deleted.
/// </param>
public static void Delete(this IServerKeysOperations operations, string resourceGroupName, string serverName, string keyName)
{
operations.DeleteAsync(resourceGroupName, serverName, keyName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the server key with the given name.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='keyName'>
/// The name of the server key to be deleted.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IServerKeysOperations operations, string resourceGroupName, string serverName, string keyName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, serverName, keyName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates or updates a server key.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='keyName'>
/// The name of the server key to be operated on (updated or created). The key
/// name is required to be in the format of 'vault_key_version'. For example,
/// if the keyId is
/// https://YourVaultName.vault.azure.net/keys/YourKeyName/01234567890123456789012345678901,
/// then the server key name should be formatted as:
/// YourVaultName_YourKeyName_01234567890123456789012345678901
/// </param>
/// <param name='parameters'>
/// The requested server key resource state.
/// </param>
public static ServerKey BeginCreateOrUpdate(this IServerKeysOperations operations, string resourceGroupName, string serverName, string keyName, ServerKey parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, serverName, keyName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a server key.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='keyName'>
/// The name of the server key to be operated on (updated or created). The key
/// name is required to be in the format of 'vault_key_version'. For example,
/// if the keyId is
/// https://YourVaultName.vault.azure.net/keys/YourKeyName/01234567890123456789012345678901,
/// then the server key name should be formatted as:
/// YourVaultName_YourKeyName_01234567890123456789012345678901
/// </param>
/// <param name='parameters'>
/// The requested server key resource state.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ServerKey> BeginCreateOrUpdateAsync(this IServerKeysOperations operations, string resourceGroupName, string serverName, string keyName, ServerKey parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, keyName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the server key with the given name.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='keyName'>
/// The name of the server key to be deleted.
/// </param>
public static void BeginDelete(this IServerKeysOperations operations, string resourceGroupName, string serverName, string keyName)
{
operations.BeginDeleteAsync(resourceGroupName, serverName, keyName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the server key with the given name.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='keyName'>
/// The name of the server key to be deleted.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IServerKeysOperations operations, string resourceGroupName, string serverName, string keyName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, serverName, keyName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets a list of server keys.
/// </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<ServerKey> ListByServerNext(this IServerKeysOperations operations, string nextPageLink)
{
return operations.ListByServerNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of server keys.
/// </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<ServerKey>> ListByServerNextAsync(this IServerKeysOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByServerNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Cci;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Roslyn.Utilities;
using System.Collections.Immutable;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed class EEAssemblyBuilder : PEAssemblyBuilderBase
{
private readonly ImmutableHashSet<MethodSymbol> _methods;
public EEAssemblyBuilder(
SourceAssemblySymbol sourceAssembly,
EmitOptions emitOptions,
ImmutableArray<MethodSymbol> methods,
ModulePropertiesForSerialization serializationProperties,
ImmutableArray<NamedTypeSymbol> additionalTypes,
CompilationTestData testData) :
base(
sourceAssembly,
emitOptions,
outputKind: OutputKind.DynamicallyLinkedLibrary,
serializationProperties: serializationProperties,
manifestResources: SpecializedCollections.EmptyEnumerable<ResourceDescription>(),
assemblySymbolMapper: null,
additionalTypes: additionalTypes)
{
_methods = ImmutableHashSet.CreateRange(methods);
if (testData != null)
{
this.SetMethodTestData(testData.Methods);
testData.Module = this;
}
}
protected override IModuleReference TranslateModule(ModuleSymbol symbol, DiagnosticBag diagnostics)
{
var moduleSymbol = symbol as PEModuleSymbol;
if ((object)moduleSymbol != null)
{
var module = moduleSymbol.Module;
// Expose the individual runtime Windows.*.winmd modules as assemblies.
// (The modules were wrapped in a placeholder Windows.winmd assembly
// in MetadataUtilities.MakeAssemblyReferences.)
if (MetadataUtilities.IsWindowsComponent(module.MetadataReader, module.Name) &&
MetadataUtilities.IsWindowsAssemblyName(moduleSymbol.ContainingAssembly.Name))
{
var identity = module.ReadAssemblyIdentityOrThrow();
return new Microsoft.CodeAnalysis.ExpressionEvaluator.AssemblyReference(identity);
}
}
return base.TranslateModule(symbol, diagnostics);
}
public override int CurrentGenerationOrdinal => 0;
internal override VariableSlotAllocator TryCreateVariableSlotAllocator(MethodSymbol symbol)
{
var method = symbol as EEMethodSymbol;
if (((object)method != null) && _methods.Contains(method))
{
var defs = GetLocalDefinitions(method.Locals);
return new SlotAllocator(defs);
}
Debug.Assert(!_methods.Contains(symbol));
return null;
}
private static ImmutableArray<LocalDefinition> GetLocalDefinitions(ImmutableArray<LocalSymbol> locals)
{
var builder = ArrayBuilder<LocalDefinition>.GetInstance();
foreach (var local in locals)
{
if (local.DeclarationKind == LocalDeclarationKind.Constant)
{
continue;
}
var def = ToLocalDefinition(local, builder.Count);
Debug.Assert(((EELocalSymbol)local).Ordinal == def.SlotIndex);
builder.Add(def);
}
return builder.ToImmutableAndFree();
}
private static LocalDefinition ToLocalDefinition(LocalSymbol local, int index)
{
// See EvaluationContext.GetLocals.
TypeSymbol type;
LocalSlotConstraints constraints;
if (local.DeclarationKind == LocalDeclarationKind.FixedVariable)
{
type = ((PointerTypeSymbol)local.Type).PointedAtType;
constraints = LocalSlotConstraints.ByRef | LocalSlotConstraints.Pinned;
}
else
{
type = local.Type;
constraints = (local.IsPinned ? LocalSlotConstraints.Pinned : LocalSlotConstraints.None) |
((local.RefKind == RefKind.None) ? LocalSlotConstraints.None : LocalSlotConstraints.ByRef);
}
return new LocalDefinition(
local,
local.Name,
(Cci.ITypeReference)type,
slot: index,
synthesizedKind: (SynthesizedLocalKind)local.SynthesizedKind,
id: LocalDebugId.None,
pdbAttributes: Cci.PdbWriter.DefaultLocalAttributesValue,
constraints: constraints,
isDynamic: false,
dynamicTransformFlags: ImmutableArray<TypedConstant>.Empty);
}
private sealed class SlotAllocator : VariableSlotAllocator
{
private readonly ImmutableArray<LocalDefinition> _locals;
internal SlotAllocator(ImmutableArray<LocalDefinition> locals)
{
_locals = locals;
}
public override void AddPreviousLocals(ArrayBuilder<Cci.ILocalDefinition> builder)
{
builder.AddRange(_locals);
}
public override LocalDefinition GetPreviousLocal(
Cci.ITypeReference type,
ILocalSymbolInternal symbol,
string nameOpt,
SynthesizedLocalKind synthesizedKind,
LocalDebugId id,
uint pdbAttributes,
LocalSlotConstraints constraints,
bool isDynamic,
ImmutableArray<TypedConstant> dynamicTransformFlags)
{
var local = symbol as EELocalSymbol;
if ((object)local == null)
{
return null;
}
return _locals[local.Ordinal];
}
public override string PreviousStateMachineTypeName
{
get { return null; }
}
public override bool TryGetPreviousHoistedLocalSlotIndex(SyntaxNode currentDeclarator, Cci.ITypeReference currentType, SynthesizedLocalKind synthesizedKind, LocalDebugId currentId, out int slotIndex)
{
slotIndex = -1;
return false;
}
public override int PreviousHoistedLocalSlotCount
{
get { return 0; }
}
public override bool TryGetPreviousAwaiterSlotIndex(Cci.ITypeReference currentType, out int slotIndex)
{
slotIndex = -1;
return false;
}
public override bool TryGetPreviousClosure(SyntaxNode closureSyntax, out int closureOrdinal)
{
closureOrdinal = -1;
return false;
}
public override bool TryGetPreviousLambda(SyntaxNode lambdaOrLambdaBodySyntax, bool isLambdaBody, out int lambdaOrdinal)
{
lambdaOrdinal = -1;
return false;
}
public override int PreviousAwaiterSlotCount
{
get { return 0; }
}
public override MethodDebugId PreviousMethodId
{
get
{
return default(MethodDebugId);
}
}
}
}
}
| |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.2
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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.Runtime.InteropServices;
using UnityEngine;
/// <summary>
/// OVRGamepadController is an interface class to a gamepad controller.
/// </summary>
public class OVRGamepadController : MonoBehaviour
{
/// <summary> An axis on the gamepad. </summary>
public enum Axis
{
None = -1,
LeftXAxis = 0,
LeftYAxis,
RightXAxis,
RightYAxis,
LeftTrigger,
RightTrigger,
DPad_X_Axis,
DPad_Y_Axis,
Max,
};
/// <summary> A button on the gamepad. </summary>
public enum Button
{
None = -1,
A = 0,
B,
X,
Y,
Up,
Down,
Left,
Right,
Start,
Back,
LStick,
RStick,
LeftShoulder,
RightShoulder,
Max
};
/// <summary>
/// The default Android Unity input name for each gamepad Axis.
/// </summary>
public static string[] AndroidAxisNames = new string[(int)Axis.Max]
{
"Left_X_Axis",
"Left_Y_Axis",
"Right_X_Axis",
"Right_Y_Axis",
"LeftTrigger",
"RightTrigger",
"DPad_X_Axis",
"DPad_Y_Axis",
};
/// <summary>
/// The default Android Unity input name for each gamepad Button.
/// </summary>
public static string[] AndroidButtonNames = new string[(int)Button.Max]
{
"Button A",
"Button B",
"Button X",
"Button Y",
"Up",
"Down",
"Left",
"Right",
"Start",
"Back",
"LStick",
"RStick",
"LeftShoulder",
"RightShoulder",
};
/// <summary>
/// The default Unity input name for each gamepad Axis.
/// </summary>
public static string[] DesktopAxisNames = new string[(int)Axis.Max]
{
"Desktop_Left_X_Axis",
"Desktop_Left_Y_Axis",
"Desktop_Right_X_Axis",
"Desktop_Right_Y_Axis",
"Desktop_LeftTrigger",
"Desktop_RightTrigger",
"Desktop_DPad_X_Axis",
"Desktop_DPad_Y_Axis",
};
/// <summary>
/// The default Unity input name for each gamepad Button.
/// </summary>
public static string[] DesktopButtonNames = new string[(int)Button.Max]
{
"Desktop_Button A",
"Desktop_Button B",
"Desktop_Button X",
"Desktop_Button Y",
"Desktop_Up",
"Desktop_Down",
"Desktop_Left",
"Desktop_Right",
"Desktop_Start",
"Desktop_Back",
"Desktop_LStick",
"Desktop_RStick",
"Desktop_LeftShoulder",
"Desktop_RightShoulder",
};
public static int[] DefaultButtonIds = new int[(int)Button.Max]
{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13
};
private static bool[] ButtonDownLastFrame = new bool[(int)Button.Max];
/// <summary>
/// The current Unity input names for all gamepad axes.
/// </summary>
public static string[] AxisNames = null;
/// <summary>
/// The current Unity input names for all gamepad buttons.
/// </summary>
public static string[] ButtonNames = null;
#if !UNITY_ANDROID || UNITY_EDITOR
private static int lastGPCRefresh = 0;
private static bool isMapped = true;
#endif
static OVRGamepadController()
{
#if UNITY_ANDROID && !UNITY_EDITOR
SetAxisNames(AndroidAxisNames);
SetButtonNames(AndroidButtonNames);
#else
SetAxisNames(DesktopAxisNames);
SetButtonNames(DesktopButtonNames);
#endif
}
/// <summary>
/// Sets the current names for all gamepad axes.
/// </summary>
public static void SetAxisNames(string[] axisNames)
{
AxisNames = axisNames;
}
/// <summary>
/// Sets the current Unity input names for all gamepad buttons.
/// </summary>
/// <param name="buttonNames">Button names.</param>
public static void SetButtonNames(string[] buttonNames)
{
ButtonNames = buttonNames;
}
/// <summary> Handles an axis read event. </summary>
public delegate float ReadAxisDelegate(Axis axis);
/// <summary> Handles an button read event. </summary>
public delegate bool ReadButtonDelegate(Button button);
/// <summary> Occurs when an axis has been read. </summary>
public static ReadAxisDelegate ReadAxis = DefaultReadAxis;
/// <summary> Occurs when a button has been read. </summary>
public static ReadButtonDelegate ReadButton = DefaultReadButton;
#if (!UNITY_ANDROID || UNITY_EDITOR)
private static bool GPC_Available = false;
//-------------------------
// Public access to plugin functions
/// <summary>
/// GPC_Initialize.
/// </summary>
/// <returns><c>true</c>, if c_ initialize was GPed, <c>false</c> otherwise.</returns>
public static bool GPC_Initialize()
{
if (!OVRManager.instance.isSupportedPlatform)
return false;
return OVR_GamepadController_Initialize();
}
/// <summary>
/// GPC_Destroy
/// </summary>
/// <returns><c>true</c>, if c_ destroy was GPed, <c>false</c> otherwise.</returns>
public static bool GPC_Destroy()
{
if (!OVRManager.instance.isSupportedPlatform)
return false;
return OVR_GamepadController_Destroy();
}
/// <summary>
/// GPC_Update
/// </summary>
/// <returns><c>true</c>, if c_ update was GPed, <c>false</c> otherwise.</returns>
public static bool GPC_Update()
{
lastGPCRefresh = Time.frameCount;
if (!OVRManager.instance.isSupportedPlatform)
return false;
return OVR_GamepadController_Update();
}
#endif
static void GPC_LateUpdate()
{
if (!OVRManager.instance.isSupportedPlatform)
return;
for (int i = 0; i < (int)Button.Max; i++)
{
ButtonDownLastFrame[i] = GPC_GetButton((Button)i);
}
}
/// <summary>
/// GPC_GetAxis
/// The default delegate for retrieving axis info.
/// </summary>
/// <returns>The current value of the axis.</returns>
/// <param name="axis">Axis.</param>
public static float DefaultReadAxis(Axis axis)
{
#if UNITY_ANDROID && !UNITY_EDITOR
return Input.GetAxis(AxisNames[(int)axis]);
#else
float xinputValue = OVR_GamepadController_GetAxis((int)axis);
float unityValue = 0f;
if (isMapped)
{
try { unityValue = Input.GetAxis(AxisNames[(int)axis]); }
catch { isMapped = false; }
}
return Mathf.Abs(xinputValue) > Mathf.Abs(unityValue) ? xinputValue : unityValue;
#endif
}
/// <summary>
/// Returns the current value of the given Axis.
/// </summary>
public static float GPC_GetAxis(Axis axis)
{
if (ReadAxis == null)
return 0f;
return ReadAxis(axis);
}
public static void SetReadAxisDelegate(ReadAxisDelegate del)
{
ReadAxis = del;
}
/// <summary>
/// Uses XInput to check if the given Button is down.
/// </summary>
public static bool DefaultReadButton(Button button)
{
#if UNITY_ANDROID && !UNITY_EDITOR
return Input.GetButton(ButtonNames[(int)button]);
#else
if (Time.frameCount != lastGPCRefresh)
{
GPC_Update();
}
bool unityValue = false;
if (isMapped)
{
try { unityValue = Input.GetButton(ButtonNames[(int)button]); }
catch { isMapped = false; }
}
return OVR_GamepadController_GetButton((int)button) || unityValue;
#endif
}
/// <summary>
/// Returns true if the given Button is down.
/// </summary>
public static bool GPC_GetButton(Button button)
{
if (ReadButton == null)
return false;
return ReadButton(button);
}
/// <summary>
/// Returns true if the given Button was pressed this frame.
/// </summary>
public static bool GPC_GetButtonDown(Button button)
{
if (ReadButton == null)
return false;
return ReadButton(button) && !ButtonDownLastFrame[(int)button];
}
/// <summary>
/// Returns true if the given Button was released this frame.
/// </summary>
public static bool GPC_GetButtonUp(Button button)
{
if (ReadButton == null)
return false;
return !ReadButton(button) && ButtonDownLastFrame[(int)button];
}
public static void SetReadButtonDelegate(ReadButtonDelegate del)
{
ReadButton = del;
}
/// <summary>
/// Returns true if the gamepad controller is available.
/// </summary>
public static bool GPC_IsAvailable()
{
#if !UNITY_ANDROID || UNITY_EDITOR
return GPC_Available;
#else
return true;
#endif
}
void GPC_Test()
{
// Axis test
Debug.Log(string.Format("LT:{0:F3} RT:{1:F3} LX:{2:F3} LY:{3:F3} RX:{4:F3} RY:{5:F3}",
GPC_GetAxis(Axis.LeftTrigger), GPC_GetAxis(Axis.RightTrigger),
GPC_GetAxis(Axis.LeftXAxis), GPC_GetAxis(Axis.LeftYAxis),
GPC_GetAxis(Axis.RightXAxis), GPC_GetAxis(Axis.RightYAxis)));
// Button test
Debug.Log(string.Format("A:{0} B:{1} X:{2} Y:{3} U:{4} D:{5} L:{6} R:{7} SRT:{8} BK:{9} LS:{10} RS:{11} L1:{12} R1:{13}",
GPC_GetButton(Button.A), GPC_GetButton(Button.B),
GPC_GetButton(Button.X), GPC_GetButton(Button.Y),
GPC_GetButton(Button.Up), GPC_GetButton(Button.Down),
GPC_GetButton(Button.Left), GPC_GetButton(Button.Right),
GPC_GetButton(Button.Start), GPC_GetButton(Button.Back),
GPC_GetButton(Button.LStick), GPC_GetButton(Button.RStick),
GPC_GetButton(Button.LeftShoulder), GPC_GetButton(Button.RightShoulder)));
}
#if !UNITY_ANDROID || UNITY_EDITOR
void Start()
{
GPC_Available = GPC_Initialize();
}
void Update()
{
if (lastGPCRefresh < Time.frameCount)
{
GPC_Available = GPC_Update();
}
}
void OnDestroy()
{
GPC_Destroy();
GPC_Available = false;
}
public const string DllName = "OVRGamepad";
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern bool OVR_GamepadController_Initialize();
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern bool OVR_GamepadController_Destroy();
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern bool OVR_GamepadController_Update();
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern float OVR_GamepadController_GetAxis(int axis);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern bool OVR_GamepadController_GetButton(int button);
#endif
void LateUpdate()
{
GPC_LateUpdate();
}
}
| |
using System;
using System.Collections.Generic;
using NUnit.Framework;
namespace Axon.Collections
{
[TestFixture]
public class ConcurrentBinaryMinHeapTest
{
#region Instance members
[Test]
public void PropertyCapacity()
{
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>( 15 );
// Ensure that Capacity reports 15.
Assert.That( heap.Capacity, Is.EqualTo( 15 ) );
// Intentionally over-fill the queue to force it to resize.
for ( int i = 0; i < 16; i++ )
{
heap.Push( 1f, 1 );
}
// Ensure that Capacity is now greater than 15.
Assert.That( heap.Capacity, Is.GreaterThan( 15 ) );
}
[Test]
public void PropertyCount()
{
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>();
// Ensure that Count reports 0.
Assert.That( heap.Count, Is.EqualTo( 0 ) );
// Enqueue 3 elements in the queue.
heap.Push( 1f, 1 );
heap.Push( 3f, 3 );
heap.Push( 2f, 2 );
// Ensure that Count now reports 3.
Assert.That( heap.Count, Is.EqualTo( 3 ) );
}
[Test]
public void PropertyIsEmpty()
{
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>();
// Ensure that IsEmpty reports TRUE.
Assert.That( heap.IsEmpty, Is.True );
// Enqueue an element in the queue.
heap.Push( 1f, 1 );
// Ensure that IsEmpty now reports FALSE.
Assert.That( heap.IsEmpty, Is.False );
}
[Test]
public void PropertyIsReadOnly()
{
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>();
// Ensure that IsReadOnly always reports FALSE.
Assert.That( heap.IsReadOnly, Is.False );
}
#endregion
#region Constructors
[Test]
public void ConstructorParameterless()
{
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>();
// Nothing to test here. The following explicitly passes this test:
Assert.That( true, Is.True );
}
[Test]
public void ConstructorInitialSize()
{
// Try to create a heap with a negative initial size and expect an
// ArgumentOutOfRangeException to be thrown.
Assert.Throws<ArgumentOutOfRangeException>( () => {
new ConcurrentBinaryMinHeap<int>( -10 );
} );
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>( 15 );
// Ensure that Capacity reports 15.
Assert.That( heap.Capacity, Is.EqualTo( 15 ) );
}
#endregion
#region Public API
[Test]
public void Add() {
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>();
// Ensure that the heap is empty.
Assert.That( heap.Count, Is.EqualTo( 0 ) );
// Call Add() to insert a new element to the queue as a PriorityValuePair.
heap.Add( new PriorityValuePair<int>( 1f, 2 ) );
// Expect a value of 2 on the first item to be removed after adding it.
Assert.That( heap.PopValue(), Is.EqualTo( 2 ) );
}
[Test]
public void Clear() {
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>();
// Push 3 elements onto the heap.
heap.Push( 1f, 2 );
heap.Push( 3f, 6 );
heap.Push( 2f, 4 );
// Ensure that 3 elements have been added to the heap.
Assert.That( heap.Count, Is.EqualTo( 3 ) );
// Clear the heap.
heap.Clear();
// Ensure that all of the elements have been removed.
Assert.That( heap.Count, Is.EqualTo( 0 ) );
}
[Test]
public void Contains() {
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>();
// Create and store a new element.
PriorityValuePair<int> elem = new PriorityValuePair<int>( 1f, 2 );
// Ensure the queue contains the element.
Assert.That( heap.Contains( elem ), Is.False );
// Push it onto the heap.
heap.Push( elem );
// Ensure the queue now contains the element.
Assert.That( heap.Contains( elem ), Is.True );
}
[Test]
public void CopyTo()
{
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>();
// Create a new array of size 5.
PriorityValuePair<int>[] arrayCopy = new PriorityValuePair<int>[ 5 ];
// Push 3 elements onto the queue.
PriorityValuePair<int> elem = new PriorityValuePair<int>( 3f, 6 );
heap.Push( 1f, 2 );
heap.Push( elem );
heap.Push( 2f, 4 );
// Copy the heap data to the array, starting from index 1 (not 0).
heap.CopyTo( arrayCopy, 1 );
// Expect the first array index to be unset, but all the rest to be set.
// Note: The order of elements after the first can't be guaranteed, because the heap
// doesn't store things in an exact linear order, but we can be sure that the elements
// aren't going to be equal to null because we set them.
Assert.That( arrayCopy[ 0 ], Is.EqualTo( null ) );
Assert.That( arrayCopy[ 1 ], Is.EqualTo( elem ) );
Assert.That( arrayCopy[ 2 ], Is.Not.EqualTo( null ) );
Assert.That( arrayCopy[ 3 ], Is.Not.EqualTo( null ) );
Assert.That( arrayCopy[ 4 ], Is.EqualTo( null ) );
}
[Test]
public void GetEnumerator()
{
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>();
// Enqueue a few elements in the queue.
heap.Push( 1f, 2 );
heap.Push( 3f, 6 );
heap.Push( 2f, 4 );
// Use the enumerator of heap (using disposes it when we're finished).
using ( IEnumerator< PriorityValuePair<int> > enumerator = heap.GetEnumerator() )
{
// Expect the first element to have the highest priority, and expect MoveNext() to
// return true until the last element. After the end of the heap is reached, it
// then returns false.
// Note: Since the heap doesn't guarantee the order of elements after the first, we
// can only be certain of the root element and after that we really can't be sure
// of the order -- just the length.
Assert.That( enumerator.MoveNext(), Is.True );
Assert.That( enumerator.Current.Value, Is.EqualTo( 6 ) );
Assert.That( enumerator.MoveNext(), Is.True );
Assert.That( enumerator.MoveNext(), Is.True );
Assert.That( enumerator.MoveNext(), Is.False );
}
}
[Test]
public void Peek()
{
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>();
// Ensure that the heap is empty.
Assert.That( heap.Count, Is.EqualTo( 0 ) );
// Expect Peek() to return null for an empty heap.
Assert.That( heap.Peek(), Is.EqualTo( null ) );
// Ensure that the heap is empty.
Assert.That( heap.Count, Is.EqualTo( 0 ) );
// Store an element and insert it into the heap.
PriorityValuePair<int> elem1 = new PriorityValuePair<int>( 1f, 2 );
heap.Push( elem1 );
// Ensure that the element was inserted into the heap as the root element.
Assert.That( heap.Count, Is.EqualTo( 1 ) );
Assert.That( heap.Peek(), Is.EqualTo( elem1 ) );
// Ensure that the element was not removed from the heap.
Assert.That( heap.Count, Is.EqualTo( 1 ) );
// Insert another element with higher priority than the last.
PriorityValuePair<int> elem2 = new PriorityValuePair<int>( 2f, 4 );
heap.Push( elem2 );
// Ensure that Peak() returns the new root element.
Assert.That( heap.Peek(), Is.EqualTo( elem2 ) );
}
[Test]
public void PeekPriority()
{
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>();
// Ensure that the heap is empty.
Assert.That( heap.Count, Is.EqualTo( 0 ) );
// Try to PeekPriority() and expect an NullReferenceException to be thrown.
Assert.Throws<NullReferenceException>( () => {
heap.PeekPriority();
} );
// Ensure that the heap is empty.
Assert.That( heap.Count, Is.EqualTo( 0 ) );
// Store an element and insert it into the heap.
PriorityValuePair<int> elem = new PriorityValuePair<int>( 1f, 2 );
heap.Push( elem );
// Ensure that the element was inserted into the heap.
Assert.That( heap.Count, Is.EqualTo( 1 ) );
Assert.That( heap.Peek(), Is.EqualTo( elem ) );
// Ensure that the priority of the pushed element is returned.
Assert.That( heap.PeekPriority(), Is.EqualTo( 1f ) );
// Ensure that the element was not removed from the heap.
Assert.That( heap.Count, Is.EqualTo( 1 ) );
}
[Test]
public void PeekValue()
{
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>();
// Ensure that the heap is empty.
Assert.That( heap.Count, Is.EqualTo( 0 ) );
// Try to PeekValue() and expect an NullReferenceException to be thrown.
Assert.Throws<NullReferenceException>( () => {
heap.PeekValue();
} );
// Ensure that the heap is empty.
Assert.That( heap.Count, Is.EqualTo( 0 ) );
// Store an element and insert it into the heap.
PriorityValuePair<int> elem = new PriorityValuePair<int>( 1f, 2 );
heap.Push( elem );
// Ensure that the element was inserted into the heap.
Assert.That( heap.Count, Is.EqualTo( 1 ) );
Assert.That( heap.Peek(), Is.EqualTo( elem ) );
// Ensure that the priority of the pushed element is returned.
Assert.That( heap.PeekValue(), Is.EqualTo( 2 ) );
// Ensure that the element was not removed from the heap.
Assert.That( heap.Count, Is.EqualTo( 1 ) );
}
[Test]
public void Pop()
{
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>();
// Ensure that the heap is empty.
Assert.That( heap.Count, Is.EqualTo( 0 ) );
// Expect Pop() to return null for an empty heap.
Assert.That( heap.Pop(), Is.EqualTo( null ) );
// Ensure that the heap is empty.
Assert.That( heap.Count, Is.EqualTo( 0 ) );
// Ensure that the heap is empty.
Assert.That( heap.Count, Is.EqualTo( 0 ) );
// Store an element and insert it into the heap.
PriorityValuePair<int> elem = new PriorityValuePair<int>( 1f, 2 );
heap.Push( elem );
// Ensure that the element was inserted into the heap.
Assert.That( heap.Count, Is.EqualTo( 1 ) );
Assert.That( heap.Peek(), Is.EqualTo( elem ) );
// Ensure that the returned element points to the same object we stored earlier.
Assert.That( heap.Pop(), Is.EqualTo( elem ) );
// Ensure that the element was removed from the heap.
Assert.That( heap.Count, Is.EqualTo( 0 ) );
}
[Test]
public void PopPriority()
{
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>();
// Ensure that the heap is empty.
Assert.That( heap.Count, Is.EqualTo( 0 ) );
// Try to PopPriority() and expect an NullReferenceException to be thrown.
Assert.Throws<NullReferenceException>( () => {
heap.PopPriority();
} );
// Ensure that the heap is empty.
Assert.That( heap.Count, Is.EqualTo( 0 ) );
// Store an element and insert it into the heap.
PriorityValuePair<int> elem = new PriorityValuePair<int>( 1f, 2 );
heap.Push( elem );
// Ensure that the element was inserted into the heap.
Assert.That( heap.Peek(), Is.EqualTo( elem ) );
// Ensure that the priority of the pushed element is returned.
Assert.That( heap.PopPriority(), Is.EqualTo( 1f ) );
// Ensure that the element was removed from the heap.
Assert.That( heap.Count, Is.EqualTo( 0 ) );
}
[Test]
public void PopValue()
{
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>();
// Ensure that the heap is empty.
Assert.That( heap.Count, Is.EqualTo( 0 ) );
// Try to PopPriority() and expect an NullReferenceException to be thrown.
Assert.Throws<NullReferenceException>( () => {
heap.PopValue();
} );
// Ensure that the heap is empty.
Assert.That( heap.Count, Is.EqualTo( 0 ) );
// Store an element and insert it into the heap.
PriorityValuePair<int> elem = new PriorityValuePair<int>( 1f, 2 );
heap.Push( elem );
// Ensure that the element was inserted into the heap.
Assert.That( heap.Peek(), Is.EqualTo( elem ) );
// Ensure that the value of the pushed element is returned.
Assert.That( heap.PopValue(), Is.EqualTo( 2 ) );
// Ensure that the element was removed from the heap.
Assert.That( heap.Count, Is.EqualTo( 0 ) );
}
[Test]
public void PushElement()
{
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>();
// Ensure that the heap is empty.
Assert.That( heap.Count, Is.EqualTo( 0 ) );
// Store an element and insert it into the heap.
PriorityValuePair<int> elem = new PriorityValuePair<int>( 1f, 2 );
heap.Push( elem );
// Ensure that the element was inserted into the heap.
Assert.That( heap.Peek(), Is.EqualTo( elem ) );
// Store another element with higher priority and insert it as well.
elem = new PriorityValuePair<int>( 2f, 4 );
heap.Push( elem );
// Ensure that the element was inserted into the queue and is at the root.
Assert.That( heap.Peek(), Is.EqualTo( elem ) );
}
[Test]
public void PushPriorityValue()
{
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>();
// Ensure that heap is empty.
Assert.That( heap.Count, Is.EqualTo( 0 ) );
// Store an element and insert it into the heap.
heap.Push( 1f, 2 );
// Ensure that the element was inserted into the heap.
Assert.That( heap.PeekValue(), Is.EqualTo( 2 ) );
// Store another element with higher priority and insert it as well.
heap.Push( 2f, 4 );
// Ensure that the element was inserted into the heap.
Assert.That( heap.PeekValue(), Is.EqualTo( 4 ) );
}
[Test]
public void Remove() {
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>();
// Create and store a few elements.
PriorityValuePair<int> elem1 = new PriorityValuePair<int>( 1f, 2 );
PriorityValuePair<int> elem2 = new PriorityValuePair<int>( 2f, 4 );
PriorityValuePair<int> elem3 = new PriorityValuePair<int>( 3f, 6 );
// Expect Remove() to return null for an empty heap.
Assert.That( heap.Remove( elem1 ), Is.EqualTo( false ) );
// Insert 2 of the elements into the heap.
heap.Push( elem2 );
heap.Push( elem3 );
// Expect Remove() to return false for elem1, indicating the element was removed
// (since it doesn't belong to the heap and can't be found). This tests the if-else
// case for when the provided element isn't found in the heap.
Assert.That( heap.Remove( elem1 ), Is.False );
// Expect Remove() to return true for elem2, indicating the element was removed
// (since it belongs to the heap and can be found). This tests the if-else case for
// when Count is 2 or greater.
Assert.That( heap.Remove( elem2 ), Is.True );
// Expect Remove() to return true for elem3, indicating the element was removed
// (since it belongs to the heap and can be found). This tests the if-else case for
// when Count equals 1.
Assert.That( heap.Remove( elem3 ), Is.True );
}
#endregion
#if DEBUG
#region Private methods (these are testable as public methods in DEBUG builds)
[Test]
public void SwapElements()
{
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>();
// Enqueue an element into the queue.
var elem1 = new PriorityValuePair<int>( 2f, 4 );
heap.Push( elem1 );
// Ensure that the element was inserted.
Assert.That( heap.Count, Is.EqualTo( 1 ) );
Assert.That( heap.Peek(), Is.EqualTo( elem1 ) );
// Try to HeapSwapElements() while the queue only contains 1 element and expect an
// InvalidOperationException to be thrown.
Assert.Throws<InvalidOperationException>( () => {
heap.SwapElements( 0, 1 );
} );
// Enqueue another element with higher priority than the last.
var elem2 = new PriorityValuePair<int>( 1f, 2 );
heap.Push( elem2 );
// Ensure that the element was inserted and that the 1st (higher priority) element is
// still at the root of the heap.
Assert.That( heap.Count, Is.EqualTo( 2 ) );
Assert.That( heap.Peek(), Is.EqualTo( elem1 ) );
// Try to HeapSwapElements() with an invalid index1 and expect an
// ArgumentOutOfRangeException to be thrown.
Assert.Throws<ArgumentOutOfRangeException>( () => {
heap.SwapElements( -1, 1 );
} );
// Try to HeapSwapElements() with an invalid index2 and expect an
// ArgumentOutOfRangeException to be thrown.
Assert.Throws<ArgumentOutOfRangeException>( () => {
heap.SwapElements( 0, -1 );
} );
// Actually swap elements now.
heap.SwapElements( 0, 1 );
// Ensure that the elements were swapped.
Assert.That( heap.Count, Is.EqualTo( 2 ) );
Assert.That( heap.Peek(), Is.EqualTo( elem2 ) );
Assert.That( heap.Contains( elem1 ), Is.True );
}
[Test]
[Ignore]
public void HeapifyBottomUp()
{
// TODO The HeapifyBottomUp() test is incomplete.
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>();
// Execute several HeapifyBottomUp()s to test different tree operations on the heap.
var index = 0;
heap.HeapifyBottomUp( index );
}
[Test]
[Ignore]
public void HeapifyTopDown()
{
// TODO The HeapifyTopDown() test is incomplete.
// Create a new heap.
ConcurrentBinaryMinHeap<int> heap = new ConcurrentBinaryMinHeap<int>();
// Execute several HeapifyBottomUp()s to test different tree operations on the heap.
var index = 0;
heap.HeapifyTopDown( index );
}
#endregion
#endif
}
}
| |
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 Control.Center.Areas.HelpPage.ModelDescriptions;
using Control.Center.Areas.HelpPage.Models;
namespace Control.Center.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);
}
}
}
}
| |
namespace android.media
{
[global::MonoJavaBridge.JavaClass()]
public partial class AudioManager : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static AudioManager()
{
InitJNI();
}
protected AudioManager(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.media.AudioManager.OnAudioFocusChangeListener_))]
public interface OnAudioFocusChangeListener : global::MonoJavaBridge.IJavaObject
{
void onAudioFocusChange(int arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.media.AudioManager.OnAudioFocusChangeListener))]
public sealed partial class OnAudioFocusChangeListener_ : java.lang.Object, OnAudioFocusChangeListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnAudioFocusChangeListener_()
{
InitJNI();
}
internal OnAudioFocusChangeListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onAudioFocusChange4824;
void android.media.AudioManager.OnAudioFocusChangeListener.onAudioFocusChange(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager.OnAudioFocusChangeListener_._onAudioFocusChange4824, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.OnAudioFocusChangeListener_.staticClass, global::android.media.AudioManager.OnAudioFocusChangeListener_._onAudioFocusChange4824, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.media.AudioManager.OnAudioFocusChangeListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/media/AudioManager$OnAudioFocusChangeListener"));
global::android.media.AudioManager.OnAudioFocusChangeListener_._onAudioFocusChange4824 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.OnAudioFocusChangeListener_.staticClass, "onAudioFocusChange", "(I)V");
}
}
internal static global::MonoJavaBridge.MethodId _getParameters4825;
public virtual global::java.lang.String getParameters(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.media.AudioManager._getParameters4825, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._getParameters4825, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _setMode4826;
public virtual void setMode(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._setMode4826, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._setMode4826, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getMode4827;
public virtual int getMode()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioManager._getMode4827);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._getMode4827);
}
internal static global::MonoJavaBridge.MethodId _playSoundEffect4828;
public virtual void playSoundEffect(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._playSoundEffect4828, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._playSoundEffect4828, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _playSoundEffect4829;
public virtual void playSoundEffect(int arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._playSoundEffect4829, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._playSoundEffect4829, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setParameters4830;
public virtual void setParameters(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._setParameters4830, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._setParameters4830, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _adjustStreamVolume4831;
public virtual void adjustStreamVolume(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._adjustStreamVolume4831, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._adjustStreamVolume4831, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _adjustVolume4832;
public virtual void adjustVolume(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._adjustVolume4832, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._adjustVolume4832, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _adjustSuggestedStreamVolume4833;
public virtual void adjustSuggestedStreamVolume(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._adjustSuggestedStreamVolume4833, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._adjustSuggestedStreamVolume4833, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _getRingerMode4834;
public virtual int getRingerMode()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioManager._getRingerMode4834);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._getRingerMode4834);
}
internal static global::MonoJavaBridge.MethodId _getStreamMaxVolume4835;
public virtual int getStreamMaxVolume(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioManager._getStreamMaxVolume4835, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._getStreamMaxVolume4835, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getStreamVolume4836;
public virtual int getStreamVolume(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioManager._getStreamVolume4836, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._getStreamVolume4836, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setRingerMode4837;
public virtual void setRingerMode(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._setRingerMode4837, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._setRingerMode4837, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setStreamVolume4838;
public virtual void setStreamVolume(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._setStreamVolume4838, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._setStreamVolume4838, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _setStreamSolo4839;
public virtual void setStreamSolo(int arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._setStreamSolo4839, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._setStreamSolo4839, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setStreamMute4840;
public virtual void setStreamMute(int arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._setStreamMute4840, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._setStreamMute4840, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _shouldVibrate4841;
public virtual bool shouldVibrate(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.media.AudioManager._shouldVibrate4841, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._shouldVibrate4841, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getVibrateSetting4842;
public virtual int getVibrateSetting(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioManager._getVibrateSetting4842, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._getVibrateSetting4842, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setVibrateSetting4843;
public virtual void setVibrateSetting(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._setVibrateSetting4843, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._setVibrateSetting4843, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setSpeakerphoneOn4844;
public virtual void setSpeakerphoneOn(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._setSpeakerphoneOn4844, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._setSpeakerphoneOn4844, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isSpeakerphoneOn4845;
public virtual bool isSpeakerphoneOn()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.media.AudioManager._isSpeakerphoneOn4845);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._isSpeakerphoneOn4845);
}
internal static global::MonoJavaBridge.MethodId _isBluetoothScoAvailableOffCall4846;
public virtual bool isBluetoothScoAvailableOffCall()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.media.AudioManager._isBluetoothScoAvailableOffCall4846);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._isBluetoothScoAvailableOffCall4846);
}
internal static global::MonoJavaBridge.MethodId _startBluetoothSco4847;
public virtual void startBluetoothSco()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._startBluetoothSco4847);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._startBluetoothSco4847);
}
internal static global::MonoJavaBridge.MethodId _stopBluetoothSco4848;
public virtual void stopBluetoothSco()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._stopBluetoothSco4848);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._stopBluetoothSco4848);
}
internal static global::MonoJavaBridge.MethodId _setBluetoothScoOn4849;
public virtual void setBluetoothScoOn(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._setBluetoothScoOn4849, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._setBluetoothScoOn4849, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isBluetoothScoOn4850;
public virtual bool isBluetoothScoOn()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.media.AudioManager._isBluetoothScoOn4850);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._isBluetoothScoOn4850);
}
internal static global::MonoJavaBridge.MethodId _setBluetoothA2dpOn4851;
public virtual void setBluetoothA2dpOn(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._setBluetoothA2dpOn4851, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._setBluetoothA2dpOn4851, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isBluetoothA2dpOn4852;
public virtual bool isBluetoothA2dpOn()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.media.AudioManager._isBluetoothA2dpOn4852);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._isBluetoothA2dpOn4852);
}
internal static global::MonoJavaBridge.MethodId _setWiredHeadsetOn4853;
public virtual void setWiredHeadsetOn(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._setWiredHeadsetOn4853, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._setWiredHeadsetOn4853, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isWiredHeadsetOn4854;
public virtual bool isWiredHeadsetOn()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.media.AudioManager._isWiredHeadsetOn4854);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._isWiredHeadsetOn4854);
}
internal static global::MonoJavaBridge.MethodId _setMicrophoneMute4855;
public virtual void setMicrophoneMute(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._setMicrophoneMute4855, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._setMicrophoneMute4855, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isMicrophoneMute4856;
public virtual bool isMicrophoneMute()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.media.AudioManager._isMicrophoneMute4856);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._isMicrophoneMute4856);
}
internal static global::MonoJavaBridge.MethodId _setRouting4857;
public virtual void setRouting(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._setRouting4857, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._setRouting4857, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _getRouting4858;
public virtual int getRouting(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioManager._getRouting4858, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._getRouting4858, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isMusicActive4859;
public virtual bool isMusicActive()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.media.AudioManager._isMusicActive4859);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._isMusicActive4859);
}
internal static global::MonoJavaBridge.MethodId _loadSoundEffects4860;
public virtual void loadSoundEffects()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._loadSoundEffects4860);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._loadSoundEffects4860);
}
internal static global::MonoJavaBridge.MethodId _unloadSoundEffects4861;
public virtual void unloadSoundEffects()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._unloadSoundEffects4861);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._unloadSoundEffects4861);
}
internal static global::MonoJavaBridge.MethodId _requestAudioFocus4862;
public virtual int requestAudioFocus(android.media.AudioManager.OnAudioFocusChangeListener arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioManager._requestAudioFocus4862, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._requestAudioFocus4862, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _abandonAudioFocus4863;
public virtual int abandonAudioFocus(android.media.AudioManager.OnAudioFocusChangeListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioManager._abandonAudioFocus4863, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._abandonAudioFocus4863, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _registerMediaButtonEventReceiver4864;
public virtual void registerMediaButtonEventReceiver(android.content.ComponentName arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._registerMediaButtonEventReceiver4864, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._registerMediaButtonEventReceiver4864, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _unregisterMediaButtonEventReceiver4865;
public virtual void unregisterMediaButtonEventReceiver(android.content.ComponentName arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioManager._unregisterMediaButtonEventReceiver4865, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioManager.staticClass, global::android.media.AudioManager._unregisterMediaButtonEventReceiver4865, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public static global::java.lang.String ACTION_AUDIO_BECOMING_NOISY
{
get
{
return "android.media.AUDIO_BECOMING_NOISY";
}
}
public static global::java.lang.String RINGER_MODE_CHANGED_ACTION
{
get
{
return "android.media.RINGER_MODE_CHANGED";
}
}
public static global::java.lang.String EXTRA_RINGER_MODE
{
get
{
return "android.media.EXTRA_RINGER_MODE";
}
}
public static global::java.lang.String VIBRATE_SETTING_CHANGED_ACTION
{
get
{
return "android.media.VIBRATE_SETTING_CHANGED";
}
}
public static global::java.lang.String EXTRA_VIBRATE_SETTING
{
get
{
return "android.media.EXTRA_VIBRATE_SETTING";
}
}
public static global::java.lang.String EXTRA_VIBRATE_TYPE
{
get
{
return "android.media.EXTRA_VIBRATE_TYPE";
}
}
public static int STREAM_VOICE_CALL
{
get
{
return 0;
}
}
public static int STREAM_SYSTEM
{
get
{
return 1;
}
}
public static int STREAM_RING
{
get
{
return 2;
}
}
public static int STREAM_MUSIC
{
get
{
return 3;
}
}
public static int STREAM_ALARM
{
get
{
return 4;
}
}
public static int STREAM_NOTIFICATION
{
get
{
return 5;
}
}
public static int STREAM_DTMF
{
get
{
return 8;
}
}
public static int NUM_STREAMS
{
get
{
return 5;
}
}
public static int ADJUST_RAISE
{
get
{
return 1;
}
}
public static int ADJUST_LOWER
{
get
{
return -1;
}
}
public static int ADJUST_SAME
{
get
{
return 0;
}
}
public static int FLAG_SHOW_UI
{
get
{
return 1;
}
}
public static int FLAG_ALLOW_RINGER_MODES
{
get
{
return 2;
}
}
public static int FLAG_PLAY_SOUND
{
get
{
return 4;
}
}
public static int FLAG_REMOVE_SOUND_AND_VIBRATE
{
get
{
return 8;
}
}
public static int FLAG_VIBRATE
{
get
{
return 16;
}
}
public static int RINGER_MODE_SILENT
{
get
{
return 0;
}
}
public static int RINGER_MODE_VIBRATE
{
get
{
return 1;
}
}
public static int RINGER_MODE_NORMAL
{
get
{
return 2;
}
}
public static int VIBRATE_TYPE_RINGER
{
get
{
return 0;
}
}
public static int VIBRATE_TYPE_NOTIFICATION
{
get
{
return 1;
}
}
public static int VIBRATE_SETTING_OFF
{
get
{
return 0;
}
}
public static int VIBRATE_SETTING_ON
{
get
{
return 1;
}
}
public static int VIBRATE_SETTING_ONLY_SILENT
{
get
{
return 2;
}
}
public static int USE_DEFAULT_STREAM_TYPE
{
get
{
return -2147483648;
}
}
public static global::java.lang.String ACTION_SCO_AUDIO_STATE_CHANGED
{
get
{
return "android.media.SCO_AUDIO_STATE_CHANGED";
}
}
public static global::java.lang.String EXTRA_SCO_AUDIO_STATE
{
get
{
return "android.media.extra.SCO_AUDIO_STATE";
}
}
public static int SCO_AUDIO_STATE_DISCONNECTED
{
get
{
return 0;
}
}
public static int SCO_AUDIO_STATE_CONNECTED
{
get
{
return 1;
}
}
public static int SCO_AUDIO_STATE_ERROR
{
get
{
return -1;
}
}
public static int MODE_INVALID
{
get
{
return -2;
}
}
public static int MODE_CURRENT
{
get
{
return -1;
}
}
public static int MODE_NORMAL
{
get
{
return 0;
}
}
public static int MODE_RINGTONE
{
get
{
return 1;
}
}
public static int MODE_IN_CALL
{
get
{
return 2;
}
}
public static int ROUTE_EARPIECE
{
get
{
return 1;
}
}
public static int ROUTE_SPEAKER
{
get
{
return 2;
}
}
public static int ROUTE_BLUETOOTH
{
get
{
return 4;
}
}
public static int ROUTE_BLUETOOTH_SCO
{
get
{
return 4;
}
}
public static int ROUTE_HEADSET
{
get
{
return 8;
}
}
public static int ROUTE_BLUETOOTH_A2DP
{
get
{
return 16;
}
}
public static int ROUTE_ALL
{
get
{
return -1;
}
}
public static int FX_KEY_CLICK
{
get
{
return 0;
}
}
public static int FX_FOCUS_NAVIGATION_UP
{
get
{
return 1;
}
}
public static int FX_FOCUS_NAVIGATION_DOWN
{
get
{
return 2;
}
}
public static int FX_FOCUS_NAVIGATION_LEFT
{
get
{
return 3;
}
}
public static int FX_FOCUS_NAVIGATION_RIGHT
{
get
{
return 4;
}
}
public static int FX_KEYPRESS_STANDARD
{
get
{
return 5;
}
}
public static int FX_KEYPRESS_SPACEBAR
{
get
{
return 6;
}
}
public static int FX_KEYPRESS_DELETE
{
get
{
return 7;
}
}
public static int FX_KEYPRESS_RETURN
{
get
{
return 8;
}
}
public static int AUDIOFOCUS_GAIN
{
get
{
return 1;
}
}
public static int AUDIOFOCUS_GAIN_TRANSIENT
{
get
{
return 2;
}
}
public static int AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK
{
get
{
return 3;
}
}
public static int AUDIOFOCUS_LOSS
{
get
{
return -1;
}
}
public static int AUDIOFOCUS_LOSS_TRANSIENT
{
get
{
return -2;
}
}
public static int AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK
{
get
{
return -3;
}
}
public static int AUDIOFOCUS_REQUEST_FAILED
{
get
{
return 0;
}
}
public static int AUDIOFOCUS_REQUEST_GRANTED
{
get
{
return 1;
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.media.AudioManager.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/media/AudioManager"));
global::android.media.AudioManager._getParameters4825 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "getParameters", "(Ljava/lang/String;)Ljava/lang/String;");
global::android.media.AudioManager._setMode4826 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "setMode", "(I)V");
global::android.media.AudioManager._getMode4827 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "getMode", "()I");
global::android.media.AudioManager._playSoundEffect4828 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "playSoundEffect", "(I)V");
global::android.media.AudioManager._playSoundEffect4829 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "playSoundEffect", "(IF)V");
global::android.media.AudioManager._setParameters4830 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "setParameters", "(Ljava/lang/String;)V");
global::android.media.AudioManager._adjustStreamVolume4831 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "adjustStreamVolume", "(III)V");
global::android.media.AudioManager._adjustVolume4832 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "adjustVolume", "(II)V");
global::android.media.AudioManager._adjustSuggestedStreamVolume4833 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "adjustSuggestedStreamVolume", "(III)V");
global::android.media.AudioManager._getRingerMode4834 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "getRingerMode", "()I");
global::android.media.AudioManager._getStreamMaxVolume4835 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "getStreamMaxVolume", "(I)I");
global::android.media.AudioManager._getStreamVolume4836 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "getStreamVolume", "(I)I");
global::android.media.AudioManager._setRingerMode4837 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "setRingerMode", "(I)V");
global::android.media.AudioManager._setStreamVolume4838 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "setStreamVolume", "(III)V");
global::android.media.AudioManager._setStreamSolo4839 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "setStreamSolo", "(IZ)V");
global::android.media.AudioManager._setStreamMute4840 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "setStreamMute", "(IZ)V");
global::android.media.AudioManager._shouldVibrate4841 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "shouldVibrate", "(I)Z");
global::android.media.AudioManager._getVibrateSetting4842 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "getVibrateSetting", "(I)I");
global::android.media.AudioManager._setVibrateSetting4843 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "setVibrateSetting", "(II)V");
global::android.media.AudioManager._setSpeakerphoneOn4844 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "setSpeakerphoneOn", "(Z)V");
global::android.media.AudioManager._isSpeakerphoneOn4845 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "isSpeakerphoneOn", "()Z");
global::android.media.AudioManager._isBluetoothScoAvailableOffCall4846 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "isBluetoothScoAvailableOffCall", "()Z");
global::android.media.AudioManager._startBluetoothSco4847 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "startBluetoothSco", "()V");
global::android.media.AudioManager._stopBluetoothSco4848 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "stopBluetoothSco", "()V");
global::android.media.AudioManager._setBluetoothScoOn4849 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "setBluetoothScoOn", "(Z)V");
global::android.media.AudioManager._isBluetoothScoOn4850 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "isBluetoothScoOn", "()Z");
global::android.media.AudioManager._setBluetoothA2dpOn4851 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "setBluetoothA2dpOn", "(Z)V");
global::android.media.AudioManager._isBluetoothA2dpOn4852 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "isBluetoothA2dpOn", "()Z");
global::android.media.AudioManager._setWiredHeadsetOn4853 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "setWiredHeadsetOn", "(Z)V");
global::android.media.AudioManager._isWiredHeadsetOn4854 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "isWiredHeadsetOn", "()Z");
global::android.media.AudioManager._setMicrophoneMute4855 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "setMicrophoneMute", "(Z)V");
global::android.media.AudioManager._isMicrophoneMute4856 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "isMicrophoneMute", "()Z");
global::android.media.AudioManager._setRouting4857 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "setRouting", "(III)V");
global::android.media.AudioManager._getRouting4858 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "getRouting", "(I)I");
global::android.media.AudioManager._isMusicActive4859 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "isMusicActive", "()Z");
global::android.media.AudioManager._loadSoundEffects4860 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "loadSoundEffects", "()V");
global::android.media.AudioManager._unloadSoundEffects4861 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "unloadSoundEffects", "()V");
global::android.media.AudioManager._requestAudioFocus4862 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "requestAudioFocus", "(Landroid/media/AudioManager$OnAudioFocusChangeListener;II)I");
global::android.media.AudioManager._abandonAudioFocus4863 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "abandonAudioFocus", "(Landroid/media/AudioManager$OnAudioFocusChangeListener;)I");
global::android.media.AudioManager._registerMediaButtonEventReceiver4864 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "registerMediaButtonEventReceiver", "(Landroid/content/ComponentName;)V");
global::android.media.AudioManager._unregisterMediaButtonEventReceiver4865 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.staticClass, "unregisterMediaButtonEventReceiver", "(Landroid/content/ComponentName;)V");
}
}
}
| |
// Copyright 2017 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using Android.App;
using Android.OS;
using Android.Widget;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
namespace ArcGISRuntimeXamarin.Samples.FindRoute
{
[Activity(Label = "FindRoute")]
public class FindRoute : Activity
{
private MapView _myMapView = new MapView();
// List of stops on the route ('from' and 'to')
private List<Stop> _routeStops;
// Graphics overlay to display stops and the route result
private GraphicsOverlay _routeGraphicsOverlay;
// URI for the San Diego route service
private Uri _sanDiegoRouteServiceUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route");
// URIs for picture marker images
private Uri _checkedFlagIconUri = new Uri("https://static.arcgis.com/images/Symbols/Transportation/CheckeredFlag.png");
private Uri _carIconUri = new Uri("https://static.arcgis.com/images/Symbols/Transportation/CarRedFront.png");
// UI control to show/hide directions dialog (private scope so it can be enabled/disabled as needed)
private Button _showHideDirectionsButton;
// Dialog for showing driving directions
private AlertDialog _directionsDialog;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Title = "Find a route";
// Create the UI
CreateLayout();
// Initialize the app
Initialize();
}
private void CreateLayout()
{
// Create a new layout for the entire page
var layout = new LinearLayout(this) { Orientation = Orientation.Vertical };
// Create a new layout for the toolbar (buttons)
var toolbar = new LinearLayout(this) { Orientation = Orientation.Horizontal };
// Create a button to solve the route and add it to the toolbar
var solveRouteButton = new Button(this) { Text = "Solve Route" };
solveRouteButton.Click += SolveRouteClick;
toolbar.AddView(solveRouteButton);
// Create a button to reset the route display, add it to the toolbar
var resetButton = new Button(this) { Text = "Reset" };
resetButton.Click += ResetClick;
toolbar.AddView(resetButton);
// Create a button to show or hide the route directions, add it to the toolbar
_showHideDirectionsButton = new Button(this) { Text = "Directions" };
_showHideDirectionsButton.Click += ShowDirectionsClick;
_showHideDirectionsButton.Enabled = false;
toolbar.AddView(_showHideDirectionsButton);
// Add the toolbar to the layout
layout.AddView(toolbar);
// Add the map view to the layout
layout.AddView(_myMapView);
// Show the layout in the app
SetContentView(layout);
}
private void Initialize()
{
// Define the route stop locations (points)
MapPoint fromPoint = new MapPoint(-117.15494348793044, 32.706506537686927, SpatialReferences.Wgs84);
MapPoint toPoint = new MapPoint(-117.14905088669816, 32.735308180609138, SpatialReferences.Wgs84);
// Create Stop objects with the points and add them to a list of stops
Stop stop1 = new Stop(fromPoint);
Stop stop2 = new Stop(toPoint);
_routeStops = new List<Stop> { stop1, stop2 };
// Picture marker symbols: from = car, to = checkered flag
PictureMarkerSymbol carSymbol = new PictureMarkerSymbol(_carIconUri);
PictureMarkerSymbol flagSymbol = new PictureMarkerSymbol(_checkedFlagIconUri);
// Add a slight offset (pixels) to the picture symbols
carSymbol.OffsetX = -20;
flagSymbol.OffsetY = -5;
// Create graphics for the stops
Graphic fromGraphic = new Graphic(fromPoint, carSymbol);
Graphic toGraphic = new Graphic(toPoint, flagSymbol);
// Create the graphics overlay and add the stop graphics
_routeGraphicsOverlay = new GraphicsOverlay();
_routeGraphicsOverlay.Graphics.Add(fromGraphic);
_routeGraphicsOverlay.Graphics.Add(toGraphic);
// Get an Envelope that covers the area of the stops (and a little more)
Envelope routeStopsExtent = new Envelope(fromPoint, toPoint);
EnvelopeBuilder envBuilder = new EnvelopeBuilder(routeStopsExtent);
envBuilder.Expand(1.5);
// Create a new viewpoint apply it to the map view when the spatial reference changes
Viewpoint sanDiegoViewpoint = new Viewpoint(envBuilder.ToGeometry());
_myMapView.SpatialReferenceChanged += (s, e) => _myMapView.SetViewpoint(sanDiegoViewpoint);
// Add a new Map and the graphics overlay to the map view
_myMapView.Map = new Map(Basemap.CreateStreets());
_myMapView.GraphicsOverlays.Add(_routeGraphicsOverlay);
}
private async void SolveRouteClick(object sender, EventArgs e)
{
// Create a new route task using the San Diego route service URI
RouteTask solveRouteTask = await RouteTask.CreateAsync(_sanDiegoRouteServiceUri);
// Get the default parameters from the route task (defined with the service)
RouteParameters routeParams = await solveRouteTask.CreateDefaultParametersAsync();
// Make some changes to the default parameters
routeParams.ReturnStops = true;
routeParams.ReturnDirections = true;
// Set the list of route stops that were defined at startup
routeParams.SetStops(_routeStops);
// Solve for the best route between the stops and store the result
RouteResult solveRouteResult = await solveRouteTask.SolveRouteAsync(routeParams);
// Get the first (should be only) route from the result
Route firstRoute = solveRouteResult.Routes.FirstOrDefault();
// Get the route geometry (polyline)
Polyline routePolyline = firstRoute.RouteGeometry;
// Create a thick purple line symbol for the route
SimpleLineSymbol routeSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Purple, 8.0);
// Create a new graphic for the route geometry and add it to the graphics overlay
Graphic routeGraphic = new Graphic(routePolyline, routeSymbol);
_routeGraphicsOverlay.Graphics.Add(routeGraphic);
// Get a list of directions for the route and display it in the list box
var directions = from d in firstRoute.DirectionManeuvers select d.DirectionText;
CreateDirectionsDialog(directions);
_showHideDirectionsButton.Enabled = true;
}
private void ResetClick(object sender, EventArgs e)
{
// Remove the route graphic from the graphics overlay (only line graphic in the collection)
int graphicsCount = _routeGraphicsOverlay.Graphics.Count;
for (var i = graphicsCount; i > 0; i--)
{
// Get this graphic and see if it has line geometry
Graphic g = _routeGraphicsOverlay.Graphics[i - 1];
if (g.Geometry.GeometryType == GeometryType.Polyline)
{
// Remove the graphic from the overlay
_routeGraphicsOverlay.Graphics.Remove(g);
}
}
// Disable the button to show the directions dialog
_showHideDirectionsButton.Enabled = false;
}
private void ShowDirectionsClick(object sender, EventArgs e)
{
// Show the directions dialog
if (_directionsDialog != null)
{
_directionsDialog.Show();
}
}
private void CreateDirectionsDialog(IEnumerable<string> directions)
{
// Create a dialog to show route directions
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// Create the layout
LinearLayout dialogLayout = new LinearLayout(this);
dialogLayout.Orientation = Orientation.Vertical;
// Create a list box for showing the route directions
var directionsList = new ListView(this);
var directionsAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, directions.ToArray());
directionsList.Adapter = directionsAdapter;
dialogLayout.AddView(directionsList);
// Add the controls to the dialog
dialogBuilder.SetView(dialogLayout);
dialogBuilder.SetTitle("Route Directions");
// Create the dialog (don't show it)
_directionsDialog = dialogBuilder.Create();
}
}
}
| |
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Common;
using Common.Messages;
using Common.TableModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Queue;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json;
using WebHook.Model;
namespace WebHook
{
public static class WebHookFunction
{
[FunctionName("WebHookFunction")]
public static Task<IActionResult> Hook(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "hook")]HttpRequestMessage req,
ILogger logger)
{
var storageAccount = CloudStorageAccount.Parse(KnownEnvironmentVariables.AzureWebJobsStorage);
var routerQueue = storageAccount.CreateCloudQueueClient().GetQueueReference("routermessage");
var openPrQueue = storageAccount.CreateCloudQueueClient().GetQueueReference("openprmessage");
var deleteBranchMessages = storageAccount.CreateCloudQueueClient().GetQueueReference("deletebranchmessage");
var installationTable = storageAccount.CreateCloudTableClient().GetTableReference("installation");
var marketplaceTable = storageAccount.CreateCloudTableClient().GetTableReference("marketplace");
return Run(req, routerQueue, openPrQueue, deleteBranchMessages, installationTable, marketplaceTable, logger);
}
public static async Task<IActionResult> Run(
HttpRequestMessage req,
CloudQueue routerMessages,
CloudQueue openPrMessages,
CloudQueue deleteBranchMessages,
CloudTable installationTable,
CloudTable marketplaceTable,
ILogger logger)
{
var hookEvent = req.Headers.GetValues("X-GitHub-Event").First();
var hook = JsonConvert.DeserializeObject<Hook>(await req.Content.ReadAsStringAsync());
var result = "no action";
switch (hookEvent)
{
case "installation_repositories":
case "installation":
result = await ProcessInstallationAsync(hook, marketplaceTable, routerMessages, installationTable, logger).ConfigureAwait(false);
break;
case "push":
result = await ProcessPushAsync(hook, marketplaceTable, routerMessages, openPrMessages, deleteBranchMessages, logger).ConfigureAwait(false);
break;
case "marketplace_purchase":
result = await ProcessMarketplacePurchaseAsync(hook, marketplaceTable, logger).ConfigureAwait(false);
break;
}
return new OkObjectResult(new HookResponse { Result = result });
}
private static async Task<string> ProcessPushAsync(
Hook hook,
CloudTable marketplaceTable,
CloudQueue routerMessages,
CloudQueue openPrMessages,
CloudQueue deleteBranchMessages,
ILogger logger)
{
// private check
if (hook.repository?.@private == true)
{
var isPrivateEligible = await IsPrivateEligible(marketplaceTable, hook.repository.owner.login);
if (!isPrivateEligible)
{
logger.LogError("ProcessPush: Plan mismatch for {Owner}/{RepoName}", hook.repository.owner.login, hook.repository.name);
throw new Exception("Plan mismatch");
}
}
// push to imgbot branch by imgbot
if (hook.@ref == $"refs/heads/{KnownGitHubs.BranchName}" && hook.sender.login == "imgbot[bot]")
{
await openPrMessages.AddMessageAsync(new CloudQueueMessage(JsonConvert.SerializeObject(new OpenPrMessage
{
InstallationId = hook.installation.id,
RepoName = hook.repository.name,
CloneUrl = $"https://github.com/{hook.repository.full_name}",
})));
logger.LogInformation("ProcessPush: Added OpenPrMessage for {Owner}/{RepoName}", hook.repository.owner.login, hook.repository.name);
return "imgbot push";
}
// push to non-default branch
if (hook.@ref != $"refs/heads/{hook.repository.default_branch}")
{
return "Commit to non default branch";
}
// merge commit to default branch from imgbot branch
if (IsDefaultWebMerge(hook))
{
await deleteBranchMessages.AddMessageAsync(new CloudQueueMessage(JsonConvert.SerializeObject(new DeleteBranchMessage
{
InstallationId = hook.installation.id,
RepoName = hook.repository.name,
Owner = hook.repository.owner.login,
CloneUrl = $"https://github.com/{hook.repository.full_name}",
})));
return "deleteit";
}
// regular commit to default branch
var relevantFiles = hook.commits.SelectMany(x => x.added)
.Concat(hook.commits.SelectMany(x => x.modified));
var imageFiles = relevantFiles.Where(file => KnownImgPatterns.ImgExtensions.Any(extension => file.ToLower().EndsWith(extension, StringComparison.Ordinal)));
var configFile = relevantFiles.Where(file => file.ToLower() == ".imgbotconfig");
if (!imageFiles.Any() && !configFile.Any())
{
return "No relevant files touched";
}
await routerMessages.AddMessageAsync(new CloudQueueMessage(JsonConvert.SerializeObject(new RouterMessage
{
InstallationId = hook.installation.id,
Owner = hook.repository.owner.login,
RepoName = hook.repository.name,
CloneUrl = $"https://github.com/{hook.repository.full_name}",
})));
logger.LogInformation("ProcessPush: Added RouterMessage for {Owner}/{RepoName}", hook.repository.owner.login, hook.repository.name);
return "truth";
}
private static async Task<string> ProcessInstallationAsync(Hook hook, CloudTable marketplaceTable, CloudQueue routerMessages, CloudTable installationTable, ILogger logger)
{
var isPrivateEligible = false;
if (hook.repositories?.Any(x => x.@private) == true || hook.repositories_added?.Any(x => x.@private) == true)
{
isPrivateEligible = await IsPrivateEligible(marketplaceTable, hook.installation.account.login);
}
switch (hook.action)
{
case "created":
foreach (var repo in hook.repositories)
{
if (repo.@private && !isPrivateEligible)
{
logger.LogError("ProcessInstallationAsync/added: Plan mismatch for {Owner}/{RepoName}", hook.installation.account.login, repo.name);
continue;
}
await routerMessages.AddMessageAsync(new CloudQueueMessage(JsonConvert.SerializeObject(new RouterMessage
{
InstallationId = hook.installation.id,
Owner = hook.installation.account.login,
RepoName = repo.name,
CloneUrl = $"https://github.com/{repo.full_name}",
})));
logger.LogInformation("ProcessInstallationAsync/created: Added RouterMessage for {Owner}/{RepoName}", hook.installation.account.login, repo.name);
}
break;
case "added":
foreach (var repo in hook.repositories_added)
{
if (repo.@private && !isPrivateEligible)
{
logger.LogError("ProcessInstallationAsync/added: Plan mismatch for {Owner}/{RepoName}", hook.installation.account.login, repo.name);
continue;
}
await routerMessages.AddMessageAsync(new CloudQueueMessage(JsonConvert.SerializeObject(new RouterMessage
{
InstallationId = hook.installation.id,
Owner = hook.installation.account.login,
RepoName = repo.name,
CloneUrl = $"https://github.com/{repo.full_name}",
})));
logger.LogInformation("ProcessInstallationAsync/added: Added RouterMessage for {Owner}/{RepoName}", hook.installation.account.login, repo.name);
}
break;
case "removed":
foreach (var repo in hook.repositories_removed)
{
await installationTable.DropRow(hook.installation.id.ToString(), repo.name);
logger.LogInformation("ProcessInstallationAsync/removed: DropRow for {InstallationId} :: {RepoName}", hook.installation.id, repo.name);
}
break;
case "deleted":
await installationTable.DropPartitionAsync(hook.installation.id.ToString());
logger.LogInformation("ProcessInstallationAsync/deleted: DropPartition for {InstallationId}", hook.installation.id);
break;
}
return "truth";
}
private static async Task<string> ProcessMarketplacePurchaseAsync(Hook hook, CloudTable marketplaceTable, ILogger logger)
{
switch (hook.action)
{
case "changed":
case "purchased":
await marketplaceTable.ExecuteAsync(TableOperation.InsertOrMerge(new Marketplace(hook.marketplace_purchase.account.id, hook.marketplace_purchase.account.login)
{
AccountType = hook.marketplace_purchase.account.type,
SenderEmail = hook.sender.email,
OrganizationBillingEmail = hook.marketplace_purchase.account.organization_billing_email,
PlanId = hook.marketplace_purchase.plan.id,
SenderId = hook.sender.id,
SenderLogin = hook.sender.login,
}));
logger.LogInformation("ProcessMarketplacePurchaseAsync/purchased {PlanId} for {Owner}", hook.marketplace_purchase.plan.id, hook.marketplace_purchase.account.login);
return hook.action;
case "cancelled":
await marketplaceTable.DropRow(hook.marketplace_purchase.account.id, hook.marketplace_purchase.account.login);
logger.LogInformation("ProcessMarketplacePurchaseAsync/cancelled {PlanId} for {Owner}", hook.marketplace_purchase.plan.id, hook.marketplace_purchase.account.login);
return "cancelled";
default:
return hook.action;
}
}
private static async Task<bool> IsPrivateEligible(CloudTable marketplaceTable, string ownerLogin)
{
var query = new TableQuery<Marketplace>().Where(
$"AccountLogin eq '{ownerLogin}' and (PlanId eq 2841 or PlanId eq 2840 or PlanId eq 1750 or PlanId eq 781)");
var rows = await marketplaceTable.ExecuteQuerySegmentedAsync(query, null);
return rows.Count() != 0;
}
// We are using commit hooks here, so let's deduce whether this is an eligble scenario for auto-deleting a branch
// 1. should be merged using the web gui on github.com
// 2. should be merging into the default branch from the imgbot branch
// 3. should only contain the merge commit and the imgbot commit to be eligible
private static bool IsDefaultWebMerge(Hook hook)
{
if (hook.@ref != $"refs/heads/{hook.repository.default_branch}")
return false;
if (hook.commits?.Count == 1)
{
// squash?
if (hook.commits?[0]?.author?.username != "imgbot[bot]" && hook.commits?[0]?.author?.username != "ImgBotApp")
return false;
}
else
{
// regular merge?
if (hook.head_commit?.committer?.username != "web-flow")
return false;
if (hook.commits?.Count > 2)
return false;
if (hook.commits?.All(x => x.committer.username != "ImgBotApp") == true)
return false;
}
return true;
}
}
}
| |
/*
* 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.Diagnostics;
using QuantConnect.Data;
namespace QuantConnect.Indicators
{
/// <summary>
/// Provides a base type for all indicators
/// </summary>
/// <typeparam name="T">The type of data input into this indicator</typeparam>
[DebuggerDisplay("{ToDetailedString()}")]
public abstract partial class IndicatorBase<T> : IIndicator<T>
where T : BaseData
{
/// <summary>the most recent input that was given to this indicator</summary>
private T _previousInput;
/// <summary>
/// Event handler that fires after this indicator is updated
/// </summary>
public event IndicatorUpdatedHandler Updated;
/// <summary>
/// Initializes a new instance of the Indicator class using the specified name.
/// </summary>
/// <param name="name">The name of this indicator</param>
protected IndicatorBase(string name)
{
Name = name;
Current = new IndicatorDataPoint(DateTime.MinValue, 0m);
}
/// <summary>
/// Gets a name for this indicator
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Gets a flag indicating when this indicator is ready and fully initialized
/// </summary>
public abstract bool IsReady { get; }
/// <summary>
/// Gets the current state of this indicator. If the state has not been updated
/// then the time on the value will equal DateTime.MinValue.
/// </summary>
public IndicatorDataPoint Current { get; protected set; }
/// <summary>
/// Gets the number of samples processed by this indicator
/// </summary>
public long Samples { get; private set; }
/// <summary>
/// Updates the state of this indicator with the given value and returns true
/// if this indicator is ready, false otherwise
/// </summary>
/// <param name="input">The value to use to update this indicator</param>
/// <returns>True if this indicator is ready, false otherwise</returns>
public bool Update(T input)
{
if (_previousInput != null && input.Time < _previousInput.Time)
{
// if we receive a time in the past, throw
throw new ArgumentException(string.Format("This is a forward only indicator: {0} Input: {1} Previous: {2}", Name, input.Time.ToString("u"), _previousInput.Time.ToString("u")));
}
if (!ReferenceEquals(input, _previousInput))
{
// compute a new value and update our previous time
Samples++;
_previousInput = input;
var nextResult = ValidateAndComputeNextValue(input);
if (nextResult.Status == IndicatorStatus.Success)
{
Current = new IndicatorDataPoint(input.Time, nextResult.Value);
// let others know we've produced a new data point
OnUpdated(Current);
}
}
return IsReady;
}
/// <summary>
/// Resets this indicator to its initial state
/// </summary>
public virtual void Reset()
{
Samples = 0;
_previousInput = null;
Current = new IndicatorDataPoint(DateTime.MinValue, default(decimal));
}
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <returns>
/// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public int CompareTo(IIndicator<T> other)
{
if (ReferenceEquals(other, null))
{
// everything is greater than null via MSDN
return 1;
}
return Current.CompareTo(other.Current);
}
/// <summary>
/// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.
/// </summary>
/// <returns>
/// A value that indicates the relative order of the objects being compared. The return value has these meanings: Value Meaning Less than zero This instance precedes <paramref name="obj"/> in the sort order. Zero This instance occurs in the same position in the sort order as <paramref name="obj"/>. Greater than zero This instance follows <paramref name="obj"/> in the sort order.
/// </returns>
/// <param name="obj">An object to compare with this instance. </param><exception cref="T:System.ArgumentException"><paramref name="obj"/> is not the same type as this instance. </exception><filterpriority>2</filterpriority>
public int CompareTo(object obj)
{
var other = obj as IndicatorBase<T>;
if (other == null)
{
throw new ArgumentException("Object must be of type " + GetType().GetBetterTypeName());
}
return CompareTo(other);
}
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// </summary>
/// <returns>
/// true if the specified object is equal to the current object; otherwise, false.
/// </returns>
/// <param name="obj">The object to compare with the current object. </param>
public override bool Equals(object obj)
{
// this implementation acts as a liason to prevent inconsistency between the operators
// == and != against primitive types. the core impl for equals between two indicators
// is still reference equality, however, when comparing value types (floats/int, ect..)
// we'll use value type semantics on Current.Value
// because of this, we shouldn't need to override GetHashCode as well since we're still
// solely relying on reference semantics (think hashset/dictionary impls)
if (ReferenceEquals(obj, null)) return false;
if (obj.GetType().IsSubclassOf(typeof (IndicatorBase<>))) return ReferenceEquals(this, obj);
// the obj is not an indicator, so let's check for value types, try converting to decimal
var converted = Convert.ToDecimal(obj);
return Current.Value == converted;
}
/// <summary>
/// ToString Overload for Indicator Base
/// </summary>
/// <returns>String representation of the indicator</returns>
public override string ToString()
{
return Current.Value.ToString("#######0.0####");
}
/// <summary>
/// Provides a more detailed string of this indicator in the form of {Name} - {Value}
/// </summary>
/// <returns>A detailed string of this indicator's current state</returns>
public string ToDetailedString()
{
return string.Format("{0} - {1}", Name, this);
}
/// <summary>
/// Computes the next value of this indicator from the given state
/// </summary>
/// <param name="input">The input given to the indicator</param>
/// <returns>A new value for this indicator</returns>
protected abstract decimal ComputeNextValue(T input);
/// <summary>
/// Computes the next value of this indicator from the given state
/// and returns an instance of the <see cref="IndicatorResult"/> class
/// </summary>
/// <param name="input">The input given to the indicator</param>
/// <returns>An IndicatorResult object including the status of the indicator</returns>
protected virtual IndicatorResult ValidateAndComputeNextValue(T input)
{
// default implementation always returns IndicatorStatus.Success
return new IndicatorResult(ComputeNextValue(input));
}
/// <summary>
/// Event invocator for the Updated event
/// </summary>
/// <param name="consolidated">This is the new piece of data produced by this indicator</param>
protected virtual void OnUpdated(IndicatorDataPoint consolidated)
{
var handler = Updated;
if (handler != null) handler(this, consolidated);
}
}
}
| |
// 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 ConvertToVector128Int32WithTruncationInt32Vector128Single()
{
var test = new SimpleUnaryOpConvTest__ConvertToVector128Int32WithTruncationInt32Vector128Single();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpConvTest__ConvertToVector128Int32WithTruncationInt32Vector128Single
{
private struct TestStruct
{
public Vector128<Single> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpConvTest__ConvertToVector128Int32WithTruncationInt32Vector128Single testClass)
{
var result = Sse2.ConvertToVector128Int32WithTruncation(_fld);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Single[] _data = new Single[Op1ElementCount];
private static Vector128<Single> _clsVar;
private Vector128<Single> _fld;
private SimpleUnaryOpTest__DataTable<Int32, Single> _dataTable;
static SimpleUnaryOpConvTest__ConvertToVector128Int32WithTruncationInt32Vector128Single()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public SimpleUnaryOpConvTest__ConvertToVector128Int32WithTruncationInt32Vector128Single()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int32, Single>(_data, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.ConvertToVector128Int32WithTruncation(
Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.ConvertToVector128Int32WithTruncation(
Sse2.LoadVector128((Single*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.ConvertToVector128Int32WithTruncation(
Sse2.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ConvertToVector128Int32WithTruncation), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ConvertToVector128Int32WithTruncation), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Single*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ConvertToVector128Int32WithTruncation), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.ConvertToVector128Int32WithTruncation(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr);
var result = Sse2.ConvertToVector128Int32WithTruncation(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((Single*)(_dataTable.inArrayPtr));
var result = Sse2.ConvertToVector128Int32WithTruncation(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr));
var result = Sse2.ConvertToVector128Int32WithTruncation(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpConvTest__ConvertToVector128Int32WithTruncationInt32Vector128Single();
var result = Sse2.ConvertToVector128Int32WithTruncation(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.ConvertToVector128Int32WithTruncation(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.ConvertToVector128Int32WithTruncation(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Single> firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Single[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
if (Sse2Verify.ConvertToVector128Int32WithTruncation(result, firstOp))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (Sse2Verify.ConvertToVector128Int32WithTruncation(result, firstOp))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ConvertToVector128Int32WithTruncation)}<Int32>(Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
}
}
| |
/**
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
#define PRETTY //Comment out when you no longer need to read JSON to disable pretty Print system-wide
//Using doubles will cause errors in VectorTemplates.cs; Unity speaks floats
#define USEFLOAT //Use floats for numbers instead of doubles (enable if you're getting too many significant digits in string output)
//#define POOLING //Currently using a build setting for this one (also it's experimental)
#if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5
using UnityEngine;
using Debug = UnityEngine.Debug;
#endif
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Text;
/*
* http://www.opensource.org/licenses/lgpl-2.1.php
* JSONObject class v.1.4.1
* for use with Unity
* Copyright Matt Schoen 2010 - 2013
*/
// Added to Fungus namespace to minimize conflicts with other assets
namespace Fungus
{
public class JSONObject {
#if POOLING
const int MAX_POOL_SIZE = 10000;
public static Queue<JSONObject> releaseQueue = new Queue<JSONObject>();
#endif
const int MAX_DEPTH = 100;
const string INFINITY = "\"INFINITY\"";
const string NEGINFINITY = "\"NEGINFINITY\"";
const string NaN = "\"NaN\"";
const string NEWLINE = "\r\n";
public static readonly char[] WHITESPACE = { ' ', '\r', '\n', '\t', '\uFEFF', '\u0009' };
public enum Type { NULL, STRING, NUMBER, OBJECT, ARRAY, BOOL, BAKED }
public bool isContainer { get { return (type == Type.ARRAY || type == Type.OBJECT); } }
public Type type = Type.NULL;
public int Count {
get {
if(list == null)
return -1;
return list.Count;
}
}
public List<JSONObject> list;
public List<string> keys;
public string str;
#if USEFLOAT
public float n;
public float f {
get {
return n;
}
}
#else
public double n;
public float f {
get {
return (float)n;
}
}
#endif
public bool useInt;
public long i;
public bool b;
public delegate void AddJSONContents(JSONObject self);
public static JSONObject nullJO { get { return Create(Type.NULL); } } //an empty, null object
public static JSONObject obj { get { return Create(Type.OBJECT); } } //an empty object
public static JSONObject arr { get { return Create(Type.ARRAY); } } //an empty array
public JSONObject(Type t) {
type = t;
switch(t) {
case Type.ARRAY:
list = new List<JSONObject>();
break;
case Type.OBJECT:
list = new List<JSONObject>();
keys = new List<string>();
break;
}
}
public JSONObject(bool b) {
type = Type.BOOL;
this.b = b;
}
#if USEFLOAT
public JSONObject(float f) {
type = Type.NUMBER;
n = f;
}
#else
public JSONObject(double d) {
type = Type.NUMBER;
n = d;
}
#endif
public JSONObject(int i) {
type = Type.NUMBER;
this.i = i;
useInt = true;
n = i;
}
public JSONObject(long l) {
type = Type.NUMBER;
i = l;
useInt = true;
n = l;
}
public JSONObject(Dictionary<string, string> dic) {
type = Type.OBJECT;
keys = new List<string>();
list = new List<JSONObject>();
//Not sure if it's worth removing the foreach here
foreach(KeyValuePair<string, string> kvp in dic) {
keys.Add(kvp.Key);
list.Add(CreateStringObject(kvp.Value));
}
}
public JSONObject(Dictionary<string, JSONObject> dic) {
type = Type.OBJECT;
keys = new List<string>();
list = new List<JSONObject>();
//Not sure if it's worth removing the foreach here
foreach(KeyValuePair<string, JSONObject> kvp in dic) {
keys.Add(kvp.Key);
list.Add(kvp.Value);
}
}
public JSONObject(AddJSONContents content) {
content.Invoke(this);
}
public JSONObject(JSONObject[] objs) {
type = Type.ARRAY;
list = new List<JSONObject>(objs);
}
//Convenience function for creating a JSONObject containing a string. This is not part of the constructor so that malformed JSON data doesn't just turn into a string object
public static JSONObject StringObject(string val) { return CreateStringObject(val); }
public void Absorb(JSONObject obj) {
list.AddRange(obj.list);
keys.AddRange(obj.keys);
str = obj.str;
n = obj.n;
useInt = obj.useInt;
i = obj.i;
b = obj.b;
type = obj.type;
}
public static JSONObject Create() {
#if POOLING
JSONObject result = null;
while(result == null && releaseQueue.Count > 0) {
result = releaseQueue.Dequeue();
#if DEV
//The following cases should NEVER HAPPEN (but they do...)
if(result == null)
Debug.WriteLine("wtf " + releaseQueue.Count);
else if(result.list != null)
Debug.WriteLine("wtflist " + result.list.Count);
#endif
}
if(result != null)
return result;
#endif
return new JSONObject();
}
public static JSONObject Create(Type t) {
JSONObject obj = Create();
obj.type = t;
switch(t) {
case Type.ARRAY:
obj.list = new List<JSONObject>();
break;
case Type.OBJECT:
obj.list = new List<JSONObject>();
obj.keys = new List<string>();
break;
}
return obj;
}
public static JSONObject Create(bool val) {
JSONObject obj = Create();
obj.type = Type.BOOL;
obj.b = val;
return obj;
}
public static JSONObject Create(float val) {
JSONObject obj = Create();
obj.type = Type.NUMBER;
obj.n = val;
return obj;
}
public static JSONObject Create(int val) {
JSONObject obj = Create();
obj.type = Type.NUMBER;
obj.n = val;
obj.useInt = true;
obj.i = val;
return obj;
}
public static JSONObject Create(long val) {
JSONObject obj = Create();
obj.type = Type.NUMBER;
obj.n = val;
obj.useInt = true;
obj.i = val;
return obj;
}
public static JSONObject CreateStringObject(string val) {
JSONObject obj = Create();
obj.type = Type.STRING;
obj.str = val;
return obj;
}
public static JSONObject CreateBakedObject(string val) {
JSONObject bakedObject = Create();
bakedObject.type = Type.BAKED;
bakedObject.str = val;
return bakedObject;
}
/// <summary>
/// Create a JSONObject by parsing string data
/// </summary>
/// <param name="val">The string to be parsed</param>
/// <param name="maxDepth">The maximum depth for the parser to search. Set this to to 1 for the first level,
/// 2 for the first 2 levels, etc. It defaults to -2 because -1 is the depth value that is parsed (see below)</param>
/// <param name="storeExcessLevels">Whether to store levels beyond maxDepth in baked JSONObjects</param>
/// <param name="strict">Whether to be strict in the parsing. For example, non-strict parsing will successfully
/// parse "a string" into a string-type </param>
/// <returns></returns>
public static JSONObject Create(string val, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false) {
JSONObject obj = Create();
obj.Parse(val, maxDepth, storeExcessLevels, strict);
return obj;
}
public static JSONObject Create(AddJSONContents content) {
JSONObject obj = Create();
content.Invoke(obj);
return obj;
}
public static JSONObject Create(Dictionary<string, string> dic) {
JSONObject obj = Create();
obj.type = Type.OBJECT;
obj.keys = new List<string>();
obj.list = new List<JSONObject>();
//Not sure if it's worth removing the foreach here
foreach(KeyValuePair<string, string> kvp in dic) {
obj.keys.Add(kvp.Key);
obj.list.Add(CreateStringObject(kvp.Value));
}
return obj;
}
public JSONObject() { }
#region PARSE
public JSONObject(string str, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false) { //create a new JSONObject from a string (this will also create any children, and parse the whole string)
Parse(str, maxDepth, storeExcessLevels, strict);
}
void Parse(string str, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false) {
if(!string.IsNullOrEmpty(str)) {
str = str.Trim(WHITESPACE);
if(strict) {
if(str[0] != '[' && str[0] != '{') {
type = Type.NULL;
#if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5
Debug.LogWarning
#else
Debug.WriteLine
#endif
("Improper (strict) JSON formatting. First character must be [ or {");
return;
}
}
if(str.Length > 0) {
#if UNITY_WP8 || UNITY_WSA
if (str == "true") {
type = Type.BOOL;
b = true;
} else if (str == "false") {
type = Type.BOOL;
b = false;
} else if (str == "null") {
type = Type.NULL;
#else
if(string.Compare(str, "true", true) == 0) {
type = Type.BOOL;
b = true;
} else if(string.Compare(str, "false", true) == 0) {
type = Type.BOOL;
b = false;
} else if(string.Compare(str, "null", true) == 0) {
type = Type.NULL;
#endif
#if USEFLOAT
} else if(str == INFINITY) {
type = Type.NUMBER;
n = float.PositiveInfinity;
} else if(str == NEGINFINITY) {
type = Type.NUMBER;
n = float.NegativeInfinity;
} else if(str == NaN) {
type = Type.NUMBER;
n = float.NaN;
#else
} else if(str == INFINITY) {
type = Type.NUMBER;
n = double.PositiveInfinity;
} else if(str == NEGINFINITY) {
type = Type.NUMBER;
n = double.NegativeInfinity;
} else if(str == NaN) {
type = Type.NUMBER;
n = double.NaN;
#endif
} else if(str[0] == '"') {
type = Type.STRING;
this.str = str.Substring(1, str.Length - 2);
} else {
int tokenTmp = 1;
/*
* Checking for the following formatting (www.json.org)
* object - {"field1":value,"field2":value}
* array - [value,value,value]
* value - string - "string"
* - number - 0.0
* - bool - true -or- false
* - null - null
*/
int offset = 0;
switch(str[offset]) {
case '{':
type = Type.OBJECT;
keys = new List<string>();
list = new List<JSONObject>();
break;
case '[':
type = Type.ARRAY;
list = new List<JSONObject>();
break;
default:
try {
#if USEFLOAT
n = System.Convert.ToSingle(str);
#else
n = System.Convert.ToDouble(str);
#endif
if(!str.Contains(".")) {
i = System.Convert.ToInt64(str);
useInt = true;
}
type = Type.NUMBER;
} catch(System.FormatException) {
type = Type.NULL;
#if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5
Debug.LogWarning
#else
Debug.WriteLine
#endif
("improper JSON formatting:" + str);
}
return;
}
string propName = "";
bool openQuote = false;
bool inProp = false;
int depth = 0;
while(++offset < str.Length) {
if(System.Array.IndexOf(WHITESPACE, str[offset]) > -1)
continue;
if(str[offset] == '\\') {
offset += 1;
continue;
}
if(str[offset] == '"') {
if(openQuote) {
if(!inProp && depth == 0 && type == Type.OBJECT)
propName = str.Substring(tokenTmp + 1, offset - tokenTmp - 1);
openQuote = false;
} else {
if(depth == 0 && type == Type.OBJECT)
tokenTmp = offset;
openQuote = true;
}
}
if(openQuote)
continue;
if(type == Type.OBJECT && depth == 0) {
if(str[offset] == ':') {
tokenTmp = offset + 1;
inProp = true;
}
}
if(str[offset] == '[' || str[offset] == '{') {
depth++;
} else if(str[offset] == ']' || str[offset] == '}') {
depth--;
}
//if (encounter a ',' at top level) || a closing ]/}
if((str[offset] == ',' && depth == 0) || depth < 0) {
inProp = false;
string inner = str.Substring(tokenTmp, offset - tokenTmp).Trim(WHITESPACE);
if(inner.Length > 0) {
if(type == Type.OBJECT)
keys.Add(propName);
if(maxDepth != -1) //maxDepth of -1 is the end of the line
list.Add(Create(inner, (maxDepth < -1) ? -2 : maxDepth - 1));
else if(storeExcessLevels)
list.Add(CreateBakedObject(inner));
}
tokenTmp = offset + 1;
}
}
}
} else type = Type.NULL;
} else type = Type.NULL; //If the string is missing, this is a null
//Profiler.EndSample();
}
#endregion
public bool IsNumber { get { return type == Type.NUMBER; } }
public bool IsNull { get { return type == Type.NULL; } }
public bool IsString { get { return type == Type.STRING; } }
public bool IsBool { get { return type == Type.BOOL; } }
public bool IsArray { get { return type == Type.ARRAY; } }
public bool IsObject { get { return type == Type.OBJECT || type == Type.BAKED; } }
public void Add(bool val) {
Add(Create(val));
}
public void Add(float val) {
Add(Create(val));
}
public void Add(int val) {
Add(Create(val));
}
public void Add(string str) {
Add(CreateStringObject(str));
}
public void Add(AddJSONContents content) {
Add(Create(content));
}
public void Add(JSONObject obj) {
if(obj) { //Don't do anything if the object is null
if(type != Type.ARRAY) {
type = Type.ARRAY; //Congratulations, son, you're an ARRAY now
if(list == null)
list = new List<JSONObject>();
}
list.Add(obj);
}
}
public void AddField(string name, bool val) {
AddField(name, Create(val));
}
public void AddField(string name, float val) {
AddField(name, Create(val));
}
public void AddField(string name, int val) {
AddField(name, Create(val));
}
public void AddField(string name, long val) {
AddField(name, Create(val));
}
public void AddField(string name, AddJSONContents content) {
AddField(name, Create(content));
}
public void AddField(string name, string val) {
AddField(name, CreateStringObject(val));
}
public void AddField(string name, JSONObject obj) {
if(obj) { //Don't do anything if the object is null
if(type != Type.OBJECT) {
if(keys == null)
keys = new List<string>();
if(type == Type.ARRAY) {
for(int i = 0; i < list.Count; i++)
keys.Add(i + "");
} else
if(list == null)
list = new List<JSONObject>();
type = Type.OBJECT; //Congratulations, son, you're an OBJECT now
}
keys.Add(name);
list.Add(obj);
}
}
public void SetField(string name, string val) { SetField(name, CreateStringObject(val)); }
public void SetField(string name, bool val) { SetField(name, Create(val)); }
public void SetField(string name, float val) { SetField(name, Create(val)); }
public void SetField(string name, int val) { SetField(name, Create(val)); }
public void SetField(string name, JSONObject obj) {
if(HasField(name)) {
list.Remove(this[name]);
keys.Remove(name);
}
AddField(name, obj);
}
public void RemoveField(string name) {
if(keys.IndexOf(name) > -1) {
list.RemoveAt(keys.IndexOf(name));
keys.Remove(name);
}
}
public delegate void FieldNotFound(string name);
public delegate void GetFieldResponse(JSONObject obj);
public bool GetField(out bool field, string name, bool fallback) {
field = fallback;
return GetField(ref field, name);
}
public bool GetField(ref bool field, string name, FieldNotFound fail = null) {
if(type == Type.OBJECT) {
int index = keys.IndexOf(name);
if(index >= 0) {
field = list[index].b;
return true;
}
}
if(fail != null) fail.Invoke(name);
return false;
}
#if USEFLOAT
public bool GetField(out float field, string name, float fallback) {
#else
public bool GetField(out double field, string name, double fallback) {
#endif
field = fallback;
return GetField(ref field, name);
}
#if USEFLOAT
public bool GetField(ref float field, string name, FieldNotFound fail = null) {
#else
public bool GetField(ref double field, string name, FieldNotFound fail = null) {
#endif
if(type == Type.OBJECT) {
int index = keys.IndexOf(name);
if(index >= 0) {
field = list[index].n;
return true;
}
}
if(fail != null) fail.Invoke(name);
return false;
}
public bool GetField(out int field, string name, int fallback) {
field = fallback;
return GetField(ref field, name);
}
public bool GetField(ref int field, string name, FieldNotFound fail = null) {
if(IsObject) {
int index = keys.IndexOf(name);
if(index >= 0) {
field = (int)list[index].n;
return true;
}
}
if(fail != null) fail.Invoke(name);
return false;
}
public bool GetField(out long field, string name, long fallback) {
field = fallback;
return GetField(ref field, name);
}
public bool GetField(ref long field, string name, FieldNotFound fail = null) {
if(IsObject) {
int index = keys.IndexOf(name);
if(index >= 0) {
field = (long)list[index].n;
return true;
}
}
if(fail != null) fail.Invoke(name);
return false;
}
public bool GetField(out uint field, string name, uint fallback) {
field = fallback;
return GetField(ref field, name);
}
public bool GetField(ref uint field, string name, FieldNotFound fail = null) {
if(IsObject) {
int index = keys.IndexOf(name);
if(index >= 0) {
field = (uint)list[index].n;
return true;
}
}
if(fail != null) fail.Invoke(name);
return false;
}
public bool GetField(out string field, string name, string fallback) {
field = fallback;
return GetField(ref field, name);
}
public bool GetField(ref string field, string name, FieldNotFound fail = null) {
if(IsObject) {
int index = keys.IndexOf(name);
if(index >= 0) {
field = list[index].str;
return true;
}
}
if(fail != null) fail.Invoke(name);
return false;
}
public void GetField(string name, GetFieldResponse response, FieldNotFound fail = null) {
if(response != null && IsObject) {
int index = keys.IndexOf(name);
if(index >= 0) {
response.Invoke(list[index]);
return;
}
}
if(fail != null) fail.Invoke(name);
}
public JSONObject GetField(string name) {
if(IsObject)
for(int i = 0; i < keys.Count; i++)
if(keys[i] == name)
return list[i];
return null;
}
public bool HasFields(string[] names) {
if(!IsObject)
return false;
for(int i = 0; i < names.Length; i++)
if(!keys.Contains(names[i]))
return false;
return true;
}
public bool HasField(string name) {
if(!IsObject)
return false;
for(int i = 0; i < keys.Count; i++)
if(keys[i] == name)
return true;
return false;
}
public void Clear() {
type = Type.NULL;
if(list != null)
list.Clear();
if(keys != null)
keys.Clear();
str = "";
n = 0;
b = false;
}
/// <summary>
/// Copy a JSONObject. This could probably work better
/// </summary>
/// <returns></returns>
public JSONObject Copy() {
return Create(Print());
}
/*
* The Merge function is experimental. Use at your own risk.
*/
public void Merge(JSONObject obj) {
MergeRecur(this, obj);
}
/// <summary>
/// Merge object right into left recursively
/// </summary>
/// <param name="left">The left (base) object</param>
/// <param name="right">The right (new) object</param>
static void MergeRecur(JSONObject left, JSONObject right) {
if(left.type == Type.NULL)
left.Absorb(right);
else if(left.type == Type.OBJECT && right.type == Type.OBJECT) {
for(int i = 0; i < right.list.Count; i++) {
string key = right.keys[i];
if(right[i].isContainer) {
if(left.HasField(key))
MergeRecur(left[key], right[i]);
else
left.AddField(key, right[i]);
} else {
if(left.HasField(key))
left.SetField(key, right[i]);
else
left.AddField(key, right[i]);
}
}
} else if(left.type == Type.ARRAY && right.type == Type.ARRAY) {
if(right.Count > left.Count) {
#if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5
Debug.LogError
#else
Debug.WriteLine
#endif
("Cannot merge arrays when right object has more elements");
return;
}
for(int i = 0; i < right.list.Count; i++) {
if(left[i].type == right[i].type) { //Only overwrite with the same type
if(left[i].isContainer)
MergeRecur(left[i], right[i]);
else {
left[i] = right[i];
}
}
}
}
}
public void Bake() {
if(type != Type.BAKED) {
str = Print();
type = Type.BAKED;
}
}
public IEnumerable BakeAsync() {
if(type != Type.BAKED) {
foreach(string s in PrintAsync()) {
if(s == null)
yield return s;
else {
str = s;
}
}
type = Type.BAKED;
}
}
#pragma warning disable 219
public string Print(bool pretty = false) {
StringBuilder builder = new StringBuilder();
Stringify(0, builder, pretty);
return builder.ToString();
}
public IEnumerable<string> PrintAsync(bool pretty = false) {
StringBuilder builder = new StringBuilder();
printWatch.Reset();
printWatch.Start();
foreach(IEnumerable e in StringifyAsync(0, builder, pretty)) {
yield return null;
}
yield return builder.ToString();
}
#pragma warning restore 219
#region STRINGIFY
const float maxFrameTime = 0.008f;
static readonly Stopwatch printWatch = new Stopwatch();
IEnumerable StringifyAsync(int depth, StringBuilder builder, bool pretty = false) { //Convert the JSONObject into a string
//Profiler.BeginSample("JSONprint");
if(depth++ > MAX_DEPTH) {
#if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5
Debug.Log
#else
Debug.WriteLine
#endif
("reached max depth!");
yield break;
}
if(printWatch.Elapsed.TotalSeconds > maxFrameTime) {
printWatch.Reset();
yield return null;
printWatch.Start();
}
switch(type) {
case Type.BAKED:
builder.Append(str);
break;
case Type.STRING:
builder.AppendFormat("\"{0}\"", str);
break;
case Type.NUMBER:
if(useInt) {
builder.Append(i.ToString());
} else {
#if USEFLOAT
if(float.IsInfinity(n))
builder.Append(INFINITY);
else if(float.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if(float.IsNaN(n))
builder.Append(NaN);
#else
if(double.IsInfinity(n))
builder.Append(INFINITY);
else if(double.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if(double.IsNaN(n))
builder.Append(NaN);
#endif
else
builder.Append(n.ToString());
}
break;
case Type.OBJECT:
builder.Append("{");
if(list.Count > 0) {
#if(PRETTY) //for a bit more readability, comment the define above to disable system-wide
if(pretty)
builder.Append(NEWLINE);
#endif
for(int i = 0; i < list.Count; i++) {
string key = keys[i];
JSONObject obj = list[i];
if(obj) {
#if(PRETTY)
if(pretty)
for(int j = 0; j < depth; j++)
builder.Append("\t"); //for a bit more readability
#endif
builder.AppendFormat("\"{0}\":", key);
foreach(IEnumerable e in obj.StringifyAsync(depth, builder, pretty))
yield return e;
builder.Append(",");
#if(PRETTY)
if(pretty)
builder.Append(NEWLINE);
#endif
}
}
#if(PRETTY)
if(pretty)
builder.Length -= 2;
else
#endif
builder.Length--;
}
#if(PRETTY)
if(pretty && list.Count > 0) {
builder.Append(NEWLINE);
for(int j = 0; j < depth - 1; j++)
builder.Append("\t"); //for a bit more readability
}
#endif
builder.Append("}");
break;
case Type.ARRAY:
builder.Append("[");
if(list.Count > 0) {
#if(PRETTY)
if(pretty)
builder.Append(NEWLINE); //for a bit more readability
#endif
for(int i = 0; i < list.Count; i++) {
if(list[i]) {
#if(PRETTY)
if(pretty)
for(int j = 0; j < depth; j++)
builder.Append("\t"); //for a bit more readability
#endif
foreach(IEnumerable e in list[i].StringifyAsync(depth, builder, pretty))
yield return e;
builder.Append(",");
#if(PRETTY)
if(pretty)
builder.Append(NEWLINE); //for a bit more readability
#endif
}
}
#if(PRETTY)
if(pretty)
builder.Length -= 2;
else
#endif
builder.Length--;
}
#if(PRETTY)
if(pretty && list.Count > 0) {
builder.Append(NEWLINE);
for(int j = 0; j < depth - 1; j++)
builder.Append("\t"); //for a bit more readability
}
#endif
builder.Append("]");
break;
case Type.BOOL:
if(b)
builder.Append("true");
else
builder.Append("false");
break;
case Type.NULL:
builder.Append("null");
break;
}
//Profiler.EndSample();
}
//TODO: Refactor Stringify functions to share core logic
/*
* I know, I know, this is really bad form. It turns out that there is a
* significant amount of garbage created when calling as a coroutine, so this
* method is duplicated. Hopefully there won't be too many future changes, but
* I would still like a more elegant way to optionaly yield
*/
void Stringify(int depth, StringBuilder builder, bool pretty = false) { //Convert the JSONObject into a string
//Profiler.BeginSample("JSONprint");
if(depth++ > MAX_DEPTH) {
#if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5
Debug.Log
#else
Debug.WriteLine
#endif
("reached max depth!");
return;
}
switch(type) {
case Type.BAKED:
builder.Append(str);
break;
case Type.STRING:
builder.AppendFormat("\"{0}\"", str);
break;
case Type.NUMBER:
if(useInt) {
builder.Append(i.ToString());
} else {
#if USEFLOAT
if(float.IsInfinity(n))
builder.Append(INFINITY);
else if(float.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if(float.IsNaN(n))
builder.Append(NaN);
#else
if(double.IsInfinity(n))
builder.Append(INFINITY);
else if(double.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if(double.IsNaN(n))
builder.Append(NaN);
#endif
else
builder.Append(n.ToString());
}
break;
case Type.OBJECT:
builder.Append("{");
if(list.Count > 0) {
#if(PRETTY) //for a bit more readability, comment the define above to disable system-wide
if(pretty)
builder.Append("\n");
#endif
for(int i = 0; i < list.Count; i++) {
string key = keys[i];
JSONObject obj = list[i];
if(obj) {
#if(PRETTY)
if(pretty)
for(int j = 0; j < depth; j++)
builder.Append("\t"); //for a bit more readability
#endif
builder.AppendFormat("\"{0}\":", key);
obj.Stringify(depth, builder, pretty);
builder.Append(",");
#if(PRETTY)
if(pretty)
builder.Append("\n");
#endif
}
}
#if(PRETTY)
if(pretty)
builder.Length -= 2;
else
#endif
builder.Length--;
}
#if(PRETTY)
if(pretty && list.Count > 0) {
builder.Append("\n");
for(int j = 0; j < depth - 1; j++)
builder.Append("\t"); //for a bit more readability
}
#endif
builder.Append("}");
break;
case Type.ARRAY:
builder.Append("[");
if(list.Count > 0) {
#if(PRETTY)
if(pretty)
builder.Append("\n"); //for a bit more readability
#endif
for(int i = 0; i < list.Count; i++) {
if(list[i]) {
#if(PRETTY)
if(pretty)
for(int j = 0; j < depth; j++)
builder.Append("\t"); //for a bit more readability
#endif
list[i].Stringify(depth, builder, pretty);
builder.Append(",");
#if(PRETTY)
if(pretty)
builder.Append("\n"); //for a bit more readability
#endif
}
}
#if(PRETTY)
if(pretty)
builder.Length -= 2;
else
#endif
builder.Length--;
}
#if(PRETTY)
if(pretty && list.Count > 0) {
builder.Append("\n");
for(int j = 0; j < depth - 1; j++)
builder.Append("\t"); //for a bit more readability
}
#endif
builder.Append("]");
break;
case Type.BOOL:
if(b)
builder.Append("true");
else
builder.Append("false");
break;
case Type.NULL:
builder.Append("null");
break;
}
//Profiler.EndSample();
}
#endregion
#if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5
public static implicit operator WWWForm(JSONObject obj) {
WWWForm form = new WWWForm();
for(int i = 0; i < obj.list.Count; i++) {
string key = i + "";
if(obj.type == Type.OBJECT)
key = obj.keys[i];
string val = obj.list[i].ToString();
if(obj.list[i].type == Type.STRING)
val = val.Replace("\"", "");
form.AddField(key, val);
}
return form;
}
#endif
public JSONObject this[int index] {
get {
if(list.Count > index) return list[index];
return null;
}
set {
if(list.Count > index)
list[index] = value;
}
}
public JSONObject this[string index] {
get {
return GetField(index);
}
set {
SetField(index, value);
}
}
public override string ToString() {
return Print();
}
public string ToString(bool pretty) {
return Print(pretty);
}
public Dictionary<string, string> ToDictionary() {
if(type == Type.OBJECT) {
Dictionary<string, string> result = new Dictionary<string, string>();
for(int i = 0; i < list.Count; i++) {
JSONObject val = list[i];
switch(val.type) {
case Type.STRING: result.Add(keys[i], val.str); break;
case Type.NUMBER: result.Add(keys[i], val.n + ""); break;
case Type.BOOL: result.Add(keys[i], val.b + ""); break;
default:
#if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5
Debug.LogWarning
#else
Debug.WriteLine
#endif
("Omitting object: " + keys[i] + " in dictionary conversion");
break;
}
}
return result;
}
#if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5
Debug.Log
#else
Debug.WriteLine
#endif
("Tried to turn non-Object JSONObject into a dictionary");
return null;
}
public static implicit operator bool(JSONObject o) {
return o != null;
}
#if POOLING
static bool pool = true;
public static void ClearPool() {
pool = false;
releaseQueue.Clear();
pool = true;
}
~JSONObject() {
if(pool && releaseQueue.Count < MAX_POOL_SIZE) {
type = Type.NULL;
list = null;
keys = null;
str = "";
n = 0;
b = false;
releaseQueue.Enqueue(this);
}
}
#endif
}
}
| |
// 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.Linq;
namespace Test
{
public class TakeWhileSkipWhileTests
{
//
// TakeWhile and SkipWhile
//
[Fact]
public static void RunTakeWhileTests()
{
// TakeWhile:
RunTakeWhile_AllFalse(1024);
RunTakeWhile_AllTrue(1024);
RunTakeWhile_SomeTrues(1024, 512);
RunTakeWhile_SomeTrues(1024, 0);
RunTakeWhile_SomeTrues(1024, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18);
RunTakeWhile_SomeTrues(1024, 1023);
RunTakeWhile_SomeTrues(1024 * 1024, 1024 * 512);
RunTakeWhile_SomeFalses(1024, 512);
RunTakeWhile_SomeFalses(1024, 0);
RunTakeWhile_SomeFalses(1024, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18);
RunTakeWhile_SomeFalses(1024, 1023);
RunTakeWhile_SomeFalses(1024 * 1024, 1024 * 512);
}
[Fact]
public static void RunSkipWhileTests()
{
// SkipWhile:
RunSkipWhile_AllFalse(1024);
RunSkipWhile_AllTrue(1024);
RunSkipWhile_SomeTrues(1024, 512);
RunSkipWhile_SomeTrues(1024, 0);
RunSkipWhile_SomeTrues(1024, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18);
RunSkipWhile_SomeTrues(1024, 1023);
RunSkipWhile_SomeTrues(1024 * 1024, 1024 * 512);
RunSkipWhile_SomeTrues(1024, 512);
RunSkipWhile_SomeTrues(1024, 0);
RunSkipWhile_SomeTrues(1024, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18);
RunSkipWhile_SomeTrues(1024, 1023);
RunSkipWhile_SomeTrues(1024 * 1024, 1024 * 512);
}
//
// TakeWhile
//
private static void RunTakeWhile_AllFalse(int size)
{
int[] data = new int[size];
for (int i = 0; i < size; i++) data[i] = i;
ParallelQuery<int> q = data.AsParallel().TakeWhile(delegate (int x) { return false; });
int count = 0;
int expect = 0;
foreach (int x in q)
{
count++;
}
if (count != expect)
Assert.Equal(expect, count);
}
private static void RunTakeWhile_AllTrue(int size)
{
int[] data = new int[size];
for (int i = 0; i < size; i++) data[i] = i;
ParallelQuery<int> q = data.AsParallel().TakeWhile(delegate (int x) { return true; });
int count = 0;
int expect = size;
foreach (int x in q)
{
count++;
}
if (count != expect)
Assert.Equal(expect, count);
}
private static void RunTakeWhile_SomeTrues(int size, params int[] truePositions)
{
int[] data = new int[size];
for (int i = 0; i < size; i++) data[i] = i;
ParallelQuery<int> q = data.AsParallel().TakeWhile(delegate (int x) { return Array.IndexOf(truePositions, x) != -1; });
int count = 0;
// We expect TakeWhile to yield all elements up to (but not including) the smallest false
// index in the array.
int expect = 0;
for (int i = 0; i < size; i++)
{
if (Array.IndexOf(truePositions, i) == -1)
break;
expect++;
}
foreach (int x in q)
{
count++;
}
if (count != expect)
{
Assert.Equal(expect, count);
}
}
private static void RunTakeWhile_SomeFalses(int size, params int[] falsePositions)
{
int[] data = new int[size];
for (int i = 0; i < size; i++) data[i] = i;
ParallelQuery<int> q = data.AsParallel().TakeWhile(delegate (int x) { return Array.IndexOf(falsePositions, x) == -1; });
int count = 0;
// We expect TakeWhile to yield all elements up to (but not including) the smallest false
// index in the array.
int expect = falsePositions[0];
for (int i = 1; i < falsePositions.Length; i++)
{
expect = expect >= falsePositions[i] ? falsePositions[i] : expect;
}
foreach (int x in q)
{
count++;
}
if (count != expect)
{
Assert.Equal(expect, count);
}
}
//
// SkipWhile
//
private static void RunSkipWhile_AllFalse(int size)
{
int[] data = new int[size];
for (int i = 0; i < size; i++) data[i] = i;
ParallelQuery<int> q = data.AsParallel().SkipWhile(delegate (int x) { return false; });
int count = 0;
int expect = size;
foreach (int x in q)
{
count++;
}
if (count != expect)
Assert.Equal(expect, count);
}
private static void RunSkipWhile_AllTrue(int size)
{
int[] data = new int[size];
for (int i = 0; i < size; i++) data[i] = i;
ParallelQuery<int> q = data.AsParallel().SkipWhile(delegate (int x) { return true; });
int count = 0;
int expect = 0;
foreach (int x in q)
{
count++;
}
if (count != expect)
Assert.Equal(expect, count);
}
private static void RunSkipWhile_SomeTrues(int size, params int[] truePositions)
{
int[] data = new int[size];
for (int i = 0; i < size; i++) data[i] = i;
ParallelQuery<int> q = data.AsParallel().SkipWhile(delegate (int x) { return Array.IndexOf(truePositions, x) != -1; });
int count = 0;
// We expect SkipWhile to yield all elements after (and including) the smallest false index in the array.
int expect = 0;
for (int i = 0; i < size; i++)
{
if (Array.IndexOf(truePositions, i) == -1)
break;
expect++;
}
expect = size - expect;
foreach (int x in q)
{
count++;
}
if (count != expect)
{
Assert.Equal(expect, count);
}
}
private static void RunSkipWhile_SomeFalses(int size, params int[] falsePositions)
{
int[] data = new int[size];
for (int i = 0; i < size; i++) data[i] = i;
ParallelQuery<int> q = data.AsParallel().SkipWhile(delegate (int x) { return Array.IndexOf(falsePositions, x) == -1; });
int count = 0;
// We expect SkipWhile to yield all elements after (and including) the smallest false index in the array.
int expect = falsePositions[0];
for (int i = 1; i < falsePositions.Length; i++)
{
expect = expect >= falsePositions[i] ? falsePositions[i] : expect;
}
expect = size - expect;
foreach (int x in q)
{
count++;
}
if (count != expect)
{
Assert.Equal(expect, count);
}
}
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) 2014 by SCIO System-Consulting GmbH & Co. KG. All rights reserved.
//
// 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 UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;
using Scio.CodeGeneration;
using AnimatorAccess;
namespace Scio.AnimatorAccessGenerator
{
/// <summary>
/// Custom inspector for all generated AnimatorAccess classes i.e. that are derived from BaseAnimatorAccess.
/// </summary>
[ExecuteInEditMode]
[CustomEditor(typeof(AnimatorAccess.BaseAnimatorAccess), true)]
public class AnimatorAccessEditor : Editor
{
const string InspectorIconsDir = "/Editor/Inspector/Icons/";
static bool updateCheckFoldOutState = true;
static Texture iconRemove = null;
static Texture iconAdd = null;
static Texture iconObsolete = null;
/// <summary>
/// Class constructor is called after every AssetDatabase.Refresh as the whole assembly is reloaded.
/// </summary>
static AnimatorAccessEditor () {
string dir = "Assets/" + Manager.SharedInstance.InstallDir + InspectorIconsDir;
iconRemove = AssetDatabase.LoadAssetAtPath (dir + "icon_remove.png", typeof(Texture)) as Texture;
iconObsolete = AssetDatabase.LoadAssetAtPath (dir + "icon_obsolete.png", typeof(Texture)) as Texture;
iconAdd = AssetDatabase.LoadAssetAtPath (dir + "icon_add.png", typeof(Texture)) as Texture;
}
/// <summary>
/// The result of the last update check i.e. a class comparison between current class version and the one that
/// will be generated next. This will be updated every Preferences.Key.AutoRefreshInterval seconds.
/// </summary>
List<ClassMemberCompareElement> updateCheck = null;
/// <summary>
/// Set after button Update or Undo was pressed to highlight the Refresh button.
/// </summary>
bool dirty = false;
/// <summary>
/// The last check timestamp to calculate the next update time according to Preferences.Key.AutoRefreshInterval.
/// </summary>
static double lastCheckTimestamp = 0;
void OnEnable () {
CheckForUpdates (false);
}
public override void OnInspectorGUI()
{
AnimatorAccess.BaseAnimatorAccess myTarget = (AnimatorAccess.BaseAnimatorAccess)target;
Attribute[] attrs = Attribute.GetCustomAttributes(myTarget.GetType (), typeof (GeneratedClassAttribute), false);
string version = "Version: ";
if (attrs.Length == 1) {
GeneratedClassAttribute a = (GeneratedClassAttribute)attrs[0];
version += a.CreationDate;
} else {
version += " not available";
}
GUILayout.Label (version);
EditorGUILayout.BeginHorizontal ();
if(GUILayout.Button("Check", EditorStyles.miniButtonLeft)) {
CheckForUpdates (true);
}
if(GUILayout.Button("Update", (updateCheck != null && updateCheck.Count > 0 ? InspectorStyles.MidMiniButtonHighLighted : EditorStyles.miniButtonMid))) {
Manager.SharedInstance.Update (Selection.activeGameObject);
updateCheck = null;
dirty = true;
}
if(GUILayout.Button("Refresh" + (dirty ? "*" : ""), (dirty ? InspectorStyles.RightMiniButtonHighLighted : EditorStyles.miniButtonRight))) {
Manager.SharedInstance.Refresh ();
dirty = false;
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Separator ();
if (EditorApplication.isCompiling || EditorApplication.isUpdating) {
EditorGUILayout.BeginVertical ();
EditorGUILayout.LabelField ("Loading, please wait ...");
EditorGUILayout.EndVertical ();
} else {
if (updateCheck != null) {
CheckForUpdates (false);
if (updateCheck.Count > 0) {
EditorGUILayout.BeginVertical ();
List<ClassMemberCompareElement> errors = updateCheck.FindAll ((element) => element.result == ClassMemberCompareElement.Result.Error);
List<ClassMemberCompareElement> infos = updateCheck.FindAll ((element) => element.result > ClassMemberCompareElement.Result.Error);
// if there are severe errors, show them first above the foldout GUI element
if (errors.Count > 0) {
string errorHintTooltip = "If one of the members is marked as obsolete, it will be removed during generation to avoid compiler errrors.\n\n" +
"If this is not the case, you probably have used the same name for an Animator state and for a parameter too.\n\n" +
"To use identical names for Animator states and parameters, go to settings and define prefixes for states and/or parameters.";
EditorGUILayout.LabelField (new GUIContent (errors.Count + " Naming Conflict(s)", errorHintTooltip), InspectorStyles.LabelRed);
foreach (ClassMemberCompareElement error in errors) {
string errorTooltip = error.Message;
string errorLabel = string.Format ("{0} : {1}", error.Member, errorTooltip);
EditorGUILayout.LabelField (new GUIContent (errorLabel, errorTooltip), InspectorStyles.LabelHighLighted);
}
EditorGUILayout.Separator ();
}
updateCheckFoldOutState = EditorGUILayout.Foldout (updateCheckFoldOutState, updateCheck.Count + " class member(s) to update");
if (updateCheckFoldOutState) {
// compare elements are sorted already: new, obsolete, removed members
foreach (ClassMemberCompareElement c in infos) {
string label = string.Format ("{0}", c.Signature);
string tooltip = "";
switch (c.result) {
case ClassMemberCompareElement.Result.New:
tooltip = string.Format ("{0} {1} {2} will be added", c.memberType, c.ElementType, c.Signature);
EditorGUILayout.LabelField (new GUIContent (label, iconAdd, tooltip));
break;
case ClassMemberCompareElement.Result.Obsolete:
tooltip = string.Format ("{0} {1} {2} will be marked as obsolete", c.memberType, c.ElementType, c.Signature);
EditorGUILayout.LabelField (new GUIContent (label, iconObsolete, tooltip));
break;
case ClassMemberCompareElement.Result.Remove:
tooltip = string.Format ("{0} {1} {2} will be removed", c.memberType, c.ElementType, c.Signature);
EditorGUILayout.LabelField (new GUIContent (label, iconRemove, tooltip));
break;
default:
break;
}
}
}
EditorGUILayout.EndVertical ();
} else {
EditorGUILayout.BeginVertical ();
EditorGUILayout.LabelField (myTarget.GetType ().Name + " is up to date");
EditorGUILayout.EndVertical ();
}
} else {
EditorGUILayout.BeginVertical ();
if (dirty) {
EditorGUILayout.LabelField ("Press 'Refresh' to load updated component " + myTarget.GetType ().Name);
} else {
EditorGUILayout.LabelField ("Press 'Check' to get update information about " + myTarget.GetType ().Name);
}
EditorGUILayout.EndVertical ();
}
}
EditorGUILayout.Separator ();
EditorGUILayout.BeginHorizontal ();
if (Manager.SharedInstance.HasBackup (myTarget)) {
EditorGUILayout.LabelField ("Saved version " + Manager.SharedInstance.GetBackupTimestamp (myTarget));
if (GUILayout.Button ("Undo")) {
Manager.SharedInstance.Undo (myTarget);
updateCheck = null;
dirty = true;
}
} else {
EditorGUILayout.LabelField ("No backup available");
GUILayout.Button ("Undo", InspectorStyles.ButtonDisabled);
}
EditorGUILayout.EndHorizontal ();
}
/// <summary>
/// Updates are performed every Preferences.Key.AutoRefreshInterval seconds to avoid heavy processing load.
/// </summary>
/// <param name="forceCheck">If set to <c>true</c> force check.</param>
void CheckForUpdates (bool forceCheck) {
if (!forceCheck) {
int checkInterval = Preferences.GetInt (Preferences.Key.AutoRefreshInterval);
if (checkInterval <= 0 || EditorApplication.timeSinceStartup - lastCheckTimestamp < checkInterval) {
return;
}
}
updateCheck = Manager.SharedInstance.CheckForUpdates (Selection.activeGameObject);
updateCheck.Sort ((x, y) => {
if (!forceCheck && x.result == ClassMemberCompareElement.Result.Error) {
// unfold results if there are errors but not if this is an automatic check
updateCheckFoldOutState = false;
}
if (x.result != y.result) {
return x.result - y.result;
}
return x.Member.CompareTo (y.Member);
});
lastCheckTimestamp = EditorApplication.timeSinceStartup;
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Management.Storage.ScenarioTest.Util;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.Storage.Blob;
using MS.Test.Common.MsTestLib;
using StorageTestLib;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using StorageBlob = Microsoft.WindowsAzure.Storage.Blob;
namespace Management.Storage.ScenarioTest
{
/// <summary>
/// this class contains all the account related functional test cases for PowerShell cmdlets
/// </summary>
[TestClass]
class CLIContextFunc
{
private static string BlockFilePath;
private static string PageFilePath;
private TestContext testContextInstance;
private static string INVALID_ACCOUNT_NAME = "invalid";
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
//You can use the following additional attributes as you write your tests:
//
//Use ClassInitialize to run code before running the first test in the class
[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext)
{
Trace.WriteLine("ClassInit");
Test.FullClassName = testContext.FullyQualifiedTestClassName;
// import module
string moduleFilePath = Test.Data.Get("ModuleFilePath");
if (moduleFilePath.Length > 0)
PowerShellAgent.ImportModule(moduleFilePath);
BlockFilePath = Path.Combine(Test.Data.Get("TempDir"), FileUtil.GetSpecialFileName());
PageFilePath = Path.Combine(Test.Data.Get("TempDir"), FileUtil.GetSpecialFileName());
FileUtil.CreateDirIfNotExits(Path.GetDirectoryName(BlockFilePath));
FileUtil.CreateDirIfNotExits(Path.GetDirectoryName(PageFilePath));
// Generate block file and page file which are used for uploading
Helper.GenerateMediumFile(BlockFilePath, 1);
Helper.GenerateMediumFile(PageFilePath, 1);
}
//
//Use ClassCleanup to run code after all tests in a class have run
[ClassCleanup()]
public static void MyClassCleanup()
{
Trace.WriteLine("ClasssCleanup");
}
//Use TestInitialize to run code before running each test
[TestInitialize()]
public void MyTestInitialize()
{
Trace.WriteLine("TestInit");
Test.Start(TestContext.FullyQualifiedTestClassName, TestContext.TestName);
}
//Use TestCleanup to run code after each test has run
[TestCleanup()]
public void MyTestCleanup()
{
Trace.WriteLine("TestCleanup");
// do not clean up the blobs here for investigation
// every test case should do cleanup in its init
Test.End(TestContext.FullyQualifiedTestClassName, TestContext.TestName);
}
#endregion
/// <summary>
/// Functional case : for context
/// </summary>
[TestMethod]
[TestCategory(Tag.Function)]
public void StorageContextTest()
{
StorageContextTest(new PowerShellAgent());
}
/// <summary>
/// Negative Functional case :
/// Use an invalid account to run all cmdlets (Negative 2)
/// </summary>
[TestMethod]
[TestCategory(Tag.Function)]
public void UseInvalidAccount()
{
Agent agent = new PowerShellAgent();
// Create an invalid account
string StorageAccountKey = Test.Data.Get("StorageAccountKey");
PowerShellAgent.SetStorageContext(INVALID_ACCOUNT_NAME, StorageAccountKey);
//TODO The test is too large, need to split it into different tests
StorageContainerTest(agent);
StorageQueueTest(agent);
StorageTableTest(agent);
string BlockFilePath = Path.Combine(Test.Data.Get("TempDir"), FileUtil.GetSpecialFileName());
string PageFilePath = Path.Combine(Test.Data.Get("TempDir"), FileUtil.GetSpecialFileName());
FileUtil.CreateDirIfNotExits(Path.GetDirectoryName(BlockFilePath));
FileUtil.CreateDirIfNotExits(Path.GetDirectoryName(PageFilePath));
// Generate block file and page file which are used for uploading
Helper.GenerateMediumFile(BlockFilePath, 1);
Helper.GenerateMediumFile(PageFilePath, 1);
StorageBlobTest(agent, BlockFilePath, StorageBlob.BlobType.BlockBlob);
StorageBlobTest(agent, PageFilePath, StorageBlob.BlobType.PageBlob);
}
internal void StorageContextTest(Agent agent)
{
string StorageAccountName = Test.Data.Get("StorageAccountName");
string StorageAccountKey = Test.Data.Get("StorageAccountKey");
string StorageEndPoint = Test.Data.Get("StorageEndPoint");
Collection<Dictionary<string, object>> comp = new Collection<Dictionary<string, object>>();
bool useHttps = true; //default protocol is https
string[] endPoints = Utility.GetStorageEndPoints(StorageAccountName, useHttps, StorageEndPoint);
comp.Add(new Dictionary<string, object>{
{"StorageAccountName", StorageAccountName},
{"BlobEndPoint", endPoints[0]},
{"QueueEndPoint", endPoints[1]},
{"TableEndPoint", endPoints[2]}
});
//--------------New operation--------------
Test.Assert(agent.NewAzureStorageContext(StorageAccountName, StorageAccountKey, StorageEndPoint), Utility.GenComparisonData("NewAzureStorageContext", true));
// Verification for returned values
agent.OutputValidation(comp);
}
internal void StorageContainerTest(Agent agent)
{
string NEW_CONTAINER_NAME = Utility.GenNameString("astoria-");
//--------------New operation--------------
Test.Assert(!agent.NewAzureStorageContainer(NEW_CONTAINER_NAME), Utility.GenComparisonData("NewAzureStorageContainer", false));
CheckErrorOutput(agent);
//--------------Get operation--------------
Test.Assert(!agent.GetAzureStorageContainer(NEW_CONTAINER_NAME), Utility.GenComparisonData("GetAzureStorageContainer", false));
CheckErrorOutput(agent);
//--------------Set operation--------------
Test.Assert(!agent.SetAzureStorageContainerACL(NEW_CONTAINER_NAME, BlobContainerPublicAccessType.Blob),
"SetAzureStorageContainerACL operation should fail");
CheckErrorOutput(agent);
Test.Assert(!agent.SetAzureStorageContainerACL(NEW_CONTAINER_NAME, BlobContainerPublicAccessType.Container),
"SetAzureStorageContainerACL operation should fail");
CheckErrorOutput(agent);
}
internal void StorageBlobTest(Agent agent, string FilePath, StorageBlob.BlobType Type)
{
string NEW_CONTAINER_NAME = Utility.GenNameString("upload-");
string BlobName = Path.GetFileName(FilePath);
//--------------Upload operation--------------
Test.Assert(!agent.SetAzureStorageBlobContent(FilePath, NEW_CONTAINER_NAME, Type), Utility.GenComparisonData("SendAzureStorageBlob", false));
CheckErrorOutput(agent);
//--------------Get operation--------------
Test.Assert(!agent.GetAzureStorageBlob(BlobName, NEW_CONTAINER_NAME), Utility.GenComparisonData("GetAzureStorageBlob", false));
CheckErrorOutput(agent);
//--------------Remove operation--------------
Test.Assert(!agent.RemoveAzureStorageBlob(BlobName, NEW_CONTAINER_NAME), Utility.GenComparisonData("RemoveAzureStorageBlob", false));
CheckErrorOutput(agent);
}
internal void StorageQueueTest(Agent agent)
{
string NEW_QUEUE_NAME = Utility.GenNameString("redmond-");
//--------------New operation--------------
Test.Assert(!agent.NewAzureStorageQueue(NEW_QUEUE_NAME), Utility.GenComparisonData("NewAzureStorageQueue", false));
CheckErrorOutput(agent);
//--------------Get operation--------------
Test.Assert(!agent.GetAzureStorageQueue(NEW_QUEUE_NAME), Utility.GenComparisonData("GetAzureStorageQueue", false));
CheckErrorOutput(agent);
//--------------Remove operation--------------
Test.Assert(!agent.RemoveAzureStorageQueue(NEW_QUEUE_NAME), Utility.GenComparisonData("RemoveAzureStorageQueue", false));
CheckErrorOutput(agent);
}
internal void StorageTableTest(Agent agent)
{
string NEW_TABLE_NAME = Utility.GenNameString("Washington");
//--------------New operation--------------
Test.Assert(!agent.NewAzureStorageTable(NEW_TABLE_NAME), Utility.GenComparisonData("NewAzureStorageTable", false));
CheckErrorOutput(agent);
//--------------Get operation--------------
Test.Assert(!agent.GetAzureStorageTable(NEW_TABLE_NAME), Utility.GenComparisonData("GetAzureStorageTable", false));
CheckErrorOutput(agent);
//--------------Remove operation--------------
Test.Assert(!agent.RemoveAzureStorageTable(NEW_TABLE_NAME), Utility.GenComparisonData("RemoveAzureStorageTable", false));
CheckErrorOutput(agent);
}
internal void CheckErrorOutput(Agent agent)
{
Test.Assert(agent.Output.Count == 0, "Only 0 row returned : {0}", agent.Output.Count);
//the same error may output different error messages in different environments
bool expectedError = agent.ErrorMessages[0].StartsWith("The remote server returned an error: (502) Bad Gateway") ||
agent.ErrorMessages[0].StartsWith("The remote name could not be resolved") ||
agent.ErrorMessages[0].StartsWith("The operation has timed out");
Test.Assert(expectedError, "use invalid storage account should return 502 or time out, actually it's {0}", agent.ErrorMessages[0]);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ListDictionary.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Collections.Specialized {
using System.Collections;
using Microsoft.Win32;
/// <devdoc>
/// <para>
/// This is a simple implementation of IDictionary using a singly linked list. This
/// will be smaller and faster than a Hashtable if the number of elements is 10 or less.
/// This should not be used if performance is important for large numbers of elements.
/// </para>
/// </devdoc>
[Serializable]
public class ListDictionary: IDictionary {
DictionaryNode head;
int version;
int count;
IComparer comparer;
[NonSerialized]
private Object _syncRoot;
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public ListDictionary() {
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public ListDictionary(IComparer comparer) {
this.comparer = comparer;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object this[object key] {
get {
if (key == null) {
throw new ArgumentNullException("key", SR.GetString(SR.ArgumentNull_Key));
}
DictionaryNode node = head;
if (comparer == null) {
while (node != null) {
object oldKey = node.key;
if ( oldKey!= null && oldKey.Equals(key)) {
return node.value;
}
node = node.next;
}
}
else {
while (node != null) {
object oldKey = node.key;
if (oldKey != null && comparer.Compare(oldKey, key) == 0) {
return node.value;
}
node = node.next;
}
}
return null;
}
set {
if (key == null) {
throw new ArgumentNullException("key", SR.GetString(SR.ArgumentNull_Key));
}
version++;
DictionaryNode last = null;
DictionaryNode node;
for (node = head; node != null; node = node.next) {
object oldKey = node.key;
if ((comparer == null) ? oldKey.Equals(key) : comparer.Compare(oldKey, key) == 0) {
break;
}
last = node;
}
if (node != null) {
// Found it
node.value = value;
return;
}
// Not found, so add a new one
DictionaryNode newNode = new DictionaryNode();
newNode.key = key;
newNode.value = value;
if (last != null) {
last.next = newNode;
}
else {
head = newNode;
}
count++;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int Count {
get {
return count;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public ICollection Keys {
get {
return new NodeKeyValueCollection(this, true);
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool IsReadOnly {
get {
return false;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool IsFixedSize {
get {
return false;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool IsSynchronized {
get {
return false;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object SyncRoot {
get {
if( _syncRoot == null) {
System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public ICollection Values {
get {
return new NodeKeyValueCollection(this, false);
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Add(object key, object value) {
if (key == null) {
throw new ArgumentNullException("key", SR.GetString(SR.ArgumentNull_Key));
}
version++;
DictionaryNode last = null;
DictionaryNode node;
for (node = head; node != null; node = node.next) {
object oldKey = node.key;
if ((comparer == null) ? oldKey.Equals(key) : comparer.Compare(oldKey, key) == 0) {
throw new ArgumentException(SR.GetString(SR.Argument_AddingDuplicate));
}
last = node;
}
// Not found, so add a new one
DictionaryNode newNode = new DictionaryNode();
newNode.key = key;
newNode.value = value;
if (last != null) {
last.next = newNode;
}
else {
head = newNode;
}
count++;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Clear() {
count = 0;
head = null;
version++;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool Contains(object key) {
if (key == null) {
throw new ArgumentNullException("key", SR.GetString(SR.ArgumentNull_Key));
}
for (DictionaryNode node = head; node != null; node = node.next) {
object oldKey = node.key;
if ((comparer == null) ? oldKey.Equals(key) : comparer.Compare(oldKey, key) == 0) {
return true;
}
}
return false;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void CopyTo(Array array, int index) {
if (array==null)
throw new ArgumentNullException("array");
if (index < 0)
throw new ArgumentOutOfRangeException("index", SR.GetString(SR.ArgumentOutOfRange_NeedNonNegNum));
if (array.Length - index < count)
throw new ArgumentException(SR.GetString(SR.Arg_InsufficientSpace));
for (DictionaryNode node = head; node != null; node = node.next) {
array.SetValue(new DictionaryEntry(node.key, node.value), index);
index++;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public IDictionaryEnumerator GetEnumerator() {
return new NodeEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator() {
return new NodeEnumerator(this);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Remove(object key) {
if (key == null) {
throw new ArgumentNullException("key", SR.GetString(SR.ArgumentNull_Key));
}
version++;
DictionaryNode last = null;
DictionaryNode node;
for (node = head; node != null; node = node.next) {
object oldKey = node.key;
if ((comparer == null) ? oldKey.Equals(key) : comparer.Compare(oldKey, key) == 0) {
break;
}
last = node;
}
if (node == null) {
return;
}
if (node == head) {
head = node.next;
} else {
last.next = node.next;
}
count--;
}
private class NodeEnumerator : IDictionaryEnumerator {
ListDictionary list;
DictionaryNode current;
int version;
bool start;
public NodeEnumerator(ListDictionary list) {
this.list = list;
version = list.version;
start = true;
current = null;
}
public object Current {
get {
return Entry;
}
}
public DictionaryEntry Entry {
get {
if (current == null) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_EnumOpCantHappen));
}
return new DictionaryEntry(current.key, current.value);
}
}
public object Key {
get {
if (current == null) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_EnumOpCantHappen));
}
return current.key;
}
}
public object Value {
get {
if (current == null) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_EnumOpCantHappen));
}
return current.value;
}
}
public bool MoveNext() {
if (version != list.version) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_EnumFailedVersion));
}
if (start) {
current = list.head;
start = false;
}
else if (current != null) {
current = current.next;
}
return (current != null);
}
public void Reset() {
if (version != list.version) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_EnumFailedVersion));
}
start = true;
current = null;
}
}
private class NodeKeyValueCollection : ICollection {
ListDictionary list;
bool isKeys;
public NodeKeyValueCollection(ListDictionary list, bool isKeys) {
this.list = list;
this.isKeys = isKeys;
}
void ICollection.CopyTo(Array array, int index) {
if (array==null)
throw new ArgumentNullException("array");
if (index < 0)
throw new ArgumentOutOfRangeException("index", SR.GetString(SR.ArgumentOutOfRange_NeedNonNegNum));
for (DictionaryNode node = list.head; node != null; node = node.next) {
array.SetValue(isKeys ? node.key : node.value, index);
index++;
}
}
int ICollection.Count {
get {
int count = 0;
for (DictionaryNode node = list.head; node != null; node = node.next) {
count++;
}
return count;
}
}
bool ICollection.IsSynchronized {
get {
return false;
}
}
object ICollection.SyncRoot {
get {
return list.SyncRoot;
}
}
IEnumerator IEnumerable.GetEnumerator() {
return new NodeKeyValueEnumerator(list, isKeys);
}
private class NodeKeyValueEnumerator: IEnumerator {
ListDictionary list;
DictionaryNode current;
int version;
bool isKeys;
bool start;
public NodeKeyValueEnumerator(ListDictionary list, bool isKeys) {
this.list = list;
this.isKeys = isKeys;
this.version = list.version;
this.start = true;
this.current = null;
}
public object Current {
get {
if (current == null) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_EnumOpCantHappen));
}
return isKeys ? current.key : current.value;
}
}
public bool MoveNext() {
if (version != list.version) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_EnumFailedVersion));
}
if (start) {
current = list.head;
start = false;
}
else if (current != null) {
current = current.next;
}
return (current != null);
}
public void Reset() {
if (version != list.version) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_EnumFailedVersion));
}
start = true;
current = null;
}
}
}
[Serializable]
private class DictionaryNode {
public object key;
public object value;
public DictionaryNode next;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.InteropServices;
namespace System.Numerics.Matrices
{
/// <summary>
/// Represents a matrix of double precision floating-point values defined by its number of columns and rows
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct Matrix1x2: IEquatable<Matrix1x2>, IMatrix
{
public const int ColumnCount = 1;
public const int RowCount = 2;
static Matrix1x2()
{
Zero = new Matrix1x2(0);
}
/// <summary>
/// Gets the smallest value used to determine equality
/// </summary>
public double Epsilon { get { return MatrixHelper.Epsilon; } }
/// <summary>
/// Constant Matrix1x2 with all values initialized to zero
/// </summary>
public static readonly Matrix1x2 Zero;
/// <summary>
/// Initializes a Matrix1x2 with all of it values specifically set
/// </summary>
/// <param name="m11">The column 1, row 1 value</param>
/// <param name="m12">The column 1, row 2 value</param>
public Matrix1x2(double m11,
double m12)
{
M11 = m11;
M12 = m12;
}
/// <summary>
/// Initialized a Matrix1x2 with all values set to the same value
/// </summary>
/// <param name="value">The value to set all values to</param>
public Matrix1x2(double value)
{
M11 =
M12 = value;
}
public double M11;
public double M12;
public unsafe double this[int col, int row]
{
get
{
if (col < 0 || col >= ColumnCount)
throw new ArgumentOutOfRangeException("col", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", ColumnCount, col));
if (row < 0 || row >= RowCount)
throw new ArgumentOutOfRangeException("row", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", RowCount, row));
fixed (Matrix1x2* p = &this)
{
double* d = (double*)p;
return d[row * ColumnCount + col];
}
}
set
{
if (col < 0 || col >= ColumnCount)
throw new ArgumentOutOfRangeException("col", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", ColumnCount, col));
if (row < 0 || row >= RowCount)
throw new ArgumentOutOfRangeException("row", String.Format("Expected greater than or equal to 0 and less than {0}, found {1}.", RowCount, row));
fixed (Matrix1x2* p = &this)
{
double* d = (double*)p;
d[row * ColumnCount + col] = value;
}
}
}
/// <summary>
/// Gets the number of columns in the matrix
/// </summary>
public int Columns { get { return ColumnCount; } }
/// <summary>
/// Get the number of rows in the matrix
/// </summary>
public int Rows { get { return RowCount; } }
public override bool Equals(object obj)
{
if (obj is Matrix1x2)
return this == (Matrix1x2)obj;
return false;
}
public bool Equals(Matrix1x2 other)
{
return this == other;
}
public unsafe override int GetHashCode()
{
fixed (Matrix1x2* p = &this)
{
int* x = (int*)p;
unchecked
{
return 0xFFE1
+ 7 * ((((x[00] ^ x[01]) << 0)) << 0)
+ 7 * ((((x[01] ^ x[02]) << 0)) << 1);
}
}
}
public override string ToString()
{
return "Matrix1x2: "
+ String.Format("{{|{0:00}|}}", M11)
+ String.Format("{{|{0:00}|}}", M12);
}
/// <summary>
/// Creates and returns a transposed matrix
/// </summary>
/// <returns>Matrix with transposed values</returns>
public Matrix2x1 Transpose()
{
return new Matrix2x1(M11, M12);
}
public static bool operator ==(Matrix1x2 matrix1, Matrix1x2 matrix2)
{
return MatrixHelper.AreEqual(matrix1.M11, matrix2.M11)
&& MatrixHelper.AreEqual(matrix1.M12, matrix2.M12);
}
public static bool operator !=(Matrix1x2 matrix1, Matrix1x2 matrix2)
{
return MatrixHelper.NotEqual(matrix1.M11, matrix2.M11)
|| MatrixHelper.NotEqual(matrix1.M12, matrix2.M12);
}
public static Matrix1x2 operator +(Matrix1x2 matrix1, Matrix1x2 matrix2)
{
double m11 = matrix1.M11 + matrix2.M11;
double m12 = matrix1.M12 + matrix2.M12;
return new Matrix1x2(m11,
m12);
}
public static Matrix1x2 operator -(Matrix1x2 matrix1, Matrix1x2 matrix2)
{
double m11 = matrix1.M11 - matrix2.M11;
double m12 = matrix1.M12 - matrix2.M12;
return new Matrix1x2(m11,
m12);
}
public static Matrix1x2 operator *(Matrix1x2 matrix, double scalar)
{
double m11 = matrix.M11 * scalar;
double m12 = matrix.M12 * scalar;
return new Matrix1x2(m11,
m12);
}
public static Matrix1x2 operator *(double scalar, Matrix1x2 matrix)
{
double m11 = scalar * matrix.M11;
double m12 = scalar * matrix.M12;
return new Matrix1x2(m11,
m12);
}
public static Matrix2x2 operator *(Matrix1x2 matrix1, Matrix2x1 matrix2)
{
double m11 = matrix1.M11 * matrix2.M11;
double m21 = matrix1.M11 * matrix2.M21;
double m12 = matrix1.M12 * matrix2.M11;
double m22 = matrix1.M12 * matrix2.M21;
return new Matrix2x2(m11, m21,
m12, m22);
}
public static Matrix3x2 operator *(Matrix1x2 matrix1, Matrix3x1 matrix2)
{
double m11 = matrix1.M11 * matrix2.M11;
double m21 = matrix1.M11 * matrix2.M21;
double m31 = matrix1.M11 * matrix2.M31;
double m12 = matrix1.M12 * matrix2.M11;
double m22 = matrix1.M12 * matrix2.M21;
double m32 = matrix1.M12 * matrix2.M31;
return new Matrix3x2(m11, m21, m31,
m12, m22, m32);
}
public static Matrix4x2 operator *(Matrix1x2 matrix1, Matrix4x1 matrix2)
{
double m11 = matrix1.M11 * matrix2.M11;
double m21 = matrix1.M11 * matrix2.M21;
double m31 = matrix1.M11 * matrix2.M31;
double m41 = matrix1.M11 * matrix2.M41;
double m12 = matrix1.M12 * matrix2.M11;
double m22 = matrix1.M12 * matrix2.M21;
double m32 = matrix1.M12 * matrix2.M31;
double m42 = matrix1.M12 * matrix2.M41;
return new Matrix4x2(m11, m21, m31, m41,
m12, m22, m32, m42);
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.IO;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Summary description for TableRowCtl.
/// </summary>
internal class TableRowCtl : System.Windows.Forms.UserControl, IProperty
{
private XmlNode _TableRow;
private DesignXmlDraw _Draw;
// flags for controlling whether syntax changed for a particular property
private bool fHidden, fToggle, fHeight;
private System.Windows.Forms.GroupBox grpBoxVisibility;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox tbHidden;
private System.Windows.Forms.ComboBox cbToggle;
private System.Windows.Forms.Button bHidden;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox tbRowHeight;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal TableRowCtl(DesignXmlDraw dxDraw, XmlNode tr)
{
_TableRow = tr;
_Draw = dxDraw;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues(tr);
}
private void InitValues(XmlNode node)
{
// Handle Width definition
this.tbRowHeight.Text = _Draw.GetElementValue(node, "Height", "");
// Handle Visiblity definition
XmlNode visNode = _Draw.GetNamedChildNode(node, "Visibility");
if (visNode != null)
{
this.tbHidden.Text = _Draw.GetElementValue(visNode, "Hidden", "");
this.cbToggle.Text = _Draw.GetElementValue(visNode, "ToggleItem", "");
}
IEnumerable list = _Draw.GetReportItems("//Textbox");
if (list != null)
{
foreach (XmlNode tNode in list)
{
XmlAttribute name = tNode.Attributes["Name"];
if (name != null && name.Value != null && name.Value.Length > 0)
cbToggle.Items.Add(name.Value);
}
}
// nothing has changed now
fHeight = fHidden = fToggle = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region 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.grpBoxVisibility = new System.Windows.Forms.GroupBox();
this.bHidden = new System.Windows.Forms.Button();
this.cbToggle = new System.Windows.Forms.ComboBox();
this.tbHidden = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.tbRowHeight = new System.Windows.Forms.TextBox();
this.grpBoxVisibility.SuspendLayout();
this.SuspendLayout();
//
// grpBoxVisibility
//
this.grpBoxVisibility.Controls.Add(this.bHidden);
this.grpBoxVisibility.Controls.Add(this.cbToggle);
this.grpBoxVisibility.Controls.Add(this.tbHidden);
this.grpBoxVisibility.Controls.Add(this.label3);
this.grpBoxVisibility.Controls.Add(this.label2);
this.grpBoxVisibility.Location = new System.Drawing.Point(8, 8);
this.grpBoxVisibility.Name = "grpBoxVisibility";
this.grpBoxVisibility.Size = new System.Drawing.Size(432, 80);
this.grpBoxVisibility.TabIndex = 1;
this.grpBoxVisibility.TabStop = false;
this.grpBoxVisibility.Text = "Visibility";
//
// bHidden
//
this.bHidden.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.bHidden.Location = new System.Drawing.Point(400, 26);
this.bHidden.Name = "bHidden";
this.bHidden.Size = new System.Drawing.Size(22, 16);
this.bHidden.TabIndex = 1;
this.bHidden.Tag = "visibility";
this.bHidden.Text = "fx";
this.bHidden.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bHidden.Click += new System.EventHandler(this.bExpr_Click);
//
// cbToggle
//
this.cbToggle.Location = new System.Drawing.Point(168, 48);
this.cbToggle.Name = "cbToggle";
this.cbToggle.Size = new System.Drawing.Size(152, 21);
this.cbToggle.TabIndex = 2;
this.cbToggle.TextChanged += new System.EventHandler(this.cbToggle_SelectedIndexChanged);
this.cbToggle.SelectedIndexChanged += new System.EventHandler(this.cbToggle_SelectedIndexChanged);
//
// tbHidden
//
this.tbHidden.Location = new System.Drawing.Point(168, 24);
this.tbHidden.Name = "tbHidden";
this.tbHidden.Size = new System.Drawing.Size(224, 20);
this.tbHidden.TabIndex = 0;
this.tbHidden.Text = "";
this.tbHidden.TextChanged += new System.EventHandler(this.tbHidden_TextChanged);
//
// label3
//
this.label3.Location = new System.Drawing.Point(16, 48);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(152, 23);
this.label3.TabIndex = 1;
this.label3.Text = "Toggle Item (Textbox name)";
//
// label2
//
this.label2.Location = new System.Drawing.Point(16, 24);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(120, 23);
this.label2.TabIndex = 0;
this.label2.Text = "Hidden (initial visibility)";
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 104);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(80, 16);
this.label1.TabIndex = 2;
this.label1.Text = "Row Height";
//
// tbRowHeight
//
this.tbRowHeight.Location = new System.Drawing.Point(88, 104);
this.tbRowHeight.Name = "tbRowHeight";
this.tbRowHeight.TabIndex = 3;
this.tbRowHeight.Text = "";
this.tbRowHeight.TextChanged += new System.EventHandler(this.tbRowHeight_TextChanged);
//
// TableRowCtl
//
this.Controls.Add(this.tbRowHeight);
this.Controls.Add(this.label1);
this.Controls.Add(this.grpBoxVisibility);
this.Name = "TableRowCtl";
this.Size = new System.Drawing.Size(472, 288);
this.grpBoxVisibility.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
public bool IsValid()
{
try
{
if (fHeight)
DesignerUtility.ValidateSize(this.tbRowHeight.Text, true, false);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Height is Invalid");
return false;
}
if (fHidden)
{
string vh = this.tbHidden.Text.Trim();
if (vh.Length > 0)
{
if (vh.StartsWith("="))
{}
else
{
vh = vh.ToLower();
switch (vh)
{
case "true":
case "false":
break;
default:
MessageBox.Show(String.Format("{0} must be an expression or 'true' or 'false'", tbHidden.Text), "Hidden is Invalid");
return false;
}
}
}
}
return true;
}
public void Apply()
{
// take information in control and apply to all the style nodes
// Only change information that has been marked as modified;
// this way when group is selected it is possible to change just
// the items you want and keep the rest the same.
ApplyChanges(this._TableRow);
// nothing has changed now
fHeight = fHidden = fToggle = false;
}
private void ApplyChanges(XmlNode rNode)
{
if (fHidden || fToggle)
{
XmlNode visNode = _Draw.SetElement(rNode, "Visibility", null);
if (fHidden)
{
string vh = this.tbHidden.Text.Trim();
if (vh.Length > 0)
_Draw.SetElement(visNode, "Hidden", vh);
else
_Draw.RemoveElement(visNode, "Hidden");
}
if (fToggle)
_Draw.SetElement(visNode, "ToggleItem", this.cbToggle.Text);
}
if (fHeight) // already validated
_Draw.SetElement(rNode, "Height", this.tbRowHeight.Text);
}
private void tbHidden_TextChanged(object sender, System.EventArgs e)
{
fHidden = true;
}
private void tbRowHeight_TextChanged(object sender, System.EventArgs e)
{
fHeight = true;
}
private void cbToggle_SelectedIndexChanged(object sender, System.EventArgs e)
{
fToggle = true;
}
private void bExpr_Click(object sender, System.EventArgs e)
{
Button b = sender as Button;
if (b == null)
return;
Control c = null;
switch (b.Tag as string)
{
case "visibility":
c = tbHidden;
break;
}
if (c == null)
return;
using (DialogExprEditor ee = new DialogExprEditor(_Draw, c.Text, _TableRow))
{
DialogResult dr = ee.ShowDialog();
if (dr == DialogResult.OK)
c.Text = ee.Expression;
return;
}
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Diagnostics;
using System.Dynamic.Utils;
#if SILVERLIGHT
using System.Core;
#endif
#if CLR2
namespace Microsoft.Scripting.Ast {
#else
namespace System.Linq.Expressions {
#endif
/// <summary>
/// Specifies what kind of jump this <see cref="GotoExpression"/> represents.
/// </summary>
public enum GotoExpressionKind {
/// <summary>
/// A <see cref="GotoExpression"/> that represents a jump to some location.
/// </summary>
Goto,
/// <summary>
/// A <see cref="GotoExpression"/> that represents a return statement.
/// </summary>
Return,
/// <summary>
/// A <see cref="GotoExpression"/> that represents a break statement.
/// </summary>
Break,
/// <summary>
/// A <see cref="GotoExpression"/> that represents a continue statement.
/// </summary>
Continue,
}
/// <summary>
/// Represents an unconditional jump. This includes return statements, break and continue statements, and other jumps.
/// </summary>
#if !SILVERLIGHT
[DebuggerTypeProxy(typeof(Expression.GotoExpressionProxy))]
#endif
public sealed class GotoExpression : Expression {
private readonly GotoExpressionKind _kind;
private readonly Expression _value;
private readonly LabelTarget _target;
private readonly Type _type;
internal GotoExpression(GotoExpressionKind kind, LabelTarget target, Expression value, Type type) {
_kind = kind;
_value = value;
_target = target;
_type = type;
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
/// </summary>
/// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
public sealed override Type Type {
get { return _type; }
}
/// <summary>
/// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
/// </summary>
/// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
public sealed override ExpressionType NodeType {
get { return ExpressionType.Goto; }
}
/// <summary>
/// The value passed to the target, or null if the target is of type
/// System.Void.
/// </summary>
public Expression Value {
get { return _value; }
}
/// <summary>
/// The target label where this node jumps to.
/// </summary>
public LabelTarget Target {
get { return _target; }
}
/// <summary>
/// The kind of the goto. For information purposes only.
/// </summary>
public GotoExpressionKind Kind {
get { return _kind; }
}
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor) {
return visitor.VisitGoto(this);
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="target">The <see cref="Target" /> property of the result.</param>
/// <param name="value">The <see cref="Value" /> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public GotoExpression Update(LabelTarget target, Expression value) {
if (target == Target && value == Value) {
return this;
}
return Expression.MakeGoto(Kind, target, value, Type);
}
}
public partial class Expression {
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a break statement.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Break,
/// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, and a null value to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Break(LabelTarget target) {
return MakeGoto(GotoExpressionKind.Break, target, null, typeof(void));
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a break statement. The value passed to the label upon jumping can be specified.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <param name="value">The value that will be passed to the associated label upon jumping.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Break,
/// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
/// and <paramref name="value"/> to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Break(LabelTarget target, Expression value) {
return MakeGoto(GotoExpressionKind.Break, target, value, typeof(void));
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a break statement with the specified type.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Break,
/// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
/// and the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>.
/// </returns>
public static GotoExpression Break(LabelTarget target, Type type) {
return MakeGoto(GotoExpressionKind.Break, target, null, type);
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a break statement with the specified type.
/// The value passed to the label upon jumping can be specified.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <param name="value">The value that will be passed to the associated label upon jumping.</param>
/// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Break,
/// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
/// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>,
/// and <paramref name="value"/> to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Break(LabelTarget target, Expression value, Type type) {
return MakeGoto(GotoExpressionKind.Break, target, value, type);
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a continue statement.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Continue,
/// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
/// and a null value to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Continue(LabelTarget target) {
return MakeGoto(GotoExpressionKind.Continue, target, null, typeof(void));
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a continue statement with the specified type.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Continue,
/// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
/// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>,
/// and a null value to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Continue(LabelTarget target, Type type) {
return MakeGoto(GotoExpressionKind.Continue, target, null, type);
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a return statement.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Return,
/// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
/// and a null value to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Return(LabelTarget target) {
return MakeGoto(GotoExpressionKind.Return, target, null, typeof(void));
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a return statement with the specified type.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Return,
/// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
/// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>,
/// and a null value to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Return(LabelTarget target, Type type) {
return MakeGoto(GotoExpressionKind.Return, target, null, type);
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a return statement. The value passed to the label upon jumping can be specified.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <param name="value">The value that will be passed to the associated label upon jumping.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Continue,
/// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
/// and <paramref name="value"/> to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Return(LabelTarget target, Expression value) {
return MakeGoto(GotoExpressionKind.Return, target, value, typeof(void));
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a return statement with the specified type.
/// The value passed to the label upon jumping can be specified.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <param name="value">The value that will be passed to the associated label upon jumping.</param>
/// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Continue,
/// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
/// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>,
/// and <paramref name="value"/> to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Return(LabelTarget target, Expression value, Type type) {
return MakeGoto(GotoExpressionKind.Return, target, value, type);
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a goto.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Goto,
/// the <see cref="P:GotoExpression.Target"/> property set to the specified value,
/// and a null value to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Goto(LabelTarget target) {
return MakeGoto(GotoExpressionKind.Goto, target, null, typeof(void));
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a goto with the specified type.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Goto,
/// the <see cref="P:GotoExpression.Target"/> property set to the specified value,
/// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>,
/// and a null value to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Goto(LabelTarget target, Type type) {
return MakeGoto(GotoExpressionKind.Goto, target, null, type);
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a goto. The value passed to the label upon jumping can be specified.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <param name="value">The value that will be passed to the associated label upon jumping.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Goto,
/// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
/// and <paramref name="value"/> to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Goto(LabelTarget target, Expression value) {
return MakeGoto(GotoExpressionKind.Goto, target, value, typeof(void));
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a goto with the specified type.
/// The value passed to the label upon jumping can be specified.
/// </summary>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <param name="value">The value that will be passed to the associated label upon jumping.</param>
/// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Goto,
/// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
/// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>,
/// and <paramref name="value"/> to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression Goto(LabelTarget target, Expression value, Type type) {
return MakeGoto(GotoExpressionKind.Goto, target, value, type);
}
/// <summary>
/// Creates a <see cref="GotoExpression"/> representing a jump of the specified <see cref="GotoExpressionKind"/>.
/// The value passed to the label upon jumping can also be specified.
/// </summary>
/// <param name="kind">The <see cref="GotoExpressionKind"/> of the <see cref="GotoExpression"/>.</param>
/// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param>
/// <param name="value">The value that will be passed to the associated label upon jumping.</param>
/// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param>
/// <returns>
/// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to <paramref name="kind"/>,
/// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>,
/// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>,
/// and <paramref name="value"/> to be passed to the target label upon jumping.
/// </returns>
public static GotoExpression MakeGoto(GotoExpressionKind kind, LabelTarget target, Expression value, Type type) {
ValidateGoto(target, ref value, "target", "value");
return new GotoExpression(kind, target, value, type);
}
private static void ValidateGoto(LabelTarget target, ref Expression value, string targetParameter, string valueParameter) {
ContractUtils.RequiresNotNull(target, targetParameter);
if (value == null) {
if (target.Type != typeof(void)) throw Error.LabelMustBeVoidOrHaveExpression();
} else {
ValidateGotoType(target.Type, ref value, valueParameter);
}
}
// Standard argument validation, taken from ValidateArgumentTypes
private static void ValidateGotoType(Type expectedType, ref Expression value, string paramName) {
RequiresCanRead(value, paramName);
if (expectedType != typeof(void)) {
if (!TypeUtils.AreReferenceAssignable(expectedType, value.Type)) {
// C# autoquotes return values, so we'll do that here
if (!TryQuote(expectedType, ref value)) {
throw Error.ExpressionTypeDoesNotMatchLabel(value.Type, expectedType);
}
}
}
}
}
}
| |
//
// Util.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Text;
using AppKit;
using CoreGraphics;
using CoreImage;
using CoreText;
using Foundation;
using ObjCRuntime;
using Xwt.Backends;
using Xwt.Drawing;
namespace Xwt.Mac
{
public static class Util
{
public static readonly string DeviceRGBString = NSColorSpace.DeviceRGB.ToString ();
static CGColorSpace deviceRGB, pattern;
public static CGColorSpace DeviceRGBColorSpace {
get {
if (deviceRGB == null)
deviceRGB = CGColorSpace.CreateDeviceRGB ();
return deviceRGB;
}
}
public static CGColorSpace PatternColorSpace {
get {
if (pattern == null)
pattern = CGColorSpace.CreatePattern (null);
return pattern;
}
}
public static void SetAttributedString (this NSTextView view, NSAttributedString str, bool canOverrideTextColor)
{
var textColor = view.TextColor;
view.TextStorage.SetString (str);
// Workaround:
// Apply the previous view's TextColor,
// otherwise it would be reset to Black by the line above.
if (canOverrideTextColor && textColor != null)
view.TextColor = textColor;
}
public static double WidgetX (this NSView v)
{
return (double) v.Frame.X;
}
public static double WidgetY (this NSView v)
{
return (double) v.Frame.Y;
}
public static double WidgetWidth (this NSView v)
{
return (double) (v.Frame.Width);
}
public static double WidgetHeight (this NSView v)
{
return (double) (v.Frame.Height);
}
public static Rectangle WidgetBounds (this NSView v)
{
return new Rectangle (v.WidgetX(), v.WidgetY(), v.WidgetWidth(), v.WidgetHeight());
}
public static Point WidgetLocation (this NSView v)
{
return new Point (v.WidgetX (), v.WidgetY ());
}
public static void SetWidgetBounds (this NSView v, Rectangle rect)
{
nfloat y = (nfloat)rect.Y;
if (v.Superview != null)
y = v.Superview.Frame.Height - y - (float)rect.Height;
v.Frame = new CGRect ((nfloat)rect.X, y, (nfloat)rect.Width, (nfloat)rect.Height);
}
public static Alignment ToAlignment (this NSTextAlignment align)
{
switch (align) {
case NSTextAlignment.Center: return Alignment.Center;
case NSTextAlignment.Right: return Alignment.End;
default: return Alignment.Start;
}
}
public static NSTextAlignment ToNSTextAlignment (this Alignment align)
{
switch (align) {
case Alignment.Center: return NSTextAlignment.Center;
case Alignment.End: return NSTextAlignment.Right;
default: return NSTextAlignment.Left;
}
}
public static NSColor ToNSColor (this Color col)
{
return NSColor.FromDeviceRgba ((float)col.Red, (float)col.Green, (float)col.Blue, (float)col.Alpha);
}
static readonly CGColorSpace DeviceRgbColorSpace = CGColorSpace.CreateDeviceRGB ();
public static CGColor ToCGColor (this Color col)
{
return new CGColor (DeviceRgbColorSpace, new nfloat[] {
(nfloat)col.Red, (nfloat)col.Green, (nfloat)col.Blue, (nfloat)col.Alpha
});
}
public static Color ToXwtColor (this NSColor col)
{
var calibrated = col.UsingColorSpace (DeviceRGBString);
if (calibrated != null)
return new Color (calibrated.RedComponent, calibrated.GreenComponent, calibrated.BlueComponent, calibrated.AlphaComponent);
// some system colors can not be calibrated and UsingColorSpace returns null.
// Use CGColor in this case, which should match the device already.
return col.CGColor.ToXwtColor();
}
public static Color ToXwtColor (this CGColor col)
{
var cs = col.Components;
return new Color (cs[0], cs[1], cs[2], col.Alpha);
}
public static CGSize ToCGSize (this Size s)
{
return new CGSize ((nfloat)s.Width, (nfloat)s.Height);
}
public static Size ToXwtSize (this CGSize s)
{
return new Size (s.Width, s.Height);
}
public static CGRect ToCGRect (this Rectangle r)
{
return new CGRect ((nfloat)r.X, (nfloat)r.Y, (nfloat)r.Width, (nfloat)r.Height);
}
public static Rectangle ToXwtRect (this CGRect r)
{
return new Rectangle (r.X, r.Y, r.Width, r.Height);
}
public static CGPoint ToCGPoint (this Point r)
{
return new CGPoint ((nfloat)r.X, (nfloat)r.Y);
}
public static Point ToXwtPoint (this CGPoint p)
{
return new Point (p.X, p.Y);
}
// /System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Headers/IconsCore.h
public static int ToIconType (string id)
{
switch (id) {
case StockIconId.Error: return 1937010544; // 'stop'
case StockIconId.Warning: return 1667331444; // 'caut'
case StockIconId.Information: return 1852798053; // 'note'
case StockIconId.Question: return 1903519091; // 'ques'
case StockIconId.Remove: return 1952736620; // 'tdel'
}
return 0;
}
/* To get the above int values, pass the four char code thru this:
public static int C (string code)
{
return ((int)code[0]) << 24
| ((int)code[1]) << 16
| ((int)code[2]) << 8
| ((int)code[3]);
}
*/
public static CGSize ToIconSize (IconSize size)
{
switch (size) {
case IconSize.Small: return new CGSize (16f, 16f);
case IconSize.Large: return new CGSize (64f, 64f);
}
return new CGSize (32f, 32f);
}
public static string ToUTI (this TransferDataType dt)
{
if (dt == TransferDataType.Uri)
return NSPasteboard.NSUrlType;
if (dt == TransferDataType.Text)
return NSPasteboard.NSStringType;
if (dt == TransferDataType.Rtf)
return NSPasteboard.NSRtfType;
if (dt == TransferDataType.Html)
return NSPasteboard.NSHtmlType;
if (dt == TransferDataType.Image)
return NSPasteboard.NSTiffType;
return dt.Id;
}
/*public static void MakeCopiable<T> () where T:ICopiableObject
{
// Nothing to do for XamMac
}
public static void DrainObjectCopyPool ()
{
// Nothing to do for XamMac
}*/
public static NSBitmapImageFileType ToMacFileType (this ImageFileType type)
{
switch (type) {
case ImageFileType.Png: return NSBitmapImageFileType.Png;
case ImageFileType.Jpeg: return NSBitmapImageFileType.Jpeg;
case ImageFileType.Bmp: return NSBitmapImageFileType.Bmp;
default:
throw new NotSupportedException ();
}
}
public static bool TriggersContextMenu (this NSEvent theEvent)
{
if (theEvent.ButtonNumber == 1 &&
(NSEvent.CurrentPressedMouseButtons & 1 | NSEvent.CurrentPressedMouseButtons & 4) == 0) {
return true;
}
if (theEvent.ButtonNumber == 0 && (theEvent.ModifierFlags & NSEventModifierMask.ControlKeyMask) != 0 &&
(NSEvent.CurrentPressedMouseButtons & 2 | NSEvent.CurrentPressedMouseButtons & 4) == 0) {
return true;
}
return false;
}
public static NSImage ToNSImage (this ImageDescription idesc)
{
if (idesc.IsNull)
return null;
var img = (NSImage)idesc.Backend;
if (img is CustomImage) {
img = ((CustomImage)img).Clone ();
((CustomImage)img).Image = idesc;
} else {
img = (NSImage)img.Copy ();
}
img.Size = new CGSize ((nfloat)idesc.Size.Width, (nfloat)idesc.Size.Height);
return img;
}
public static int ToUnderlineStyle (FontStyle style)
{
return 1;
}
public static int ToMacValue (this FontWeight weight)
{
switch (weight) {
case FontWeight.Ultrathin:
return 0;
case FontWeight.Thin:
return 1;
case FontWeight.Ultralight:
return 2;
case FontWeight.Light:
return 3;
case FontWeight.Book:
return 4;
case FontWeight.Normal:
return 5;
case FontWeight.Medium:
return 6;
case FontWeight.Mediumbold:
return 7;
case FontWeight.Semibold:
return 8;
case FontWeight.Bold:
return 9;
case FontWeight.Ultrabold:
return 10;
case FontWeight.Heavy:
return 11;
case FontWeight.Ultraheavy:
return 12;
case FontWeight.Semiblack:
return 13;
case FontWeight.Black:
return 14;
case FontWeight.Ultrablack:
return 15;
default:
return 15;
}
}
public static NSFont WithWeight (this NSFont font, FontWeight weight)
{
int w = weight.ToMacValue ();
var traits = NSFontManager.SharedFontManager.TraitsOfFont (font);
traits |= weight >= FontWeight.Bold ? NSFontTraitMask.Bold : NSFontTraitMask.Unbold;
traits &= weight >= FontWeight.Bold ? ~NSFontTraitMask.Unbold : ~NSFontTraitMask.Bold;
return NSFontManager.SharedFontManager.FontWithFamily (font.FamilyName, traits, w, font.PointSize);
}
public static NSFont WithSize (this NSFont font, float size)
{
var w = NSFontManager.SharedFontManager.WeightOfFont (font);
var traits = NSFontManager.SharedFontManager.TraitsOfFont (font);
return NSFontManager.SharedFontManager.FontWithFamily (font.FamilyName, traits, w, size);
}
static Selector applyFontTraits = new Selector ("applyFontTraits:range:");
public static NSMutableAttributedString ToAttributedString (this FormattedText ft)
{
NSMutableAttributedString ns = new NSMutableAttributedString (ft.Text);
ns.BeginEditing ();
foreach (var att in ft.Attributes) {
var r = new NSRange (att.StartIndex, att.Count);
if (att is BackgroundTextAttribute) {
var xa = (BackgroundTextAttribute)att;
ns.AddAttribute (NSStringAttributeKey.BackgroundColor, xa.Color.ToNSColor (), r);
}
else if (att is ColorTextAttribute) {
var xa = (ColorTextAttribute)att;
ns.AddAttribute (NSStringAttributeKey.ForegroundColor, xa.Color.ToNSColor (), r);
}
else if (att is UnderlineTextAttribute) {
var xa = (UnderlineTextAttribute)att;
int style = xa.Underline ? 0x01 /*NSUnderlineStyleSingle*/ : 0;
ns.AddAttribute (NSStringAttributeKey.UnderlineStyle, (NSNumber)style, r);
}
else if (att is FontStyleTextAttribute) {
var xa = (FontStyleTextAttribute)att;
if (xa.Style == FontStyle.Italic) {
Messaging.void_objc_msgSend_int_NSRange (ns.Handle, applyFontTraits.Handle, (IntPtr)(long)NSFontTraitMask.Italic, r);
} else if (xa.Style == FontStyle.Oblique) {
ns.AddAttribute (NSStringAttributeKey.Obliqueness, (NSNumber)0.2f, r);
} else {
ns.AddAttribute (NSStringAttributeKey.Obliqueness, (NSNumber)0.0f, r);
Messaging.void_objc_msgSend_int_NSRange (ns.Handle, applyFontTraits.Handle, (IntPtr)(long)NSFontTraitMask.Unitalic, r);
}
}
else if (att is FontWeightTextAttribute) {
var xa = (FontWeightTextAttribute)att;
var trait = xa.Weight >= FontWeight.Bold ? NSFontTraitMask.Bold : NSFontTraitMask.Unbold;
Messaging.void_objc_msgSend_int_NSRange (ns.Handle, applyFontTraits.Handle, (IntPtr)(long) trait, r);
}
else if (att is FontSizeTextAttribute)
{
var xa = (FontSizeTextAttribute)att;
ns.EnumerateAttribute (NSStringAttributeKey.Font, r, NSAttributedStringEnumeration.None, (NSObject value, NSRange range, ref bool stop) => {
var font = value as NSFont;
if (font == null) {
font = NSFont.SystemFontOfSize (xa.Size);
} else {
font = font.WithSize (xa.Size);
}
ns.RemoveAttribute (NSStringAttributeKey.Font, r);
ns.AddAttribute (NSStringAttributeKey.Font, font, r);
});
}
else if (att is LinkTextAttribute) {
var xa = (LinkTextAttribute)att;
if (xa.Target != null)
ns.AddAttribute (NSStringAttributeKey.Link, new NSUrl (xa.Target.ToString ()), r);
ns.AddAttribute (NSStringAttributeKey.ForegroundColor, Toolkit.CurrentEngine.Defaults.FallbackLinkColor.ToNSColor (), r);
ns.AddAttribute (NSStringAttributeKey.UnderlineStyle, NSNumber.FromInt32 ((int)NSUnderlineStyle.Single), r);
}
else if (att is StrikethroughTextAttribute) {
var xa = (StrikethroughTextAttribute)att;
int style = xa.Strikethrough ? 0x01 /*NSUnderlineStyleSingle*/ : 0;
ns.AddAttribute (NSStringAttributeKey.StrikethroughStyle, (NSNumber)style, r);
}
else if (att is FontTextAttribute) {
var xa = (FontTextAttribute)att;
var nf = ((FontData)Toolkit.GetBackend (xa.Font)).Font;
ns.EnumerateAttribute (NSStringAttributeKey.Font, r, NSAttributedStringEnumeration.None, (NSObject value, NSRange range, ref bool stop) => {
var font = value as NSFont;
if (font == null) {
font = nf;
} else {
var w = NSFontManager.SharedFontManager.WeightOfFont (font);
var traits = NSFontManager.SharedFontManager.TraitsOfFont (font);
font = NSFontManager.SharedFontManager.FontWithFamily (nf.FamilyName, traits, w, font.PointSize);
}
ns.RemoveAttribute (NSStringAttributeKey.Font, r);
ns.AddAttribute (NSStringAttributeKey.Font, font, r);
});
}
}
ns.EndEditing ();
return ns;
}
public static NSMutableAttributedString WithAlignment (this NSMutableAttributedString ns, NSTextAlignment alignment)
{
if (ns == null)
return null;
ns.BeginEditing ();
var r = new NSRange (0, ns.Length);
ns.RemoveAttribute (NSStringAttributeKey.ParagraphStyle, r);
var pstyle = NSParagraphStyle.DefaultParagraphStyle.MutableCopy () as NSMutableParagraphStyle;
pstyle.Alignment = alignment;
ns.AddAttribute (NSStringAttributeKey.ParagraphStyle, pstyle, r);
ns.EndEditing ();
return ns;
}
/// <summary>
/// Removes the mnemonics (underscore character) from a string.
/// </summary>
/// <returns>The string with the mnemonics unescaped.</returns>
/// <param name="text">The string.</param>
/// <remarks>
/// Single underscores are removed. Double underscores are replaced with single underscores (unescaped).
/// </remarks>
public static string RemoveMnemonic(this string str)
{
if (str == null)
return null;
var newText = new StringBuilder (str.Length);
for (int i = 0; i < str.Length; i++) {
if (str [i] != '_')
newText.Append (str [i]);
else if (i < str.Length && str [i + 1] == '_') {
newText.Append ('_');
i++;
}
}
return newText.ToString ();
}
public static CheckBoxState ToXwtState (this NSCellStateValue state)
{
switch (state) {
case NSCellStateValue.Mixed:
return CheckBoxState.Mixed;
case NSCellStateValue.On:
return CheckBoxState.On;
case NSCellStateValue.Off:
return CheckBoxState.Off;
default:
throw new ArgumentOutOfRangeException ();
}
}
public static NSCellStateValue ToMacState (this CheckBoxState state)
{
switch (state) {
case CheckBoxState.Mixed:
return NSCellStateValue.Mixed;
case CheckBoxState.On:
return NSCellStateValue.On;
case CheckBoxState.Off:
return NSCellStateValue.Off;
default:
throw new ArgumentOutOfRangeException ();
}
}
public static ModifierKeys ToXwtValue (this NSEventModifierMask e)
{
ModifierKeys m = ModifierKeys.None;
if (e.HasFlag (NSEventModifierMask.ControlKeyMask))
m |= ModifierKeys.Control;
if (e.HasFlag (NSEventModifierMask.AlternateKeyMask))
m |= ModifierKeys.Alt;
if (e.HasFlag (NSEventModifierMask.CommandKeyMask))
m |= ModifierKeys.Command;
if (e.HasFlag (NSEventModifierMask.ShiftKeyMask))
m |= ModifierKeys.Shift;
return m;
}
public static NSTableViewGridStyle ToMacValue (this GridLines value)
{
switch (value)
{
case GridLines.Both:
return (NSTableViewGridStyle.SolidHorizontalLine | NSTableViewGridStyle.SolidVerticalLine);
case GridLines.Horizontal:
return NSTableViewGridStyle.SolidHorizontalLine;
case GridLines.Vertical:
return NSTableViewGridStyle.SolidVerticalLine;
case GridLines.None:
return NSTableViewGridStyle.None;
}
throw new InvalidOperationException("Invalid GridLines value: " + value);
}
public static GridLines ToXwtValue (this NSTableViewGridStyle value)
{
if (value.HasFlag (NSTableViewGridStyle.SolidHorizontalLine)) {
if (value.HasFlag (NSTableViewGridStyle.SolidVerticalLine))
return GridLines.Both;
else
return GridLines.Horizontal;
}
if (value.HasFlag (NSTableViewGridStyle.SolidVerticalLine))
return GridLines.Vertical;
return GridLines.None;
}
public static NSDatePickerElementFlags ToMacValue (this DatePickerStyle style)
{
switch (style) {
case DatePickerStyle.Date:
return NSDatePickerElementFlags.YearMonthDateDay;
case DatePickerStyle.DateTime:
return NSDatePickerElementFlags.YearMonthDateDay | NSDatePickerElementFlags.HourMinuteSecond;
case DatePickerStyle.Time:
return NSDatePickerElementFlags.HourMinuteSecond;
}
return NSDatePickerElementFlags.YearMonthDate;
}
public static DatePickerStyle ToXwtValue (this NSDatePickerElementFlags flags)
{
switch (flags) {
case NSDatePickerElementFlags.HourMinuteSecond:
return DatePickerStyle.Time;
case NSDatePickerElementFlags.YearMonthDate:
case NSDatePickerElementFlags.YearMonthDateDay:
return DatePickerStyle.Date;
default:
return DatePickerStyle.DateTime;
}
}
static readonly Selector selConvertSizeToBacking = new Selector ("convertSizeToBacking:");
public static void DrawWithColorTransform (this NSView view, Color? color, Action drawDelegate)
{
if (color.HasValue) {
var size = view.Frame.Size;
if (size.Width <= 0 || size.Height <= 0)
return;
// render view to image
var image = new NSImage(size);
image.LockFocusFlipped(!view.IsFlipped);
drawDelegate ();
image.UnlockFocus();
// create Core image for transformation
var ciImage = CIImage.FromCGImage(image.CGImage);
CGSize displaySize;
#pragma warning disable iOSAndMacApiUsageIssue
if (view.RespondsToSelector (selConvertSizeToBacking))
displaySize = view.ConvertSizeToBacking (size);
else
displaySize = view.ConvertSizeToBase (size);
#pragma warning restore iOSAndMacApiUsageIssue
// apply color matrix
var transformColor = new CIColorMatrix();
transformColor.SetDefaults();
transformColor.Image = ciImage;
transformColor.RVector = new CIVector(0, (float)color.Value.Red, 0);
transformColor.GVector = new CIVector((float)color.Value.Green, 0, 0);
transformColor.BVector = new CIVector(0, 0, (float)color.Value.Blue);
using (var key = new NSString("outputImage"))
ciImage = (CIImage)transformColor.ValueForKey(key);
var ciCtx = CIContext.FromContext(NSGraphicsContext.CurrentContext.GraphicsPort, null);
ciCtx.DrawImage (ciImage, new CGRect (CGPoint.Empty, size), new CGRect (CGPoint.Empty, displaySize));
} else
drawDelegate();
}
public static CGPoint ConvertPointFromEvent(this NSView view, NSEvent theEvent)
{
var point = theEvent.LocationInWindow;
if (view.Window != null && theEvent.WindowNumber != view.Window.WindowNumber)
{
point = theEvent.Window.ConvertBaseToScreen(point);
point = view.Window.ConvertScreenToBase(point);
}
return view.ConvertPointFromView(point, null);
}
public static PointerButton GetPointerButton (this NSEvent theEvent)
{
switch (theEvent.ButtonNumber) {
case 0: return PointerButton.Left;
case 1: return PointerButton.Right;
case 2: return PointerButton.Middle;
case 3: return PointerButton.ExtendedButton1;
case 4: return PointerButton.ExtendedButton2;
}
return (PointerButton)0;
}
public static Accessibility.Role GetXwtRole (INSAccessibility widget)
{
var r = widget.AccessibilityRole;
var sr = widget.AccessibilitySubrole;
if (r == NSAccessibilityRoles.ButtonRole) {
if (sr == NSAccessibilitySubroles.CloseButtonSubrole)
return Accessibility.Role.ButtonClose;
if (sr == NSAccessibilitySubroles.MinimizeButtonSubrole)
return Accessibility.Role.ButtonMinimize;
if (sr == NSAccessibilitySubroles.ZoomButtonSubrole)
return Accessibility.Role.ButtonMaximize;
if (sr == NSAccessibilitySubroles.FullScreenButtonSubrole)
return Accessibility.Role.ButtonFullscreen;
return Accessibility.Role.Button;
}
if (r == NSAccessibilityRoles.CellRole)
return Accessibility.Role.Cell;
if (r == NSAccessibilityRoles.CheckBoxRole)
return Accessibility.Role.CheckBox;
if (r == NSAccessibilityRoles.ColorWellRole)
return Accessibility.Role.ColorChooser;
if (r == NSAccessibilityRoles.ColumnRole)
return Accessibility.Role.Column;
if (r == NSAccessibilityRoles.ComboBoxRole)
return Accessibility.Role.ComboBox;
if (r == NSAccessibilityRoles.ComboBoxRole)
return Accessibility.Role.ComboBox;
if (r == NSAccessibilityRoles.DisclosureTriangleRole)
return Accessibility.Role.Disclosure;
if (r == NSAccessibilityRoles.GroupRole)
return Accessibility.Role.Group;
if (r == NSAccessibilityRoles.ImageRole)
return Accessibility.Role.Image;
if (r == NSAccessibilityRoles.LevelIndicatorRole)
return Accessibility.Role.LevelIndicator;
if (r == NSAccessibilityRoles.LinkRole)
return Accessibility.Role.Link;
if (r == NSAccessibilityRoles.ListRole)
return Accessibility.Role.List;
if (r == "NSAccessibilityMenuBarRole")
return Accessibility.Role.MenuBar;
if (r == NSAccessibilityRoles.MenuBarItemRole)
return Accessibility.Role.MenuBarItem;
if (r == NSAccessibilityRoles.MenuItemRole)
return Accessibility.Role.MenuItem;
if (r == NSAccessibilityRoles.MenuRole)
return Accessibility.Role.Menu;
if (r == NSAccessibilityRoles.OutlineRole)
return Accessibility.Role.Tree;
if (r == NSAccessibilityRoles.PopUpButtonRole)
return Accessibility.Role.MenuButton;
if (r == NSAccessibilityRoles.PopoverRole)
return Accessibility.Role.Popup;
if (r == NSAccessibilityRoles.ProgressIndicatorRole)
return Accessibility.Role.ProgressBar;
if (r == NSAccessibilityRoles.RadioButtonRole)
return Accessibility.Role.RadioButton;
if (r == NSAccessibilityRoles.RadioGroupRole)
return Accessibility.Role.RadioGroup;
if (r == NSAccessibilityRoles.RowRole)
return Accessibility.Role.Row;
if (r == NSAccessibilityRoles.ScrollAreaRole)
return Accessibility.Role.ScrollView;
if (r == NSAccessibilityRoles.ScrollBarRole)
return Accessibility.Role.ScrollBar;
if (r == NSAccessibilityRoles.SliderRole)
return Accessibility.Role.Slider;
if (r == NSAccessibilityRoles.SplitGroupRole)
return Accessibility.Role.Paned;
if (r == NSAccessibilityRoles.SplitterRole)
return Accessibility.Role.PanedSplitter;
if (r == NSAccessibilityRoles.StaticTextRole)
return Accessibility.Role.Label;
if (r == NSAccessibilityRoles.TabGroupRole)
return Accessibility.Role.Notebook;
if (r == NSAccessibilityRoles.TableRole)
return Accessibility.Role.Table;
if (r == NSAccessibilityRoles.TextAreaRole)
return Accessibility.Role.TextEntry;
if (r == NSAccessibilityRoles.TextFieldRole) {
if (sr == NSAccessibilitySubroles.SearchFieldSubrole)
return Accessibility.Role.TextEntrySearch;
if (sr == NSAccessibilitySubroles.SecureTextFieldSubrole)
return Accessibility.Role.TextEntryPassword;
return Accessibility.Role.TextEntry;
}
if (r == NSAccessibilityRoles.ToolbarRole)
return Accessibility.Role.ToolBar;
if (r == NSAccessibilityRoles.ValueIndicatorRole)
return Accessibility.Role.SpinButton;
//if (r == NSAccessibilityRoles.WindowRole)
// return Accessibility.Role.Window;
return Accessibility.Role.Custom;
// TODO:
//NSAccessibilityRoles.ApplicationRole;
//NSAccessibilityRoles.BrowserRole;
//NSAccessibilityRoles.BusyIndicatorRole;
//NSAccessibilityRoles.DrawerRole;
//NSAccessibilityRoles.GridRole;
//NSAccessibilityRoles.GrowAreaRole;
//NSAccessibilityRoles.HandleRole;
//NSAccessibilityRoles.HelpTagRole;
//NSAccessibilityRoles.IncrementorRole;
//NSAccessibilityRoles.LayoutAreaRole;
//NSAccessibilityRoles.LayoutItemRole;
//NSAccessibilityRoles.IncrementorRole
//NSAccessibilityRoles.MatteRole;
//NSAccessibilityRoles.MenuButtonRole;
//NSAccessibilityRoles.RelevanceIndicatorRole;
//NSAccessibilityRoles.RulerMarkerRole;
//NSAccessibilityRoles.RulerRole;
//NSAccessibilityRoles.SheetRole;
//NSAccessibilityRoles.UnknownRole;
}
public static NSString GetMacRole (this Accessibility.Role role)
{
switch (role) {
case Accessibility.Role.Button:
return NSAccessibilityRoles.ButtonRole;
//case Accessibility.Role.Calendar:
// break;
case Accessibility.Role.Cell:
return NSAccessibilityRoles.CellRole;
case Accessibility.Role.CheckBox:
return NSAccessibilityRoles.CheckBoxRole;
case Accessibility.Role.ColorChooser:
return NSAccessibilityRoles.ColorWellRole;
case Accessibility.Role.Column:
return NSAccessibilityRoles.ColumnRole;
case Accessibility.Role.ComboBox:
return NSAccessibilityRoles.ComboBoxRole;
//case Accessibility.Role.Custom:
// break;
//case Accessibility.Role.Dialog:
// return NSAccessibilityRoles.WindowRole;
case Accessibility.Role.Disclosure:
return NSAccessibilityRoles.DisclosureTriangleRole;
//case Accessibility.Role.Grid:
// break;
case Accessibility.Role.Group:
return NSAccessibilityRoles.GroupRole;
case Accessibility.Role.Image:
return NSAccessibilityRoles.ImageRole;
case Accessibility.Role.Label:
return NSAccessibilityRoles.StaticTextRole;
case Accessibility.Role.LevelIndicator:
return NSAccessibilityRoles.LevelIndicatorRole;
case Accessibility.Role.Link:
return NSAccessibilityRoles.LinkRole;
case Accessibility.Role.List:
return NSAccessibilityRoles.ListRole;
case Accessibility.Role.Menu:
return NSAccessibilityRoles.MenuRole;
case Accessibility.Role.MenuBar:
return new NSString ("NSAccessibilityMenuBarRole");
case Accessibility.Role.MenuBarItem:
return NSAccessibilityRoles.MenuBarItemRole;
case Accessibility.Role.MenuButton:
return NSAccessibilityRoles.PopUpButtonRole;
case Accessibility.Role.MenuItem:
case Accessibility.Role.MenuItemCheckBox:
case Accessibility.Role.MenuItemRadio:
return NSAccessibilityRoles.MenuItemRole;
case Accessibility.Role.Notebook:
return NSAccessibilityRoles.TabGroupRole;
//case Accessibility.Role.NotebookTab:
// break;
case Accessibility.Role.Popup:
return NSAccessibilityRoles.PopoverRole;
case Accessibility.Role.ProgressBar:
return NSAccessibilityRoles.ProgressIndicatorRole;
case Accessibility.Role.RadioButton:
return NSAccessibilityRoles.RadioButtonRole;
case Accessibility.Role.RadioGroup:
return NSAccessibilityRoles.RadioGroupRole;
case Accessibility.Role.Row:
return NSAccessibilityRoles.RowRole;
case Accessibility.Role.ScrollBar:
return NSAccessibilityRoles.ScrollBarRole;
case Accessibility.Role.ScrollView:
return NSAccessibilityRoles.ScrollAreaRole;
//case Accessibility.Role.Separator:
// break;
case Accessibility.Role.Slider:
return NSAccessibilityRoles.SliderRole;
case Accessibility.Role.SpinButton:
return NSAccessibilityRoles.ValueIndicatorRole;
case Accessibility.Role.Paned:
return NSAccessibilityRoles.SplitGroupRole;
case Accessibility.Role.PanedSplitter:
return NSAccessibilityRoles.SplitterRole;
case Accessibility.Role.Table:
return NSAccessibilityRoles.TableRole;
case Accessibility.Role.TextArea:
return NSAccessibilityRoles.TextAreaRole;
case Accessibility.Role.TextEntry:
return NSAccessibilityRoles.TextFieldRole;
case Accessibility.Role.ToggleButton:
return NSAccessibilityRoles.ButtonRole;
case Accessibility.Role.ToolBar:
return NSAccessibilityRoles.ToolbarRole;
//case Accessibility.Role.ToolTip:
// break;
case Accessibility.Role.Tree:
return NSAccessibilityRoles.OutlineRole;
//case Accessibility.Role.Window:
// return NSAccessibilityRoles.WindowRole;
}
return NSAccessibilityRoles.UnknownRole;
}
public static NSString GetMacSubrole (this Accessibility.Role role)
{
switch (role) {
case Accessibility.Role.ButtonClose:
return NSAccessibilitySubroles.CloseButtonSubrole;
case Accessibility.Role.ButtonMaximize:
return NSAccessibilitySubroles.ZoomButtonSubrole;
case Accessibility.Role.ButtonMinimize:
return NSAccessibilitySubroles.MinimizeButtonSubrole;
case Accessibility.Role.ButtonFullscreen:
return NSAccessibilitySubroles.FullScreenButtonSubrole;
case Accessibility.Role.TextEntrySearch:
return NSAccessibilitySubroles.SearchFieldSubrole;
case Accessibility.Role.TextEntryPassword:
return NSAccessibilitySubroles.SecureTextFieldSubrole;
}
return null;
}
}
public interface ICopiableObject
{
void CopyFrom (object other);
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.GenerateType;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.GenerateType;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.UnitTests;
using Microsoft.CodeAnalysis.UnitTests.Diagnostics;
using Microsoft.VisualStudio.Text.Differencing;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics
{
public abstract class AbstractUserDiagnosticTest : AbstractCodeActionOrUserDiagnosticTest
{
internal abstract Task<IEnumerable<Tuple<Diagnostic, CodeFixCollection>>> GetDiagnosticAndFixesAsync(TestWorkspace workspace, string fixAllActionEquivalenceKey);
internal abstract Task<IEnumerable<Diagnostic>> GetDiagnosticsAsync(TestWorkspace workspace);
protected override async Task<IList<CodeAction>> GetCodeActionsWorkerAsync(TestWorkspace workspace, string fixAllActionEquivalenceKey)
{
var diagnostics = await GetDiagnosticAndFixAsync(workspace, fixAllActionEquivalenceKey);
return diagnostics?.Item2?.Fixes.Select(f => f.Action).ToList();
}
internal async Task<Tuple<Diagnostic, CodeFixCollection>> GetDiagnosticAndFixAsync(TestWorkspace workspace, string fixAllActionEquivalenceKey = null)
{
return (await GetDiagnosticAndFixesAsync(workspace, fixAllActionEquivalenceKey)).FirstOrDefault();
}
protected Document GetDocumentAndSelectSpan(TestWorkspace workspace, out TextSpan span)
{
var hostDocument = workspace.Documents.Single(d => d.SelectedSpans.Any());
span = hostDocument.SelectedSpans.Single();
return workspace.CurrentSolution.GetDocument(hostDocument.Id);
}
protected bool TryGetDocumentAndSelectSpan(TestWorkspace workspace, out Document document, out TextSpan span)
{
var hostDocument = workspace.Documents.FirstOrDefault(d => d.SelectedSpans.Any());
if (hostDocument == null)
{
document = null;
span = default(TextSpan);
return false;
}
span = hostDocument.SelectedSpans.Single();
document = workspace.CurrentSolution.GetDocument(hostDocument.Id);
return true;
}
protected Document GetDocumentAndAnnotatedSpan(TestWorkspace workspace, out string annotation, out TextSpan span)
{
var hostDocument = workspace.Documents.Single(d => d.AnnotatedSpans.Any());
var annotatedSpan = hostDocument.AnnotatedSpans.Single();
annotation = annotatedSpan.Key;
span = annotatedSpan.Value.Single();
return workspace.CurrentSolution.GetDocument(hostDocument.Id);
}
protected FixAllScope? GetFixAllScope(string annotation)
{
if (annotation == null)
{
return null;
}
switch (annotation)
{
case "FixAllInDocument":
return FixAllScope.Document;
case "FixAllInProject":
return FixAllScope.Project;
case "FixAllInSolution":
return FixAllScope.Solution;
case "FixAllInSelection":
return FixAllScope.Custom;
}
throw new InvalidProgramException("Incorrect FixAll annotation in test");
}
internal async Task<IEnumerable<Tuple<Diagnostic, CodeFixCollection>>> GetDiagnosticAndFixesAsync(
IEnumerable<Diagnostic> diagnostics,
DiagnosticAnalyzer provider,
CodeFixProvider fixer,
TestDiagnosticAnalyzerDriver testDriver,
Document document,
TextSpan span,
string annotation,
string fixAllActionId)
{
if (diagnostics.IsEmpty())
{
return SpecializedCollections.EmptyEnumerable<Tuple<Diagnostic, CodeFixCollection>>();
}
FixAllScope? scope = GetFixAllScope(annotation);
return await GetDiagnosticAndFixesAsync(diagnostics, provider, fixer, testDriver, document, span, scope, fixAllActionId);
}
private async Task<IEnumerable<Tuple<Diagnostic, CodeFixCollection>>> GetDiagnosticAndFixesAsync(
IEnumerable<Diagnostic> diagnostics,
DiagnosticAnalyzer provider,
CodeFixProvider fixer,
TestDiagnosticAnalyzerDriver testDriver,
Document document,
TextSpan span,
FixAllScope? scope,
string fixAllActionId)
{
Assert.NotEmpty(diagnostics);
var result = new List<Tuple<Diagnostic, CodeFixCollection>>();
if (scope == null)
{
// Simple code fix.
foreach (var diagnostic in diagnostics)
{
var fixes = new List<CodeFix>();
var context = new CodeFixContext(document, diagnostic, (a, d) => fixes.Add(new CodeFix(document.Project, a, d)), CancellationToken.None);
await fixer.RegisterCodeFixesAsync(context);
if (fixes.Any())
{
var codeFix = new CodeFixCollection(fixer, diagnostic.Location.SourceSpan, fixes);
result.Add(Tuple.Create(diagnostic, codeFix));
}
}
}
else
{
// Fix all fix.
var fixAllProvider = fixer.GetFixAllProvider();
Assert.NotNull(fixAllProvider);
var fixAllContext = GetFixAllContext(diagnostics, provider, fixer, testDriver, document, scope.Value, fixAllActionId);
var fixAllFix = await fixAllProvider.GetFixAsync(fixAllContext);
if (fixAllFix != null)
{
// Same fix applies to each diagnostic in scope.
foreach (var diagnostic in diagnostics)
{
var diagnosticSpan = diagnostic.Location.IsInSource ? diagnostic.Location.SourceSpan : default(TextSpan);
var codeFix = new CodeFixCollection(fixAllProvider, diagnosticSpan, ImmutableArray.Create(new CodeFix(document.Project, fixAllFix, diagnostic)));
result.Add(Tuple.Create(diagnostic, codeFix));
}
}
}
return result;
}
private static FixAllContext GetFixAllContext(
IEnumerable<Diagnostic> diagnostics,
DiagnosticAnalyzer provider,
CodeFixProvider fixer,
TestDiagnosticAnalyzerDriver testDriver,
Document document,
FixAllScope scope,
string fixAllActionId)
{
Assert.NotEmpty(diagnostics);
if (scope == FixAllScope.Custom)
{
// Bulk fixing diagnostics in selected scope.
var diagnosticsToFix = ImmutableDictionary.CreateRange(SpecializedCollections.SingletonEnumerable(KeyValuePair.Create(document, diagnostics.ToImmutableArray())));
return FixMultipleContext.Create(diagnosticsToFix, fixer, fixAllActionId, CancellationToken.None);
}
var diagnostic = diagnostics.First();
Func<Document, ImmutableHashSet<string>, CancellationToken, Task<IEnumerable<Diagnostic>>> getDocumentDiagnosticsAsync =
async (d, diagIds, c) =>
{
var root = await d.GetSyntaxRootAsync();
var diags = await testDriver.GetDocumentDiagnosticsAsync(provider, d, root.FullSpan);
diags = diags.Where(diag => diagIds.Contains(diag.Id));
return diags;
};
Func<Project, bool, ImmutableHashSet<string>, CancellationToken, Task<IEnumerable<Diagnostic>>> getProjectDiagnosticsAsync =
async (p, includeAllDocumentDiagnostics, diagIds, c) =>
{
var diags = includeAllDocumentDiagnostics
? await testDriver.GetAllDiagnosticsAsync(provider, p)
: await testDriver.GetProjectDiagnosticsAsync(provider, p);
diags = diags.Where(diag => diagIds.Contains(diag.Id));
return diags;
};
var diagnosticIds = ImmutableHashSet.Create(diagnostic.Id);
var fixAllDiagnosticProvider = new FixAllCodeActionContext.FixAllDiagnosticProvider(diagnosticIds, getDocumentDiagnosticsAsync, getProjectDiagnosticsAsync);
return diagnostic.Location.IsInSource
? new FixAllContext(document, fixer, scope, fixAllActionId, diagnosticIds, fixAllDiagnosticProvider, CancellationToken.None)
: new FixAllContext(document.Project, fixer, scope, fixAllActionId, diagnosticIds, fixAllDiagnosticProvider, CancellationToken.None);
}
protected async Task TestEquivalenceKeyAsync(string initialMarkup, string equivalenceKey)
{
using (var workspace = await CreateWorkspaceFromFileAsync(initialMarkup, parseOptions: null, compilationOptions: null))
{
var diagnosticAndFix = await GetDiagnosticAndFixAsync(workspace);
Assert.Equal(equivalenceKey, diagnosticAndFix.Item2.Fixes.ElementAt(index: 0).Action.EquivalenceKey);
}
}
protected async Task TestActionCountInAllFixesAsync(
string initialMarkup,
int count,
ParseOptions parseOptions = null, CompilationOptions compilationOptions = null)
{
using (var workspace = await CreateWorkspaceFromFileAsync(initialMarkup, parseOptions, compilationOptions))
{
var diagnosticAndFix = await GetDiagnosticAndFixesAsync(workspace, null);
var diagnosticCount = diagnosticAndFix.Select(x => x.Item2.Fixes.Count()).Sum();
Assert.Equal(count, diagnosticCount);
}
}
protected async Task TestSpansAsync(
string initialMarkup, string expectedMarkup,
int index = 0,
ParseOptions parseOptions = null, CompilationOptions compilationOptions = null,
string diagnosticId = null, string fixAllActionEquivalenceId = null)
{
IList<TextSpan> spansList;
string unused;
MarkupTestFile.GetSpans(expectedMarkup, out unused, out spansList);
var expectedTextSpans = spansList.ToSet();
using (var workspace = await CreateWorkspaceFromFileAsync(initialMarkup, parseOptions, compilationOptions))
{
ISet<TextSpan> actualTextSpans;
if (diagnosticId == null)
{
var diagnosticsAndFixes = await GetDiagnosticAndFixesAsync(workspace, fixAllActionEquivalenceId);
var diagnostics = diagnosticsAndFixes.Select(t => t.Item1);
actualTextSpans = diagnostics.Select(d => d.Location.SourceSpan).ToSet();
}
else
{
var diagnostics = await GetDiagnosticsAsync(workspace);
actualTextSpans = diagnostics.Where(d => d.Id == diagnosticId).Select(d => d.Location.SourceSpan).ToSet();
}
Assert.True(expectedTextSpans.SetEquals(actualTextSpans));
}
}
protected async Task TestAddDocument(
string initialMarkup, string expectedMarkup,
IList<string> expectedContainers,
string expectedDocumentName,
int index = 0,
bool compareTokens = true, bool isLine = true)
{
await TestAddDocument(initialMarkup, expectedMarkup, index, expectedContainers, expectedDocumentName, null, null, compareTokens, isLine);
await TestAddDocument(initialMarkup, expectedMarkup, index, expectedContainers, expectedDocumentName, GetScriptOptions(), null, compareTokens, isLine);
}
private async Task TestAddDocument(
string initialMarkup, string expectedMarkup,
int index,
IList<string> expectedContainers,
string expectedDocumentName,
ParseOptions parseOptions, CompilationOptions compilationOptions,
bool compareTokens, bool isLine)
{
using (var workspace = isLine
? await CreateWorkspaceFromFileAsync(initialMarkup, parseOptions, compilationOptions)
: await TestWorkspaceFactory.CreateWorkspaceAsync(initialMarkup))
{
var codeActions = await GetCodeActionsAsync(workspace, fixAllActionEquivalenceKey: null);
await TestAddDocument(workspace, expectedMarkup, index, expectedContainers, expectedDocumentName,
codeActions, compareTokens);
}
}
private async Task TestAddDocument(
TestWorkspace workspace,
string expectedMarkup,
int index,
IList<string> expectedFolders,
string expectedDocumentName,
IList<CodeAction> actions,
bool compareTokens)
{
var operations = await VerifyInputsAndGetOperationsAsync(index, actions);
await TestAddDocument(
workspace,
expectedMarkup,
operations,
hasProjectChange: false,
modifiedProjectId: null,
expectedFolders: expectedFolders,
expectedDocumentName: expectedDocumentName,
compareTokens: compareTokens);
}
private async Task<Tuple<Solution, Solution>> TestAddDocument(
TestWorkspace workspace,
string expected,
IEnumerable<CodeActionOperation> operations,
bool hasProjectChange,
ProjectId modifiedProjectId,
IList<string> expectedFolders,
string expectedDocumentName,
bool compareTokens)
{
var appliedChanges = ApplyOperationsAndGetSolution(workspace, operations);
var oldSolution = appliedChanges.Item1;
var newSolution = appliedChanges.Item2;
Document addedDocument = null;
if (!hasProjectChange)
{
addedDocument = SolutionUtilities.GetSingleAddedDocument(oldSolution, newSolution);
}
else
{
Assert.NotNull(modifiedProjectId);
addedDocument = newSolution.GetProject(modifiedProjectId).Documents.SingleOrDefault(doc => doc.Name == expectedDocumentName);
}
Assert.NotNull(addedDocument);
AssertEx.Equal(expectedFolders, addedDocument.Folders);
Assert.Equal(expectedDocumentName, addedDocument.Name);
if (compareTokens)
{
TokenUtilities.AssertTokensEqual(
expected, (await addedDocument.GetTextAsync()).ToString(), GetLanguage());
}
else
{
Assert.Equal(expected, (await addedDocument.GetTextAsync()).ToString());
}
var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>();
if (!hasProjectChange)
{
// If there is just one document change then we expect the preview to be a WpfTextView
var content = (await editHandler.GetPreviews(workspace, operations, CancellationToken.None).GetPreviewsAsync())[0];
var diffView = content as IWpfDifferenceViewer;
Assert.NotNull(diffView);
diffView.Close();
}
else
{
// If there are more changes than just the document we need to browse all the changes and get the document change
var contents = editHandler.GetPreviews(workspace, operations, CancellationToken.None);
bool hasPreview = false;
var previews = await contents.GetPreviewsAsync();
if (previews != null)
{
foreach (var preview in previews)
{
if (preview != null)
{
var diffView = preview as IWpfDifferenceViewer;
if (diffView != null)
{
hasPreview = true;
diffView.Close();
break;
}
}
}
}
Assert.True(hasPreview);
}
return Tuple.Create(oldSolution, newSolution);
}
internal async Task TestWithMockedGenerateTypeDialog(
string initial,
string languageName,
string typeName,
string expected = null,
bool isLine = true,
bool isMissing = false,
Accessibility accessibility = Accessibility.NotApplicable,
TypeKind typeKind = TypeKind.Class,
string projectName = null,
bool isNewFile = false,
string existingFilename = null,
IList<string> newFileFolderContainers = null,
string fullFilePath = null,
string newFileName = null,
string assertClassName = null,
bool checkIfUsingsIncluded = false,
bool checkIfUsingsNotIncluded = false,
string expectedTextWithUsings = null,
string defaultNamespace = "",
bool areFoldersValidIdentifiers = true,
GenerateTypeDialogOptions assertGenerateTypeDialogOptions = null,
IList<TypeKindOptions> assertTypeKindPresent = null,
IList<TypeKindOptions> assertTypeKindAbsent = null,
bool isCancelled = false)
{
using (var testState = await GenerateTypeTestState.CreateAsync(initial, isLine, projectName, typeName, existingFilename, languageName))
{
// Initialize the viewModel values
testState.TestGenerateTypeOptionsService.SetGenerateTypeOptions(
accessibility: accessibility,
typeKind: typeKind,
typeName: testState.TypeName,
project: testState.ProjectToBeModified,
isNewFile: isNewFile,
newFileName: newFileName,
folders: newFileFolderContainers,
fullFilePath: fullFilePath,
existingDocument: testState.ExistingDocument,
areFoldersValidIdentifiers: areFoldersValidIdentifiers,
isCancelled: isCancelled);
testState.TestProjectManagementService.SetDefaultNamespace(
defaultNamespace: defaultNamespace);
var diagnosticsAndFixes = await GetDiagnosticAndFixesAsync(testState.Workspace, null);
var generateTypeDiagFixes = diagnosticsAndFixes.SingleOrDefault(df => GenerateTypeTestState.FixIds.Contains(df.Item1.Id));
if (isMissing)
{
Assert.Null(generateTypeDiagFixes);
return;
}
var fixes = generateTypeDiagFixes.Item2.Fixes;
Assert.NotNull(fixes);
var fixActions = MassageActions(fixes.Select(f => f.Action).ToList());
Assert.NotNull(fixActions);
// Since the dialog option is always fed as the last CodeAction
var index = fixActions.Count() - 1;
var action = fixActions.ElementAt(index);
Assert.Equal(action.Title, FeaturesResources.GenerateNewType);
var operations = await action.GetOperationsAsync(CancellationToken.None);
Tuple<Solution, Solution> oldSolutionAndNewSolution = null;
if (!isNewFile)
{
oldSolutionAndNewSolution = await TestOperationsAsync(
testState.Workspace, expected, operations,
conflictSpans: null, renameSpans: null, warningSpans: null,
compareTokens: false, expectedChangedDocumentId: testState.ExistingDocument.Id);
}
else
{
oldSolutionAndNewSolution = await TestAddDocument(
testState.Workspace,
expected,
operations,
projectName != null,
testState.ProjectToBeModified.Id,
newFileFolderContainers,
newFileName,
compareTokens: false);
}
if (checkIfUsingsIncluded)
{
Assert.NotNull(expectedTextWithUsings);
await TestOperationsAsync(testState.Workspace, expectedTextWithUsings, operations,
conflictSpans: null, renameSpans: null, warningSpans: null, compareTokens: false,
expectedChangedDocumentId: testState.InvocationDocument.Id);
}
if (checkIfUsingsNotIncluded)
{
var oldSolution = oldSolutionAndNewSolution.Item1;
var newSolution = oldSolutionAndNewSolution.Item2;
var changedDocumentIds = SolutionUtilities.GetChangedDocuments(oldSolution, newSolution);
Assert.False(changedDocumentIds.Contains(testState.InvocationDocument.Id));
}
// Added into a different project than the triggering project
if (projectName != null)
{
var appliedChanges = ApplyOperationsAndGetSolution(testState.Workspace, operations);
var newSolution = appliedChanges.Item2;
var triggeredProject = newSolution.GetProject(testState.TriggeredProject.Id);
// Make sure the Project reference is present
Assert.True(triggeredProject.ProjectReferences.Any(pr => pr.ProjectId == testState.ProjectToBeModified.Id));
}
// Assert Option Calculation
if (assertClassName != null)
{
Assert.True(assertClassName == testState.TestGenerateTypeOptionsService.ClassName);
}
if (assertGenerateTypeDialogOptions != null || assertTypeKindPresent != null || assertTypeKindAbsent != null)
{
var generateTypeDialogOptions = testState.TestGenerateTypeOptionsService.GenerateTypeDialogOptions;
if (assertGenerateTypeDialogOptions != null)
{
Assert.True(assertGenerateTypeDialogOptions.IsPublicOnlyAccessibility == generateTypeDialogOptions.IsPublicOnlyAccessibility);
Assert.True(assertGenerateTypeDialogOptions.TypeKindOptions == generateTypeDialogOptions.TypeKindOptions);
Assert.True(assertGenerateTypeDialogOptions.IsAttribute == generateTypeDialogOptions.IsAttribute);
}
if (assertTypeKindPresent != null)
{
foreach (var typeKindPresentEach in assertTypeKindPresent)
{
Assert.True((typeKindPresentEach & generateTypeDialogOptions.TypeKindOptions) != 0);
}
}
if (assertTypeKindAbsent != null)
{
foreach (var typeKindPresentEach in assertTypeKindAbsent)
{
Assert.True((typeKindPresentEach & generateTypeDialogOptions.TypeKindOptions) == 0);
}
}
}
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.CortexM0OnMBED.Drivers
{
using System;
using System.Runtime.CompilerServices;
using RT = Microsoft.Zelig.Runtime;
using LLOS = Zelig.LlilumOSAbstraction;
using ChipsetModel = Microsoft.DeviceModels.Chipset.CortexM;
/// <summary>
/// This class implements the internal system timer. All times are in ticks (time agnostic)
/// however in practice, and due to limitations of mbed 1 tick is equal to 1 uS (micro second)
/// </summary>
public abstract class SystemTimer
{
public delegate void Callback(Timer timer, ulong currentTime);
public class Timer
{
//
// State
//
private readonly Callback m_callback;
private readonly RT.KernelNode<Timer> m_node;
private readonly SystemTimer m_owner;
private ulong m_timeout;
//
// Constructor Methods
//
internal Timer(SystemTimer owner, Callback callback)
{
m_owner = owner;
m_node = new RT.KernelNode<Timer>(this);
m_callback = callback;
}
//
// Helper Methods
//
public void Cancel()
{
m_owner.Deregister(this);
}
/// <summary>
/// Call to the Timer handler
/// </summary>
/// <param name="currentTime">Time in ticks</param>
internal void Invoke(ulong currentTime)
{
m_callback(this, currentTime);
}
//
// Access Methods
//
internal RT.KernelNode<Timer> Node
{
get
{
return m_node;
}
}
/// <summary>
/// Set/get the timeout in absolute time
/// </summary>
public ulong Timeout
{
get
{
return m_timeout;
}
set
{
m_timeout = value;
m_owner.Register(this);
}
}
/// <summary>
/// Set/get the timeout in relation to current time
/// </summary>
public ulong RelativeTimeout
{
get
{
return m_timeout - m_owner.CurrentTime;
}
set
{
m_timeout = value + m_owner.CurrentTime;
m_owner.Register(this);
}
}
}
//--//
//
// System Timer Implementation
//
public const uint c_MaxCounterValue = uint.MaxValue;
public const uint c_HalfCycle = c_MaxCounterValue >> 1;
public const uint c_QuarterCycle = c_MaxCounterValue >> 2;
public const uint c_ThreeQuarterCycle = c_HalfCycle + c_QuarterCycle;
//--//
private RT.KernelList<Timer> m_timers;
private ulong m_accumulator;
private uint m_lastAccumulatorUpdate;
// This is only used as a placeholder to pass into timer_insert_event
private unsafe LLOS.HAL.TimerContext* m_timerEvent;
//--//
//private static Timer s_guard;
public void Initialize()
{
m_timers = new RT.KernelList<Timer>();
m_accumulator = 0;
m_lastAccumulatorUpdate = this.Counter;
// Allocate our one, and only, timer event
unsafe
{
fixed (LLOS.HAL.TimerContext** timer_ptr = &m_timerEvent)
{
LLOS.HAL.Timer.LLOS_SYSTEM_TIMER_AllocateTimer( HandleSystemTimer, ulong.MaxValue, timer_ptr );
}
}
ChipsetModel.NVIC.SetPriority( ChipsetModel.Board.Instance.GetSystemTimerIRQNumber(), RT.TargetPlatform.ARMv6.ProcessorARMv6M.c_Priority__SystemTimer );
//
// Set up a guard to never suffer from shutting down the underlying circuitry
//
//s_guard = CreateTimer( (timer, currentTime) => { timer.RelativeTimeout = QuarterCycle; } );
//s_guard.RelativeTimeout = QuarterCycle;
// no need to Refresh because guard causes a refresh already
Refresh();
}
/// <summary>
/// Create a new Timer and return to the user
/// </summary>
/// <param name="callback">Handler to run on timer expiration</param>
/// <returns>New Timer instance</returns>
public Timer CreateTimer(Callback callback)
{
return new Timer(this, callback);
}
/// <summary>
/// Gets the current accumulator time
/// </summary>
public ulong CurrentTime
{
get
{
using (RT.SmartHandles.InterruptState.Disable())
{
// Current time is the accumulator + time since it was updated
return m_accumulator + TimeSinceAccumulatorUpdate( this.Counter );
}
}
}
/// <summary>
/// Gets the current value of the timer accumulator
/// </summary>
public unsafe uint Counter
{
[RT.Inline]
get
{
return (uint)LLOS.HAL.Timer.LLOS_SYSTEM_TIMER_GetTicks( m_timerEvent );
}
}
/// <summary>
/// Protected constructor to ensure only we can create this
/// </summary>
protected SystemTimer()
{
}
public static extern SystemTimer Instance
{
[RT.SingletonFactory()]
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}
//--//
/// <summary>
/// Handle the timer expiration interrupt
/// </summary>
/// <param name="ticks">Time when the timer was fired</param>
private void ProcessTimeout(ulong ticks)
{
// Ensure that lastAccumulatorUpdate is always updated with the accumulator!
uint counter = this.Counter;
//
// BUGBUG: this logic does not cover the case of multiple wraparounds
//
m_accumulator += TimeSinceAccumulatorUpdate(counter);
m_lastAccumulatorUpdate = counter;
// we just updated this above, so it will be precise
ulong now = m_accumulator;
while (true)
{
RT.KernelNode<Timer> node = m_timers.StartOfForwardWalk;
// If the next node is null, break and call Refresh
if (node.IsValidForForwardMove == false)
{
break;
}
ulong timeout = node.Target.Timeout;
if (timeout > now)
{
// If we get here, there are no timers that need to be cleared/invoked
break;
}
// The current timeout is for the current node (Timer). Remove from List
// so we do not try to Reload its time.
node.RemoveFromList();
// Invoke the handler for the expired timer
node.Target.Invoke(now);
}
Refresh();
}
/// <summary>
/// Reload the next expiring timer, if there is one. Otherwise, reload QuarterCycle
/// </summary>
private void Refresh()
{
ulong absTimeout;
Timer target = m_timers.FirstTarget();
ulong now = this.CurrentTime;
if(target != null)
{
absTimeout = target.Timeout;
}
else
{
absTimeout = c_QuarterCycle + now;
}
//
// Timeout in the past? Trigger the match immediately by loading 1
// Timeout too far in the future? Generate match for
// a fraction of largest counter value, so we have time to handle wraparounds
//
Reload((now > absTimeout) ? 1 : (absTimeout - now));
}
/// <summary>
/// Place the timer closest to expiration on the mbed queue
/// </summary>
/// <param name="remainder"></param>
private void Reload(ulong remainder)
{
// trim to quarter cycle, so we have time to handle wraparounds
// This is guaranteed to fit in a uint
uint trimmed = (uint)Math.Min(remainder, c_QuarterCycle);
unsafe
{
LLOS.HAL.Timer.LLOS_SYSTEM_TIMER_ScheduleTimer( m_timerEvent, trimmed );
}
}
//
// Timer registration
//
/// <summary>
/// Add the timer to the queue in the chronologically appropriate position
/// </summary>
/// <param name="timer">Timer to add</param>
private void Register(Timer timer)
{
RT.KernelNode<Timer> node = timer.Node;
node.RemoveFromList();
ulong timeout = timer.Timeout;
RT.KernelNode<Timer> node2 = m_timers.StartOfForwardWalk;
while (node2.IsValidForForwardMove)
{
if (node2.Target.Timeout > timeout)
{
break;
}
node2 = node2.Next;
}
node.InsertBefore(node2);
Refresh();
}
/// <summary>
/// Remove the timer from the queue
/// </summary>
/// <param name="timer">Timer to be removed</param>
private void Deregister(Timer timer)
{
var node = timer.Node;
if (node.IsLinked)
{
node.RemoveFromList();
Refresh();
}
}
/// <summary>
/// Gets the difference in ticks between when the accumulator, and its last recorded value
/// </summary>
/// <returns>Difference in ticks</returns>
private uint TimeSinceAccumulatorUpdate( uint current )
{
// If the current timer value is greater than last accumulator update,
// the counter is still going up. Otherwise, the timer hit its max value
// and started counting from 0
return (current >= m_lastAccumulatorUpdate) ?
current - m_lastAccumulatorUpdate :
c_MaxCounterValue - m_lastAccumulatorUpdate + current;
}
private static void HandleSystemTimer(ulong ticks)
{
using(RT.SmartHandles.InterruptState.Disable())
{
Instance.ProcessTimeout( ticks );
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql.LegacySdk;
using Microsoft.Azure.Management.Sql.LegacySdk.Models;
namespace Microsoft.Azure.Management.Sql.LegacySdk
{
/// <summary>
/// The Windows Azure SQL Database management API provides a RESTful set of
/// web services that interact with Windows Azure SQL Database services to
/// manage your databases. The API enables users to create, retrieve,
/// update, and delete databases and servers.
/// </summary>
public static partial class ServerCommunicationLinkOperationsExtensions
{
/// <summary>
/// Begins creating a new or updating an existing Azure SQL Server
/// communication. To determine the status of the operation call
/// GetServerCommunicationLinkOperationStatus.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerCommunicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='communicationLinkName'>
/// Required. The name of the Azure SQL Server communication link to be
/// operated on (Updated or created).
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a Server
/// communication link.
/// </param>
/// <returns>
/// Response for long running Azure Sql server communication link
/// operation.
/// </returns>
public static ServerCommunicationLinkCreateOrUpdateResponse BeginCreateOrUpdate(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName, ServerCommunicationLinkCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerCommunicationLinkOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, serverName, communicationLinkName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Begins creating a new or updating an existing Azure SQL Server
/// communication. To determine the status of the operation call
/// GetServerCommunicationLinkOperationStatus.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerCommunicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='communicationLinkName'>
/// Required. The name of the Azure SQL Server communication link to be
/// operated on (Updated or created).
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a Server
/// communication link.
/// </param>
/// <returns>
/// Response for long running Azure Sql server communication link
/// operation.
/// </returns>
public static Task<ServerCommunicationLinkCreateOrUpdateResponse> BeginCreateOrUpdateAsync(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName, ServerCommunicationLinkCreateOrUpdateParameters parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, serverName, communicationLinkName, parameters, CancellationToken.None);
}
/// <summary>
/// Creates a new or updates an existing Azure SQL Server communication
/// link.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerCommunicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='communicationLinkName'>
/// Required. The name of the Azure SQL Server communication link to be
/// operated on (Updated or created).
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a Server
/// communication link.
/// </param>
/// <returns>
/// Response for long running Azure Sql server communication link
/// operation.
/// </returns>
public static ServerCommunicationLinkCreateOrUpdateResponse CreateOrUpdate(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName, ServerCommunicationLinkCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerCommunicationLinkOperations)s).CreateOrUpdateAsync(resourceGroupName, serverName, communicationLinkName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new or updates an existing Azure SQL Server communication
/// link.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerCommunicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='communicationLinkName'>
/// Required. The name of the Azure SQL Server communication link to be
/// operated on (Updated or created).
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a Server
/// communication link.
/// </param>
/// <returns>
/// Response for long running Azure Sql server communication link
/// operation.
/// </returns>
public static Task<ServerCommunicationLinkCreateOrUpdateResponse> CreateOrUpdateAsync(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName, ServerCommunicationLinkCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, serverName, communicationLinkName, parameters, CancellationToken.None);
}
/// <summary>
/// Deletes the Azure SQL server communication link with the given name.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerCommunicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='communicationLinkName'>
/// Required. The name of the Azure SQL server communication link to be
/// retrieved.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerCommunicationLinkOperations)s).DeleteAsync(resourceGroupName, serverName, communicationLinkName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the Azure SQL server communication link with the given name.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerCommunicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='communicationLinkName'>
/// Required. The name of the Azure SQL server communication link to be
/// retrieved.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName)
{
return operations.DeleteAsync(resourceGroupName, serverName, communicationLinkName, CancellationToken.None);
}
/// <summary>
/// Returns information about an Azure SQL Server communication links.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerCommunicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='communicationLinkName'>
/// Required. The name of the Azure SQL server communication link to be
/// retrieved.
/// </param>
/// <returns>
/// Represents the response to a get server communication link request.
/// </returns>
public static ServerCommunicationLinkGetResponse Get(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerCommunicationLinkOperations)s).GetAsync(resourceGroupName, serverName, communicationLinkName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns information about an Azure SQL Server communication links.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerCommunicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='communicationLinkName'>
/// Required. The name of the Azure SQL server communication link to be
/// retrieved.
/// </param>
/// <returns>
/// Represents the response to a get server communication link request.
/// </returns>
public static Task<ServerCommunicationLinkGetResponse> GetAsync(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName, string communicationLinkName)
{
return operations.GetAsync(resourceGroupName, serverName, communicationLinkName, CancellationToken.None);
}
/// <summary>
/// Gets the status of an Azure Sql Server communication link create or
/// update operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerCommunicationLinkOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure Sql server communication link
/// operation.
/// </returns>
public static ServerCommunicationLinkCreateOrUpdateResponse GetServerCommunicationLinkOperationStatus(this IServerCommunicationLinkOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerCommunicationLinkOperations)s).GetServerCommunicationLinkOperationStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the status of an Azure Sql Server communication link create or
/// update operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerCommunicationLinkOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure Sql server communication link
/// operation.
/// </returns>
public static Task<ServerCommunicationLinkCreateOrUpdateResponse> GetServerCommunicationLinkOperationStatusAsync(this IServerCommunicationLinkOperations operations, string operationStatusLink)
{
return operations.GetServerCommunicationLinkOperationStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// Returns information about Azure SQL Server communication links.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerCommunicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Server communication
/// link request.
/// </returns>
public static ServerCommunicationLinkListResponse List(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerCommunicationLinkOperations)s).ListAsync(resourceGroupName, serverName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns information about Azure SQL Server communication links.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IServerCommunicationLinkOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Server communication
/// link request.
/// </returns>
public static Task<ServerCommunicationLinkListResponse> ListAsync(this IServerCommunicationLinkOperations operations, string resourceGroupName, string serverName)
{
return operations.ListAsync(resourceGroupName, serverName, CancellationToken.None);
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web.Configuration;
using System.Web.Hosting;
using ASC.Common.Caching;
using ASC.Core;
using ASC.Core.Common.Configuration;
using ASC.Data.Storage.Configuration;
using ASC.Data.Storage.DiscStorage;
namespace ASC.Data.Storage
{
public static class StorageFactory
{
private const string DefaultTenantName = "default";
private static readonly ICacheNotify Cache;
static StorageFactory()
{
Cache = AscCache.Notify;
Cache.Subscribe<DataStoreCacheItem>((r, act) => DataStoreCache.Remove(r.TenantId, r.Module));
}
public static IDataStore GetStorage(string tenant, string module)
{
return GetStorage(string.Empty, tenant, module);
}
public static IDataStore GetStorage(string configpath, string tenant, string module)
{
int tenantId;
int.TryParse(tenant, out tenantId);
return GetStorage(configpath, tenant, module, new TenantQuotaController(tenantId));
}
public static IDataStore GetStorage(string configpath, string tenant, string module, IQuotaController controller)
{
var tenantId = -2;
if (string.IsNullOrEmpty(tenant))
{
tenant = DefaultTenantName;
}
else
{
tenantId = Convert.ToInt32(tenant);
}
//Make tenant path
tenant = TenantPath.CreatePath(tenant);
var store = DataStoreCache.Get(tenant, module);
if (store == null)
{
var section = GetSection(configpath);
if (section == null)
{
throw new InvalidOperationException("config section not found");
}
var settings = StorageSettings.LoadForTenant(tenantId);
store = GetStoreAndCache(tenant, module, section, settings.DataStoreConsumer, controller);
}
return store;
}
public static IDataStore GetStorageFromConsumer(string configpath, string tenant, string module, DataStoreConsumer consumer)
{
if (tenant == null) tenant = DefaultTenantName;
//Make tenant path
tenant = TenantPath.CreatePath(tenant);
var section = GetSection(configpath);
if (section == null)
{
throw new InvalidOperationException("config section not found");
}
int tenantId;
int.TryParse(tenant, out tenantId);
return GetDataStore(tenant, module, section, consumer, new TenantQuotaController(tenantId));
}
public static IEnumerable<string> GetModuleList(string configpath, bool exceptDisabledMigration = false)
{
var section = GetSection(configpath);
return section.Modules.Cast<ModuleConfigurationElement>()
.Where(x => x.Visible)
.Where(x => !exceptDisabledMigration || !x.DisabledMigrate)
.Select(x => x.Name);
}
public static IEnumerable<string> GetModuleList(string configpath, string type, bool exceptDisabledMigration = false)
{
var section = GetSection(configpath);
return section.Modules.Cast<ModuleConfigurationElement>()
.Where(x => x.Visible && x.Type == type)
.Where(x => !exceptDisabledMigration || !x.DisabledMigrate)
.Select(x => x.Name);
}
public static IEnumerable<string> GetDomainList(string configpath, string modulename)
{
var section = GetSection(configpath);
if (section == null)
{
throw new ArgumentException("config section not found");
}
return
section.Modules
.Cast<ModuleConfigurationElement>()
.Single(x => x.Name.Equals(modulename, StringComparison.OrdinalIgnoreCase))
.Domains.Cast<DomainConfigurationElement>()
.Where(x => x.Visible)
.Select(x => x.Name);
}
public static void InitializeHttpHandlers(string config = null)
{
if (!HostingEnvironment.IsHosted)
{
throw new InvalidOperationException("Application not hosted.");
}
var section = GetSection(config);
if (section != null)
{
//old scheme
var discHandler = section.Handlers.GetHandler("disc");
if (discHandler != null)
{
var props = discHandler.GetProperties();
foreach (var m in section.Modules.Cast<ModuleConfigurationElement>().Where(m => m.Type == "disc"))
{
if (m.Path.Contains(Constants.STORAGE_ROOT_PARAM))
DiscDataHandler.RegisterVirtualPath(
PathUtils.ResolveVirtualPath(m.VirtualPath),
PathUtils.ResolvePhysicalPath(m.Path, props),
m.Public);
foreach (var d in m.Domains.Cast<DomainConfigurationElement>().Where(d => (d.Type == "disc" || string.IsNullOrEmpty(d.Type)) && d.Path.Contains(Constants.STORAGE_ROOT_PARAM)))
{
DiscDataHandler.RegisterVirtualPath(
PathUtils.ResolveVirtualPath(d.VirtualPath),
PathUtils.ResolvePhysicalPath(d.Path, props));
}
}
}
//new scheme
foreach (var m in section.Modules.Cast<ModuleConfigurationElement>())
{
//todo: add path criterion
if (m.Type == "disc" || !m.Public || m.Path.Contains(Constants.STORAGE_ROOT_PARAM))
StorageHandler.RegisterVirtualPath(
m.Name,
string.Empty,
m.Public);
//todo: add path criterion
foreach (var d in m.Domains.Cast<DomainConfigurationElement>().Where(d => d.Path.Contains(Constants.STORAGE_ROOT_PARAM)))
{
StorageHandler.RegisterVirtualPath(
m.Name,
d.Name,
d.Public);
}
}
}
}
internal static void ClearCache()
{
var tenantId = CoreContext.TenantManager.GetCurrentTenant().TenantId.ToString();
var path = TenantPath.CreatePath(tenantId);
foreach (var module in GetModuleList("", true))
{
Cache.Publish(DataStoreCacheItem.Create(path, module), CacheNotifyAction.Remove);
}
}
private static IDataStore GetStoreAndCache(string tenant, string module, StorageConfigurationSection section, DataStoreConsumer consumer, IQuotaController controller)
{
var store = GetDataStore(tenant, module, section, consumer, controller);
if (store != null)
{
DataStoreCache.Put(store, tenant, module);
}
return store;
}
private static IDataStore GetDataStore(string tenant, string module, StorageConfigurationSection section, DataStoreConsumer consumer, IQuotaController controller)
{
var moduleElement = section.Modules.GetModuleElement(module);
if (moduleElement == null)
{
throw new ArgumentException("no such module", module);
}
var handler = section.Handlers.GetHandler(moduleElement.Type);
Type instanceType;
IDictionary<string, string> props;
if (CoreContext.Configuration.Standalone &&
!moduleElement.DisabledMigrate &&
consumer.IsSet)
{
instanceType = consumer.HandlerType;
props = consumer;
}
else
{
instanceType = handler.Type;
props = handler.GetProperties();
}
return ((IDataStore)Activator.CreateInstance(instanceType, tenant, handler, moduleElement))
.Configure(props)
.SetQuotaController(moduleElement.Count ? controller : null
/*don't count quota if specified on module*/);
}
private static StorageConfigurationSection GetSection(string configpath)
{
var sectionKey = "StorageConfigurationSection" + (configpath ?? "").Replace("\\", "").Replace("/", "");
var section = AscCache.Memory.Get<StorageConfigurationSection>(sectionKey);
if (section != null)
{
return section;
}
if (!string.IsNullOrEmpty(configpath))
{
if (configpath.Contains(Path.DirectorySeparatorChar) && (!Uri.IsWellFormedUriString(configpath, UriKind.Relative) || WorkContext.IsMono))
{
//Not mapped path
var filename = string.Compare(Path.GetExtension(configpath), ".config", true) == 0 ? configpath : Path.Combine(configpath, "Web.config");
var configMap = new ExeConfigurationFileMap { ExeConfigFilename = filename };
section = (StorageConfigurationSection)ConfigurationManager
.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None)
.GetSection(Schema.SECTION_NAME);
section.SetSourceFile(filename);
}
else
{
section = (StorageConfigurationSection)WebConfigurationManager
.OpenWebConfiguration(configpath)
.GetSection(Schema.SECTION_NAME);
}
}
else
{
section = (StorageConfigurationSection)ConfigurationManagerExtension.GetSection(Schema.SECTION_NAME);
}
AscCache.Memory.Insert(sectionKey, section, DateTime.MaxValue);
return section;
}
}
}
| |
#region License
/*
* All content copyright Terracotta, Inc., unless otherwise indicated. 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.
*
*/
#endregion
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Threading;
using Common.Logging;
using Quartz.Spi;
namespace Quartz.Core
{
/// <summary>
/// The thread responsible for performing the work of firing <see cref="ITrigger" />
/// s that are registered with the <see cref="QuartzScheduler" />.
/// </summary>
/// <seealso cref="QuartzScheduler" />
/// <seealso cref="IJob" />
/// <seealso cref="ITrigger" />
/// <author>James House</author>
/// <author>Marko Lahma (.NET)</author>
public class QuartzSchedulerThread : QuartzThread
{
private readonly ILog log;
private QuartzScheduler qs;
private QuartzSchedulerResources qsRsrcs;
private readonly object sigLock = new object();
private bool signaled;
private DateTimeOffset? signaledNextFireTimeUtc;
private bool paused;
private bool halted;
private readonly Random random = new Random((int) DateTimeOffset.Now.Ticks);
// When the scheduler finds there is no current trigger to fire, how long
// it should wait until checking again...
private static readonly TimeSpan DefaultIdleWaitTime = TimeSpan.FromSeconds(30);
private TimeSpan idleWaitTime = DefaultIdleWaitTime;
private int idleWaitVariableness = 7*1000;
/// <summary>
/// Gets the log.
/// </summary>
/// <value>The log.</value>
protected ILog Log
{
get { return log; }
}
/// <summary>
/// Sets the idle wait time.
/// </summary>
/// <value>The idle wait time.</value>
[TimeSpanParseRule(TimeSpanParseRule.Milliseconds)]
internal virtual TimeSpan IdleWaitTime
{
set
{
idleWaitTime = value;
idleWaitVariableness = (int) (value.TotalMilliseconds*0.2);
}
}
/// <summary>
/// Gets the randomized idle wait time.
/// </summary>
/// <value>The randomized idle wait time.</value>
private TimeSpan GetRandomizedIdleWaitTime()
{
return idleWaitTime - TimeSpan.FromMilliseconds(random.Next(idleWaitVariableness));
}
/// <summary>
/// Gets a value indicating whether this <see cref="QuartzSchedulerThread"/> is paused.
/// </summary>
/// <value><c>true</c> if paused; otherwise, <c>false</c>.</value>
internal virtual bool Paused
{
get { return paused; }
}
/// <summary>
/// Construct a new <see cref="QuartzSchedulerThread" /> for the given
/// <see cref="QuartzScheduler" /> as a non-daemon <see cref="Thread" />
/// with normal priority.
/// </summary>
internal QuartzSchedulerThread(QuartzScheduler qs, QuartzSchedulerResources qsRsrcs)
: this(qs, qsRsrcs, qsRsrcs.MakeSchedulerThreadDaemon, (int) ThreadPriority.Normal)
{
}
/// <summary>
/// Construct a new <see cref="QuartzSchedulerThread" /> for the given
/// <see cref="QuartzScheduler" /> as a <see cref="Thread" /> with the given
/// attributes.
/// </summary>
internal QuartzSchedulerThread(QuartzScheduler qs, QuartzSchedulerResources qsRsrcs,
bool setDaemon, int threadPrio) : base(qsRsrcs.ThreadName)
{
log = LogManager.GetLogger(GetType());
//ThreadGroup generatedAux = qs.SchedulerThreadGroup;
this.qs = qs;
this.qsRsrcs = qsRsrcs;
IsBackground = setDaemon;
Priority = (ThreadPriority) threadPrio;
// start the underlying thread, but put this object into the 'paused'
// state
// so processing doesn't start yet...
paused = true;
halted = false;
}
/// <summary>
/// Signals the main processing loop to pause at the next possible point.
/// </summary>
internal virtual void TogglePause(bool pause)
{
lock (sigLock)
{
paused = pause;
if (paused)
{
SignalSchedulingChange(SchedulerConstants.SchedulingSignalDateTime);
}
else
{
Monitor.PulseAll(sigLock);
}
}
}
/// <summary>
/// Signals the main processing loop to pause at the next possible point.
/// </summary>
internal virtual void Halt(bool wait)
{
lock (sigLock)
{
halted = true;
if (paused)
{
Monitor.PulseAll(sigLock);
}
else
{
SignalSchedulingChange(SchedulerConstants.SchedulingSignalDateTime);
}
}
if (wait)
{
bool interrupted = false;
try
{
while (true)
{
try
{
Join();
break;
}
catch (ThreadInterruptedException)
{
interrupted = true;
}
}
}
finally
{
if (interrupted)
{
Thread.CurrentThread.Interrupt();
}
}
}
}
/// <summary>
/// Signals the main processing loop that a change in scheduling has been
/// made - in order to interrupt any sleeping that may be occurring while
/// waiting for the fire time to arrive.
/// </summary>
/// <param name="candidateNewNextFireTimeUtc">
/// the time when the newly scheduled trigger
/// will fire. If this method is being called do to some other even (rather
/// than scheduling a trigger), the caller should pass null.
/// </param>
public void SignalSchedulingChange(DateTimeOffset? candidateNewNextFireTimeUtc)
{
lock (sigLock)
{
signaled = true;
signaledNextFireTimeUtc = candidateNewNextFireTimeUtc;
Monitor.PulseAll(sigLock);
}
}
public void ClearSignaledSchedulingChange()
{
lock (sigLock)
{
signaled = false;
signaledNextFireTimeUtc = SchedulerConstants.SchedulingSignalDateTime;
}
}
public bool IsScheduleChanged()
{
lock(sigLock)
{
return signaled;
}
}
public DateTimeOffset? GetSignaledNextFireTimeUtc()
{
lock (sigLock)
{
return signaledNextFireTimeUtc;
}
}
/// <summary>
/// The main processing loop of the <see cref="QuartzSchedulerThread" />.
/// </summary>
public override void Run()
{
bool lastAcquireFailed = false;
while (!halted)
{
try
{
// check if we're supposed to pause...
lock (sigLock)
{
while (paused && !halted)
{
try
{
// wait until togglePause(false) is called...
Monitor.Wait(sigLock, 1000);
}
catch (ThreadInterruptedException)
{
}
}
if (halted)
{
break;
}
}
int availThreadCount = qsRsrcs.ThreadPool.BlockForAvailableThreads();
if (availThreadCount > 0) // will always be true, due to semantics of blockForAvailableThreads...
{
IList<IOperableTrigger> triggers;
DateTimeOffset now = SystemTime.UtcNow();
ClearSignaledSchedulingChange();
try
{
triggers = qsRsrcs.JobStore.AcquireNextTriggers(
now + idleWaitTime, Math.Min(availThreadCount, qsRsrcs.MaxBatchSize), qsRsrcs.BatchTimeWindow);
lastAcquireFailed = false;
if (log.IsDebugEnabled)
{
log.DebugFormat("Batch acquisition of {0} triggers", (triggers == null ? 0 : triggers.Count));
}
}
catch (JobPersistenceException jpe)
{
if (!lastAcquireFailed)
{
qs.NotifySchedulerListenersError("An error occurred while scanning for the next trigger to fire.", jpe);
}
lastAcquireFailed = true;
continue;
}
catch (Exception e)
{
if (!lastAcquireFailed)
{
Log.Error("quartzSchedulerThreadLoop: RuntimeException " + e.Message, e);
}
lastAcquireFailed = true;
continue;
}
if (triggers != null && triggers.Count > 0)
{
now = SystemTime.UtcNow();
DateTimeOffset triggerTime = triggers[0].GetNextFireTimeUtc().Value;
TimeSpan timeUntilTrigger = triggerTime - now;
while (timeUntilTrigger > TimeSpan.Zero)
{
if (ReleaseIfScheduleChangedSignificantly(triggers, triggerTime))
{
break;
}
lock (sigLock)
{
if (halted)
{
break;
}
if (!IsCandidateNewTimeEarlierWithinReason(triggerTime, false))
{
try
{
// we could have blocked a long while
// on 'synchronize', so we must recompute
now = SystemTime.UtcNow();
timeUntilTrigger = triggerTime - now;
if (timeUntilTrigger > TimeSpan.Zero)
{
Monitor.Wait(sigLock, timeUntilTrigger);
}
}
catch (ThreadInterruptedException)
{
}
}
}
if (ReleaseIfScheduleChangedSignificantly(triggers, triggerTime))
{
break;
}
now = SystemTime.UtcNow();
timeUntilTrigger = triggerTime - now;
}
// this happens if releaseIfScheduleChangedSignificantly decided to release triggers
if (triggers.Count == 0)
{
continue;
}
// set triggers to 'executing'
IList<TriggerFiredResult> bndles = new List<TriggerFiredResult>();
bool goAhead;
lock (sigLock)
{
goAhead = !halted;
}
if (goAhead)
{
try
{
IList<TriggerFiredResult> res = qsRsrcs.JobStore.TriggersFired(triggers);
if (res != null)
{
bndles = res;
}
}
catch (SchedulerException se)
{
qs.NotifySchedulerListenersError("An error occurred while firing triggers '" + triggers + "'", se);
// QTZ-179 : a problem occurred interacting with the triggers from the db
// we release them and loop again
foreach (IOperableTrigger t in triggers)
{
qsRsrcs.JobStore.ReleaseAcquiredTrigger(t);
}
continue;
}
}
for (int i = 0; i < bndles.Count; i++)
{
TriggerFiredResult result = bndles[i];
TriggerFiredBundle bndle = result.TriggerFiredBundle;
Exception exception = result.Exception;
IOperableTrigger trigger = triggers[i];
// TODO SQL exception?
if (exception != null && (exception is DbException || exception.InnerException is DbException))
{
Log.Error("DbException while firing trigger " + trigger, exception);
qsRsrcs.JobStore.ReleaseAcquiredTrigger(trigger);
continue;
}
// it's possible to get 'null' if the triggers was paused,
// blocked, or other similar occurrences that prevent it being
// fired at this time... or if the scheduler was shutdown (halted)
if (bndle == null)
{
qsRsrcs.JobStore.ReleaseAcquiredTrigger(trigger);
continue;
}
// TODO: improvements:
//
// 2- make sure we can get a job runshell before firing trigger, or
// don't let that throw an exception (right now it never does,
// but the signature says it can).
// 3- acquire more triggers at a time (based on num threads available?)
JobRunShell shell;
try
{
shell = qsRsrcs.JobRunShellFactory.CreateJobRunShell(bndle);
shell.Initialize(qs);
}
catch (SchedulerException)
{
qsRsrcs.JobStore.TriggeredJobComplete(trigger, bndle.JobDetail, SchedulerInstruction.SetAllJobTriggersError);
continue;
}
if (qsRsrcs.ThreadPool.RunInThread(shell) == false)
{
// this case should never happen, as it is indicative of the
// scheduler being shutdown or a bug in the thread pool or
// a thread pool being used concurrently - which the docs
// say not to do...
Log.Error("ThreadPool.runInThread() return false!");
qsRsrcs.JobStore.TriggeredJobComplete(trigger, bndle.JobDetail, SchedulerInstruction.SetAllJobTriggersError);
}
}
continue; // while (!halted)
}
}
else // if(availThreadCount > 0)
{
// should never happen, if threadPool.blockForAvailableThreads() follows contract
continue;
// while (!halted)
}
DateTimeOffset utcNow = SystemTime.UtcNow();
DateTimeOffset waitTime = utcNow.Add(GetRandomizedIdleWaitTime());
TimeSpan timeUntilContinue = waitTime - utcNow;
lock (sigLock)
{
if (!halted)
{
try
{
// QTZ-336 A job might have been completed in the mean time and we might have
// missed the scheduled changed signal by not waiting for the notify() yet
// Check that before waiting for too long in case this very job needs to be
// scheduled very soon
if (!IsScheduleChanged())
{
Monitor.Wait(sigLock, timeUntilContinue);
}
}
catch (ThreadInterruptedException)
{
}
}
}
}
catch (Exception re)
{
if (Log != null)
{
Log.Error("Runtime error occurred in main trigger firing loop.", re);
}
}
} // while (!halted)
// drop references to scheduler stuff to aid garbage collection...
qs = null;
qsRsrcs = null;
}
private bool ReleaseIfScheduleChangedSignificantly(IList<IOperableTrigger> triggers, DateTimeOffset triggerTime)
{
if (IsCandidateNewTimeEarlierWithinReason(triggerTime, true))
{
foreach (IOperableTrigger trigger in triggers)
{
// above call does a clearSignaledSchedulingChange()
qsRsrcs.JobStore.ReleaseAcquiredTrigger(trigger);
}
triggers.Clear();
return true;
}
return false;
}
private bool IsCandidateNewTimeEarlierWithinReason(DateTimeOffset oldTimeUtc, bool clearSignal)
{
// So here's the deal: We know due to being signaled that 'the schedule'
// has changed. We may know (if getSignaledNextFireTime() != DateTimeOffset.MinValue) the
// new earliest fire time. We may not (in which case we will assume
// that the new time is earlier than the trigger we have acquired).
// In either case, we only want to abandon our acquired trigger and
// go looking for a new one if "it's worth it". It's only worth it if
// the time cost incurred to abandon the trigger and acquire a new one
// is less than the time until the currently acquired trigger will fire,
// otherwise we're just "thrashing" the job store (e.g. database).
//
// So the question becomes when is it "worth it"? This will depend on
// the job store implementation (and of course the particular database
// or whatever behind it). Ideally we would depend on the job store
// implementation to tell us the amount of time in which it "thinks"
// it can abandon the acquired trigger and acquire a new one. However
// we have no current facility for having it tell us that, so we make
// a somewhat educated but arbitrary guess.
lock (sigLock)
{
if (!IsScheduleChanged())
{
return false;
}
bool earlier = false;
if(!GetSignaledNextFireTimeUtc().HasValue)
{
earlier = true;
}
else if (GetSignaledNextFireTimeUtc().Value < oldTimeUtc)
{
earlier = true;
}
if(earlier)
{
// so the new time is considered earlier, but is it enough earlier?
TimeSpan diff = oldTimeUtc - SystemTime.UtcNow();
if(diff < (qsRsrcs.JobStore.SupportsPersistence ? TimeSpan.FromMilliseconds(70) : TimeSpan.FromMilliseconds(7)))
{
earlier = false;
}
}
if (clearSignal)
{
ClearSignaledSchedulingChange();
}
return earlier;
}
}
}
}
| |
//
// QueryParserTests.cs
//
// Author:
// Scott Thomas <lunchtimemama@gmail.com>
//
// Copyright (c) 2010 Scott Thomas
//
// 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.Text;
using NUnit.Framework;
using Mono.Upnp.Dcp.MediaServer1.ContentDirectory1;
using Mono.Upnp.Dcp.MediaServer1.Internal;
namespace Mono.Upnp.Dcp.MediaServer1.Tests
{
[TestFixture]
public class QueryParserTests : QueryTests
{
static readonly Query foo = new Query ("foo");
static readonly Query bat = new Query ("bat");
static readonly Query name = new Query ("name");
static readonly Query eyes = new Query ("eyes");
static readonly Query age = new Query ("age");
[Test]
public void EqualityOperator ()
{
AssertEquality (foo == "bar", @"foo = ""bar""");
}
[Test]
public void InequalityOperator ()
{
AssertEquality (foo != "bar", @"foo != ""bar""");
}
[Test]
public void LessThanOperator ()
{
AssertEquality (foo < "5", @"foo < ""5""");
}
[Test]
public void LessThanOrEqualOperator ()
{
AssertEquality (foo <= "5", @"foo <= ""5""");
}
[Test]
public void GreaterThanOperator ()
{
AssertEquality (foo > "5", @"foo > ""5""");
}
[Test]
public void GreaterThanOrEqualOperator ()
{
AssertEquality (foo >= "5", @"foo >= ""5""");
}
[Test]
public void ContainsOperator ()
{
AssertEquality (foo.Contains ("bar"), @"foo contains ""bar""");
}
[Test]
public void ExistsTrue ()
{
AssertEquality (foo.Exists (true), "foo exists true");
}
[Test]
public void ExistsFalse ()
{
AssertEquality (foo.Exists (false), "foo exists false");
}
[Test]
public void ExistsTrueWithTrailingWhiteSpace ()
{
AssertEquality (foo.Exists (true), "foo exists true ");
}
[Test]
public void ExistsFalseWithTrailingWhiteSpace ()
{
AssertEquality (foo.Exists (false), "foo exists false ");
}
[Test]
public void ExistsTrueWithLeadingWhiteSpace ()
{
AssertEquality (foo.Exists (true), "foo exists \t\rtrue");
}
[Test]
public void ExistsFalseWithLeadingWhiteSpace ()
{
AssertEquality (foo.Exists (false), "foo exists \t\rfalse");
}
[Test]
public void DerivedFromOperator ()
{
AssertEquality (foo.DerivedFrom ("object.item"), @"foo derivedfrom ""object.item""");
}
[Test]
public void NamespacedDerivedFromOperator ()
{
var @class = new Query ("upnp:class");
AssertEquality (@class.DerivedFrom ("object.item"), @"upnp:class derivedfrom ""object.item""");
}
[Test]
public void DoesNotContainOperator ()
{
AssertEquality (foo.DoesNotContain ("bar"), @"foo doesNotContain ""bar""");
}
[Test]
public void EscapedDoubleQuote ()
{
AssertEquality (foo == @"b""a""r", @"foo = ""b\""a\""r""");
}
[Test]
public void EscapedSlash ()
{
AssertEquality (foo == @"b\a\r", @"foo = ""b\\a\\r""");
}
[Test]
public void AndOperator ()
{
AssertEquality (
Conjoin (foo == "bar", bat == "baz"),
@"foo = ""bar"" and bat = ""baz""");
}
[Test]
public void OrOperator ()
{
AssertEquality (
Disjoin (foo == "bar", bat == "baz"),
@"foo = ""bar"" or bat = ""baz""");
}
[Test]
public void OperatorPriority ()
{
AssertEquality (
Disjoin (
Disjoin (
Conjoin (foo == "bar", bat == "baz"),
name.Contains ("john")),
Conjoin (eyes == "green", age >= "21")),
@"foo = ""bar"" and bat = ""baz"" or name contains ""john"" or eyes = ""green"" and age >= ""21""");
}
[Test]
public void ParentheticalPriority1 ()
{
AssertEquality (
Disjoin (
Conjoin (foo == "bar", bat == "baz"),
Conjoin (
Disjoin (name.Contains ("john"), eyes == "green"),
age >= "21")),
@"foo = ""bar"" and bat = ""baz"" or (name contains ""john"" or eyes = ""green"") and age >= ""21""");
}
[Test]
public void ParentheticalPriority2 ()
{
AssertEquality (
Conjoin (
Conjoin (
foo == "bar",
Disjoin (
Disjoin (bat == "baz", name.Contains ("john")),
eyes == "green")),
age >= "21"),
@"foo = ""bar"" and ((bat = ""baz"" or name contains ""john"") or eyes = ""green"") and age >= ""21""");
}
[Test]
public void ParentheticalPriority3 ()
{
AssertEquality (
Disjoin (
Conjoin (
foo == "bar",
Disjoin (bat == "baz", name.Contains ("john"))),
Conjoin (eyes == "green", age >= "21")),
@"foo = ""bar"" and (bat = ""baz"" or name contains ""john"") or eyes = ""green"" and age >= ""21""");
}
[Test]
public void ParentheticalPriority4 ()
{
AssertEquality (
Conjoin (
Conjoin (
Disjoin (foo == "bar", bat == "baz"),
Disjoin (name.Contains ("john"), eyes == "green")),
age >= "21"),
@"(foo = ""bar"" or bat = ""baz"") and (name contains ""john"" or eyes = ""green"") and age >= ""21""");
}
[Test]
public void ParentheticalPriority5 ()
{
AssertEquality (
Conjoin (
Disjoin (foo == "bar", bat.Exists (true)),
Conjoin (
Disjoin (name.Contains ("john"), eyes.Exists (false)),
age >= "21")),
@"(foo = ""bar"" or bat exists true) and ((name contains ""john"" or eyes exists false) and age >= ""21"")");
}
[Test]
public void WildCard ()
{
AssertEquality (visitor => visitor.VisitAllResults (), "*");
}
[Test]
public void WildCardWithWhiteSpace ()
{
AssertEquality (visitor => visitor.VisitAllResults (), " * ");
}
[Test]
public void WhiteSpaceAroundOperator ()
{
var expected = foo == "bar";
AssertEquality (expected, @" foo = ""bar""");
AssertEquality (expected, @"foo = ""bar""");
AssertEquality (expected, @"foo = ""bar""");
AssertEquality (expected, @"foo = ""bar"" ");
AssertEquality (expected, @" foo = ""bar"" ");
}
[Test]
public void DerivedFromOperatorWithParentheses ()
{
AssertEquality (
new Query ("upnp:class").DerivedFrom ("object.item.audioItem"),
@"(upnp:class derivedfrom ""object.item.audioItem"")");
}
[Test, ExpectedException (typeof (QueryParsingException), ExpectedMessage = "The query is empty.")]
public void EmptyQuery ()
{
QueryParser.Parse ("");
}
[Test, ExpectedException (typeof (QueryParsingException), ExpectedMessage = "Unexpected operator: !.")]
public void IncompleteInequalityOperator ()
{
QueryParser.Parse (@"foo ! ""bar""");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "The property identifier is not a part of an expression: foo.")]
public void NoOperator ()
{
QueryParser.Parse ("foo");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = @"No operator is applied to the property identifier: foo.")]
public void NoOperatorAndTrailingWhiteSpace ()
{
QueryParser.Parse ("foo ");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = @"The property identifier is not a part of an expression: foo=""bar"".")]
public void NoWhiteSpaceAroundOperator ()
{
QueryParser.Parse (@"foo=""bar""");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = @"Unexpected operator begining: ="".")]
public void NoTrailingWhiteSpaceAroundOperator ()
{
QueryParser.Parse (@"foo =""bar""");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Unexpected operator begining: ==.")]
public void DoubleEqualityOperator ()
{
QueryParser.Parse (@"foo == ""bar""");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = @"Unexpected operator begining: <"".")]
public void NoTrailingWhiteSpaceAroundLessThan ()
{
QueryParser.Parse (@"foo <""bar""");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = @"Unexpected operator begining: <="".")]
public void NoTrailingWhiteSpaceAroundLessThanOrEqualTo ()
{
QueryParser.Parse (@"foo <=""bar""");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = @"Unexpected operator begining: >"".")]
public void NoTrailingWhiteSpaceAroundGreaterThan ()
{
QueryParser.Parse (@"foo >""bar""");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = @"Unexpected operator begining: >="".")]
public void NoTrailingWhiteSpaceAroundGreaterThanOrEqualTo ()
{
QueryParser.Parse (@"foo >=""bar""");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Expecting double-quoted string operand with the operator: =.")]
public void UnquotedOperand ()
{
QueryParser.Parse ("foo = bar");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Unexpected operator begining: /.")]
public void UnexpectedOperator ()
{
QueryParser.Parse (@"foo / ""bar""");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = @"The double-quoted string is not terminated: ""bar"".")]
public void UnterminatedDoubleQuotedString ()
{
QueryParser.Parse (@"foo = ""bar");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "There is no operand for the operator: =.")]
public void MissingOperandWithNoSpace ()
{
QueryParser.Parse ("foo =");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "There is no operand for the operator: =.")]
public void MissingOperandWithSpace ()
{
QueryParser.Parse ("foo = ");
}
[Test]
[ExpectedException (typeof (QueryParsingException), ExpectedMessage = "Unexpected operator: contain.")]
public void IncompleteContainsOperator ()
{
QueryParser.Parse (@"foo contain ""bar""");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Unexpected operator begining: containe.")]
public void IncorrectContainsOperator ()
{
QueryParser.Parse (@"foo container ""bar""");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Unexpected operator begining: containsi.")]
public void OverlongContainsOperator ()
{
QueryParser.Parse (@"foo containsing ""bar""");
}
const string boolean_error_message = @"Expecting either ""true"" or ""false"".";
[Test, ExpectedException (typeof (QueryParsingException), ExpectedMessage = boolean_error_message)]
public void IllegalBooleanLiteral ()
{
QueryParser.Parse ("foo exists bar");
}
[Test, ExpectedException (typeof (QueryParsingException), ExpectedMessage = boolean_error_message)]
public void IllegalTrueLiteral ()
{
QueryParser.Parse ("foo exists troo");
}
[Test, ExpectedException (typeof (QueryParsingException), ExpectedMessage = boolean_error_message)]
public void IllegalFalseLiteral ()
{
QueryParser.Parse ("foo exists falze");
}
[Test, ExpectedException (typeof (QueryParsingException), ExpectedMessage = boolean_error_message)]
public void IllegallyShortTrueLiteral ()
{
QueryParser.Parse ("foo exists tru");
}
[Test, ExpectedException (typeof (QueryParsingException), ExpectedMessage = boolean_error_message)]
public void IllegallyShortTrueLiteralWithTrailingWhitespace ()
{
QueryParser.Parse ("foo exists tru ");
}
[Test, ExpectedException (typeof (QueryParsingException), ExpectedMessage = boolean_error_message)]
public void IllegallyShortFalseLiteral ()
{
QueryParser.Parse ("foo exists fals");
}
[Test, ExpectedException (typeof (QueryParsingException), ExpectedMessage = boolean_error_message)]
public void IllegallyShortFalseLiteralWithTrailingWhitespace ()
{
QueryParser.Parse ("foo exists fals ");
}
[Test, ExpectedException (typeof (QueryParsingException), ExpectedMessage = boolean_error_message)]
public void IllegallyLongTrueLiteral ()
{
QueryParser.Parse ("foo exists truely");
}
[Test, ExpectedException (typeof (QueryParsingException), ExpectedMessage = boolean_error_message)]
public void IllegallyLongFalseLiteral ()
{
QueryParser.Parse ("foo exists falserize");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "There is no operand for the operator: exists.")]
public void ExistsOperatorWithNoOperand ()
{
QueryParser.Parse ("foo exists ");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Unexpected operator begining: du.")]
public void NeitherDerivedFromNorDoesNotContain ()
{
QueryParser.Parse (@"foo dumbo ""bar""");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Unexpected operator: d.")]
public void IllegallyShortDerivedFromOrDoesNotContain ()
{
QueryParser.Parse ("foo d");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Unexpected operator: d.")]
public void IllegallyShortDerivedFromOrDoesNotContainWithWhiteSpace ()
{
QueryParser.Parse (@"foo d ""bar""");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Unexpected operator begining: az.")]
public void IllegalAndOperator1 ()
{
QueryParser.Parse (@"foo = ""bar"" az");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Unexpected operator begining: anz.")]
public void IllegalAndOperator2 ()
{
QueryParser.Parse (@"foo = ""bar"" anz");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Unexpected operator begining: andz.")]
public void IllegalAndOperator3 ()
{
QueryParser.Parse (@"foo = ""bar"" andz");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Unexpected operator: a.")]
public void IllegallyShortAndOperator1 ()
{
QueryParser.Parse (@"foo = ""bar"" a");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Unexpected operator: a.")]
public void IllegallyShortAndOperatorWithTrailingWhiteSpace1 ()
{
QueryParser.Parse ("foo = \"bar\" a\t");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Unexpected operator: an.")]
public void IllegallyShortAndOperator2 ()
{
QueryParser.Parse (@"foo = ""bar"" an");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Unexpected operator: an.")]
public void IllegallyShortAndOperatorWithTrailingWhiteSpace2 ()
{
QueryParser.Parse ("foo = \"bar\" an\t");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "There is no operand for the operator: and.")]
public void IncompleteConjuction ()
{
QueryParser.Parse (@"foo = ""bar"" and");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "There is no operand for the operator: and.")]
public void IncompleteConjuctionWithTrailingWhiteSpace ()
{
QueryParser.Parse ("foo = \"bar\" and \t\n");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Unexpected operator begining: oz.")]
public void IllegalOrOperator1 ()
{
QueryParser.Parse (@"foo = ""bar"" oz");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Unexpected operator begining: orz.")]
public void IllegalOrOperator2 ()
{
QueryParser.Parse (@"foo = ""bar"" orz");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Unexpected operator: o.")]
public void IllegallyShortOrOperator ()
{
QueryParser.Parse (@"foo = ""bar"" o");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Unexpected operator: o.")]
public void IllegallyShortOrOperatorWithTrailingWhiteSpace ()
{
QueryParser.Parse (@"foo = ""bar"" o ");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "There is no operand for the operator: or.")]
public void IncompleteDisjunction ()
{
QueryParser.Parse (@"foo = ""bar"" or");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "There is no operand for the operator: or.")]
public void IncompleteDisjunctionWithTrailingWhiteSpace ()
{
QueryParser.Parse (@"foo = ""bar"" or ");
}
[Test]
[ExpectedException (typeof (QueryParsingException), ExpectedMessage = "The parentheses are unbalanced.")]
public void UnbalancedOpeningParenthesis ()
{
QueryParser.Parse (")");
}
[Test]
[ExpectedException (typeof (QueryParsingException), ExpectedMessage = "Empty expressions are not allowed.")]
public void OpeningEmptyParentheses ()
{
QueryParser.Parse ("()");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Expecting an expression after the conjunction.")]
public void ConjoinedEmptyParentheses ()
{
QueryParser.Parse (@"foo = ""bar"" and ()");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Expecting an expression after the disjunction.")]
public void DisjoinedEmptyParentheses ()
{
QueryParser.Parse (@"foo = ""bar"" or ()");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Unexpected operator begining: n.")]
public void NeitherAndNorOr ()
{
QueryParser.Parse (@"foo = ""bar"" nor bat = ""baz""");
}
[Test]
[ExpectedException (typeof (QueryParsingException), ExpectedMessage = "The parentheses are unbalanced.")]
public void BackHeavyUnbalancedEquasionStatement ()
{
QueryParser.Parse (@"foo = ""bar"")");
}
[Test]
[ExpectedException (typeof (QueryParsingException), ExpectedMessage = "The parentheses are unbalanced.")]
public void FrontHeavyUnbalancedEquasionStatement ()
{
QueryParser.Parse (@"(foo = ""bar""");
}
[Test]
[ExpectedException (typeof (QueryParsingException), ExpectedMessage = "The parentheses are unbalanced.")]
public void UnbalancedExistsStatement ()
{
QueryParser.Parse (@"foo exists true )");
}
[Test]
[ExpectedException (typeof (QueryParsingException), ExpectedMessage = "The parentheses are unbalanced.")]
public void UnbalancedConjunction ()
{
QueryParser.Parse (@"foo exists true and bar = ""bat"" )");
}
[Test]
[ExpectedException (typeof (QueryParsingException), ExpectedMessage = "The parentheses are unbalanced.")]
public void UnbalancedDisjunction ()
{
QueryParser.Parse (@"foo exists true or bar = ""bat"" )");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Expecting an expression after the conjunction.")]
public void IllegalParenthesisWithConjunction ()
{
QueryParser.Parse (@"foo exists true and )");
}
[Test]
[ExpectedException (typeof (QueryParsingException),
ExpectedMessage = "Expecting an expression after the disjunction.")]
public void IllegalParenthesisWithDisjunction ()
{
QueryParser.Parse (@"foo exists true or )");
}
[Test]
[ExpectedException (typeof (QueryParsingException), ExpectedMessage = "The wildcard must be used alone.")]
public void WildCardWithOpenParenthesis ()
{
QueryParser.Parse (@"* (foo exists true)");
}
[Test]
[ExpectedException (typeof (QueryParsingException), ExpectedMessage = "The parentheses are unbalanced.")]
public void WildCardWithCloseParenthesis ()
{
QueryParser.Parse (@"* ) foo exists true)");
}
[Test]
[ExpectedException (typeof (QueryParsingException), ExpectedMessage = "The wildcard must be used alone.")]
public void WildCardWithConjunction ()
{
QueryParser.Parse (@"* and foo exists true");
}
[Test]
[ExpectedException (typeof (QueryParsingException), ExpectedMessage = "The wildcard must be used alone.")]
public void DoubleWildCards ()
{
QueryParser.Parse (@"* *");
}
[Test]
[ExpectedException (typeof (QueryParsingException), ExpectedMessage = @"Unexpected escape sequence: \t.")]
public void BadEscapeSequence ()
{
QueryParser.Parse (@"foo = ""\tbar""");
}
void AssertEquality (Action<QueryVisitor> expectedQuery, string actualQuery)
{
var expected_builder = new StringBuilder ();
var actual_builder = new StringBuilder ();
expectedQuery (new QueryStringifier (expected_builder));
QueryParser.Parse (actualQuery) (new QueryStringifier (actual_builder));
Assert.AreEqual (expected_builder.ToString (), actual_builder.ToString ());
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.DynamoDB.Model
{
/// <summary>
/// <para>AttributeValue can be <c>String</c> ,
/// <c>Number</c> ,
/// <c>Binary</c> ,
/// <c>StringSet</c> ,
/// <c>NumberSet</c> ,
/// <c>BinarySet</c> .</para>
/// </summary>
public class AttributeValue
{
private string s;
private string n;
private MemoryStream b;
private List<string> sS = new List<string>();
private List<string> nS = new List<string>();
private List<MemoryStream> bS = new List<MemoryStream>();
/// <summary>
/// Strings are Unicode with UTF-8 binary encoding. The maximum size is limited by the size of the primary key (1024 bytes as a range part of a
/// key or 2048 bytes as a single part hash key) or the item size (64k).
///
/// </summary>
public string S
{
get { return this.s; }
set { this.s = value; }
}
/// <summary>
/// Sets the S property
/// </summary>
/// <param name="s">The value to set for the S property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AttributeValue WithS(string s)
{
this.s = s;
return this;
}
// Check to see if S property is set
internal bool IsSetS()
{
return this.s != null;
}
/// <summary>
/// Numbers are positive or negative exact-value decimals and integers. A number can have up to 38 digits precision and can be between 10^-128
/// to 10^+126.
///
/// </summary>
public string N
{
get { return this.n; }
set { this.n = value; }
}
/// <summary>
/// Sets the N property
/// </summary>
/// <param name="n">The value to set for the N property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AttributeValue WithN(string n)
{
this.n = n;
return this;
}
// Check to see if N property is set
internal bool IsSetN()
{
return this.n != null;
}
/// <summary>
/// Binary attributes are sequences of unsigned bytes.
///
/// </summary>
public MemoryStream B
{
get { return this.b; }
set { this.b = value; }
}
/// <summary>
/// Sets the B property
/// </summary>
/// <param name="b">The value to set for the B property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AttributeValue WithB(MemoryStream b)
{
this.b = b;
return this;
}
// Check to see if B property is set
internal bool IsSetB()
{
return this.b != null;
}
/// <summary>
/// A set of strings.
///
/// </summary>
public List<string> SS
{
get { return this.sS; }
set { this.sS = value; }
}
/// <summary>
/// Adds elements to the SS collection
/// </summary>
/// <param name="sS">The values to add to the SS collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AttributeValue WithSS(params string[] sS)
{
foreach (string element in sS)
{
this.sS.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the SS collection
/// </summary>
/// <param name="sS">The values to add to the SS collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AttributeValue WithSS(IEnumerable<string> sS)
{
foreach (string element in sS)
{
this.sS.Add(element);
}
return this;
}
// Check to see if SS property is set
internal bool IsSetSS()
{
return this.sS.Count > 0;
}
/// <summary>
/// A set of numbers.
///
/// </summary>
public List<string> NS
{
get { return this.nS; }
set { this.nS = value; }
}
/// <summary>
/// Adds elements to the NS collection
/// </summary>
/// <param name="nS">The values to add to the NS collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AttributeValue WithNS(params string[] nS)
{
foreach (string element in nS)
{
this.nS.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the NS collection
/// </summary>
/// <param name="nS">The values to add to the NS collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AttributeValue WithNS(IEnumerable<string> nS)
{
foreach (string element in nS)
{
this.nS.Add(element);
}
return this;
}
// Check to see if NS property is set
internal bool IsSetNS()
{
return this.nS.Count > 0;
}
/// <summary>
/// A set of binary attributes.
///
/// </summary>
public List<MemoryStream> BS
{
get { return this.bS; }
set { this.bS = value; }
}
/// <summary>
/// Adds elements to the BS collection
/// </summary>
/// <param name="bS">The values to add to the BS collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AttributeValue WithBS(params MemoryStream[] bS)
{
foreach (MemoryStream element in bS)
{
this.bS.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the BS collection
/// </summary>
/// <param name="bS">The values to add to the BS collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public AttributeValue WithBS(IEnumerable<MemoryStream> bS)
{
foreach (MemoryStream element in bS)
{
this.bS.Add(element);
}
return this;
}
// Check to see if BS property is set
internal bool IsSetBS()
{
return this.bS.Count > 0;
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.PnL.Algo
File: PnLQueue.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo.PnL
{
using System;
using System.Linq;
using Ecng.Collections;
using Ecng.Common;
using StockSharp.Messages;
/// <summary>
/// The queue of profit calculation by messages stream.
/// </summary>
public class PnLQueue
{
private Sides _openedPosSide;
private readonly SynchronizedStack<RefPair<decimal, decimal>> _openedTrades = new SynchronizedStack<RefPair<decimal, decimal>>();
private decimal _multiplier;
/// <summary>
/// Initializes a new instance of the <see cref="PnLQueue"/>.
/// </summary>
/// <param name="securityId">Security ID.</param>
public PnLQueue(SecurityId securityId)
{
SecurityId = securityId;
PriceStep = 1;
StepPrice = 1;
}
/// <summary>
/// Security ID.
/// </summary>
public SecurityId SecurityId { get; private set; }
private decimal _priceStep;
/// <summary>
/// Price step.
/// </summary>
public decimal PriceStep
{
get { return _priceStep; }
private set
{
_priceStep = value;
UpdateMultiplier();
}
}
private decimal _stepPrice;
/// <summary>
/// Step price.
/// </summary>
public decimal StepPrice
{
get { return _stepPrice; }
private set
{
_stepPrice = value;
UpdateMultiplier();
}
}
/// <summary>
/// Last price of tick trade.
/// </summary>
public decimal TradePrice { get; private set; }
/// <summary>
/// Last price of demand.
/// </summary>
public decimal BidPrice { get; private set; }
/// <summary>
/// Last price of offer.
/// </summary>
public decimal AskPrice { get; private set; }
private decimal? _unrealizedPnL;
/// <summary>
/// Unrealized profit.
/// </summary>
public decimal UnrealizedPnL
{
get
{
var v = _unrealizedPnL;
if (v != null)
return v.Value;
var sum = _openedTrades
.SyncGet(c => c.Sum(t =>
{
var price = _openedPosSide == Sides.Buy ? AskPrice : BidPrice;
if (price == 0)
price = TradePrice;
return TraderHelper.GetPnL(t.First, t.Second, _openedPosSide, price);
}));
v = _unrealizedPnL = sum * _multiplier;
return v.Value;
}
}
/// <summary>
/// Realized profit.
/// </summary>
public decimal RealizedPnL { get; private set; }
/// <summary>
/// To calculate trade profitability. If the trade was already processed earlier, previous information returns.
/// </summary>
/// <param name="trade">Trade.</param>
/// <returns>Information on new trade.</returns>
public PnLInfo Process(ExecutionMessage trade)
{
if (trade == null)
throw new ArgumentNullException(nameof(trade));
var closedVolume = 0m;
var pnl = 0m;
var volume = trade.SafeGetVolume();
var price = trade.GetTradePrice();
_unrealizedPnL = null;
lock (_openedTrades.SyncRoot)
{
if (_openedTrades.Count > 0)
{
var currTrade = _openedTrades.Peek();
if (_openedPosSide != trade.Side)
{
while (volume > 0)
{
if (currTrade == null)
currTrade = _openedTrades.Peek();
var diff = currTrade.Second.Min(volume);
closedVolume += diff;
pnl += TraderHelper.GetPnL(currTrade.First, diff, _openedPosSide, price);
volume -= diff;
currTrade.Second -= diff;
if (currTrade.Second != 0)
continue;
currTrade = null;
_openedTrades.Pop();
if (_openedTrades.Count == 0)
break;
}
}
}
if (volume > 0)
{
_openedPosSide = trade.Side;
_openedTrades.Push(RefTuple.Create(price, volume));
}
RealizedPnL += _multiplier * pnl;
}
return new PnLInfo(trade, closedVolume, pnl);
}
/// <summary>
/// To process the message, containing market data.
/// </summary>
/// <param name="levelMsg">The message, containing market data.</param>
public void ProcessLevel1(Level1ChangeMessage levelMsg)
{
var priceStep = levelMsg.Changes.TryGetValue(Level1Fields.PriceStep);
if (priceStep != null)
{
PriceStep = (decimal)priceStep;
_unrealizedPnL = null;
}
var stepPrice = levelMsg.Changes.TryGetValue(Level1Fields.StepPrice);
if (stepPrice != null)
{
StepPrice = (decimal)stepPrice;
_unrealizedPnL = null;
}
var tradePrice = levelMsg.Changes.TryGetValue(Level1Fields.LastTradePrice);
if (tradePrice != null)
{
TradePrice = (decimal)tradePrice;
_unrealizedPnL = null;
}
var bidPrice = levelMsg.Changes.TryGetValue(Level1Fields.BestBidPrice);
if (bidPrice != null)
{
BidPrice = (decimal)bidPrice;
_unrealizedPnL = null;
}
var askPrice = levelMsg.Changes.TryGetValue(Level1Fields.BestAskPrice);
if (askPrice != null)
{
AskPrice = (decimal)askPrice;
_unrealizedPnL = null;
}
}
/// <summary>
/// To process the message, containing information on tick trade.
/// </summary>
/// <param name="execMsg">The message, containing information on tick trade.</param>
public void ProcessExecution(ExecutionMessage execMsg)
{
if (execMsg.TradePrice != null)
{
TradePrice = execMsg.TradePrice.Value;
_unrealizedPnL = null;
}
}
/// <summary>
/// To process the message, containing data on order book.
/// </summary>
/// <param name="quoteMsg">The message, containing data on order book.</param>
public void ProcessQuotes(QuoteChangeMessage quoteMsg)
{
var ask = quoteMsg.GetBestAsk();
AskPrice = ask != null ? ask.Price : 0;
var bid = quoteMsg.GetBestBid();
BidPrice = bid != null ? bid.Price : 0;
_unrealizedPnL = null;
}
private void UpdateMultiplier()
{
_multiplier = StepPrice == 0 || PriceStep == 0
? 1
: StepPrice / PriceStep;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.HSSF.Record
{
using System;
using System.Collections.Generic;
using System.Text;
using NPOI.HSSF.Record.Cont;
using NPOI.Util;
/**
* Title: Unicode String<p/>
* Description: Unicode String - just standard fields that are in several records.
* It is considered more desirable then repeating it in all of them.<p/>
* This is often called a XLUnicodeRichExtendedString in MS documentation.<p/>
* REFERENCE: PG 264 Microsoft Excel 97 Developer's Kit (ISBN: 1-57231-498-2)<p/>
* REFERENCE: PG 951 Excel Binary File Format (.xls) Structure Specification v20091214
*/
internal class UnicodeString : IComparable<UnicodeString>
{ // TODO - make this when the compatibility version is Removed
private static POILogger _logger = POILogFactory.GetLogger(typeof(UnicodeString));
private short field_1_charCount;
private byte field_2_optionflags;
private String field_3_string;
private List<FormatRun> field_4_format_Runs;
private ExtRst field_5_ext_rst;
private static BitField highByte = BitFieldFactory.GetInstance(0x1);
// 0x2 is reserved
private static BitField extBit = BitFieldFactory.GetInstance(0x4);
private static BitField richText = BitFieldFactory.GetInstance(0x8);
internal class FormatRun : IComparable<FormatRun>
{
internal short _character;
internal short _fontIndex;
public FormatRun(short character, short fontIndex)
{
this._character = character;
this._fontIndex = fontIndex;
}
public FormatRun(ILittleEndianInput in1) :
this(in1.ReadShort(), in1.ReadShort())
{
}
public short CharacterPos
{
get
{
return _character;
}
}
public short FontIndex
{
get
{
return _fontIndex;
}
}
public override bool Equals(Object o)
{
if (!(o is FormatRun))
{
return false;
}
FormatRun other = (FormatRun)o;
return _character == other._character && _fontIndex == other._fontIndex;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public int CompareTo(FormatRun r)
{
if (_character == r._character && _fontIndex == r._fontIndex)
{
return 0;
}
if (_character == r._character)
{
return _fontIndex - r._fontIndex;
}
return _character - r._character;
}
public override String ToString()
{
return "character=" + _character + ",fontIndex=" + _fontIndex;
}
public void Serialize(ILittleEndianOutput out1)
{
out1.WriteShort(_character);
out1.WriteShort(_fontIndex);
}
}
// See page 681
internal class ExtRst : IComparable<ExtRst>
{
private short reserved;
// This is a Phs (see page 881)
private short formattingFontIndex;
private short formattingOptions;
// This is a RPHSSub (see page 894)
private int numberOfRuns;
private String phoneticText;
// This is an array of PhRuns (see page 881)
private PhRun[] phRuns;
// Sometimes there's some cruft at the end
private byte[] extraData;
private void populateEmpty()
{
reserved = 1;
phoneticText = "";
phRuns = new PhRun[0];
extraData = new byte[0];
}
public override int GetHashCode()
{
return base.GetHashCode();
}
internal ExtRst()
{
populateEmpty();
}
internal ExtRst(ILittleEndianInput in1, int expectedLength)
{
reserved = in1.ReadShort();
// Old style detection (Reserved = 0xFF)
if (reserved == -1)
{
populateEmpty();
return;
}
// Spot corrupt records
if (reserved != 1)
{
_logger.Log(POILogger.WARN, "Warning - ExtRst has wrong magic marker, expecting 1 but found " + reserved + " - ignoring");
// Grab all the remaining data, and ignore it
for (int i = 0; i < expectedLength - 2; i++)
{
in1.ReadByte();
}
// And make us be empty
populateEmpty();
return;
}
// Carry on Reading in as normal
short stringDataSize = in1.ReadShort();
formattingFontIndex = in1.ReadShort();
formattingOptions = in1.ReadShort();
// RPHSSub
numberOfRuns = in1.ReadUShort();
short length1 = in1.ReadShort();
// No really. Someone Clearly forgot to read
// the docs on their datastructure...
short length2 = in1.ReadShort();
// And sometimes they write out garbage :(
if (length1 == 0 && length2 > 0)
{
length2 = 0;
}
if (length1 != length2)
{
throw new InvalidOperationException(
"The two length fields of the Phonetic Text don't agree! " +
length1 + " vs " + length2
);
}
phoneticText = StringUtil.ReadUnicodeLE(in1, length1);
int RunData = stringDataSize - 4 - 6 - (2 * phoneticText.Length);
int numRuns = (RunData / 6);
phRuns = new PhRun[numRuns];
for (int i = 0; i < phRuns.Length; i++)
{
phRuns[i] = new PhRun(in1);
}
int extraDataLength = RunData - (numRuns * 6);
if (extraDataLength < 0)
{
//System.err.Println("Warning - ExtRst overran by " + (0-extraDataLength) + " bytes");
extraDataLength = 0;
}
extraData = new byte[extraDataLength];
for (int i = 0; i < extraData.Length; i++)
{
extraData[i] = (byte)in1.ReadByte();
}
}
/**
* Returns our size, excluding our
* 4 byte header
*/
internal int DataSize
{
get
{
return 4 + 6 + (2 * phoneticText.Length) +
(6 * phRuns.Length) + extraData.Length;
}
}
internal void Serialize(ContinuableRecordOutput out1)
{
int dataSize = DataSize;
out1.WriteContinueIfRequired(8);
out1.WriteShort(reserved);
out1.WriteShort(dataSize);
out1.WriteShort(formattingFontIndex);
out1.WriteShort(formattingOptions);
out1.WriteContinueIfRequired(6);
out1.WriteShort(numberOfRuns);
out1.WriteShort(phoneticText.Length);
out1.WriteShort(phoneticText.Length);
out1.WriteContinueIfRequired(phoneticText.Length * 2);
StringUtil.PutUnicodeLE(phoneticText, out1);
for (int i = 0; i < phRuns.Length; i++)
{
phRuns[i].Serialize(out1);
}
out1.Write(extraData);
}
public override bool Equals(Object obj)
{
if (!(obj is ExtRst))
{
return false;
}
ExtRst other = (ExtRst)obj;
return (CompareTo(other) == 0);
}
public int CompareTo(ExtRst o)
{
int result;
result = reserved - o.reserved;
if (result != 0) return result;
result = formattingFontIndex - o.formattingFontIndex;
if (result != 0) return result;
result = formattingOptions - o.formattingOptions;
if (result != 0) return result;
result = numberOfRuns - o.numberOfRuns;
if (result != 0) return result;
//result = phoneticText.CompareTo(o.phoneticText);
result = string.Compare(phoneticText, o.phoneticText, StringComparison.CurrentCulture);
if (result != 0) return result;
result = phRuns.Length - o.phRuns.Length;
if (result != 0) return result;
for (int i = 0; i < phRuns.Length; i++)
{
result = phRuns[i].phoneticTextFirstCharacterOffset - o.phRuns[i].phoneticTextFirstCharacterOffset;
if (result != 0) return result;
result = phRuns[i].realTextFirstCharacterOffset - o.phRuns[i].realTextFirstCharacterOffset;
if (result != 0) return result;
result = phRuns[i].realTextFirstCharacterOffset - o.phRuns[i].realTextLength;
if (result != 0) return result;
}
result = extraData.Length - o.extraData.Length;
if (result != 0) return result;
// If we Get here, it's the same
return 0;
}
internal ExtRst Clone()
{
ExtRst ext = new ExtRst();
ext.reserved = reserved;
ext.formattingFontIndex = formattingFontIndex;
ext.formattingOptions = formattingOptions;
ext.numberOfRuns = numberOfRuns;
ext.phoneticText = phoneticText;
ext.phRuns = new PhRun[phRuns.Length];
for (int i = 0; i < ext.phRuns.Length; i++)
{
ext.phRuns[i] = new PhRun(
phRuns[i].phoneticTextFirstCharacterOffset,
phRuns[i].realTextFirstCharacterOffset,
phRuns[i].realTextLength
);
}
return ext;
}
public short FormattingFontIndex
{
get
{
return formattingFontIndex;
}
}
public short FormattingOptions
{
get
{
return formattingOptions;
}
}
public int NumberOfRuns
{
get
{
return numberOfRuns;
}
}
public String PhoneticText
{
get
{
return phoneticText;
}
}
public PhRun[] PhRuns
{
get
{
return phRuns;
}
}
}
internal class PhRun
{
internal int phoneticTextFirstCharacterOffset;
internal int realTextFirstCharacterOffset;
internal int realTextLength;
public PhRun(int phoneticTextFirstCharacterOffset,
int realTextFirstCharacterOffset, int realTextLength)
{
this.phoneticTextFirstCharacterOffset = phoneticTextFirstCharacterOffset;
this.realTextFirstCharacterOffset = realTextFirstCharacterOffset;
this.realTextLength = realTextLength;
}
internal PhRun(ILittleEndianInput in1)
{
phoneticTextFirstCharacterOffset = in1.ReadUShort();
realTextFirstCharacterOffset = in1.ReadUShort();
realTextLength = in1.ReadUShort();
}
internal void Serialize(ContinuableRecordOutput out1)
{
out1.WriteContinueIfRequired(6);
out1.WriteShort(phoneticTextFirstCharacterOffset);
out1.WriteShort(realTextFirstCharacterOffset);
out1.WriteShort(realTextLength);
}
}
private UnicodeString()
{
//Used for clone method.
}
public UnicodeString(String str)
{
String = (str);
}
public override int GetHashCode()
{
int stringHash = 0;
if (field_3_string != null)
stringHash = field_3_string.GetHashCode();
return field_1_charCount + stringHash;
}
/**
* Our handling of Equals is inconsistent with CompareTo. The trouble is because we don't truely understand
* rich text fields yet it's difficult to make a sound comparison.
*
* @param o The object to Compare.
* @return true if the object is actually Equal.
*/
public override bool Equals(Object o)
{
if (!(o is UnicodeString))
{
return false;
}
UnicodeString other = (UnicodeString)o;
//OK lets do this in stages to return a quickly, first check the actual string
bool eq = ((field_1_charCount == other.field_1_charCount)
&& (field_2_optionflags == other.field_2_optionflags)
&& field_3_string.Equals(other.field_3_string));
if (!eq) return false;
//OK string appears to be equal but now lets compare formatting Runs
if ((field_4_format_Runs == null) && (other.field_4_format_Runs == null))
//Strings are Equal, and there are not formatting Runs.
return true;
if (((field_4_format_Runs == null) && (other.field_4_format_Runs != null)) ||
(field_4_format_Runs != null) && (other.field_4_format_Runs == null))
//Strings are Equal, but one or the other has formatting Runs
return false;
//Strings are Equal, so now compare formatting Runs.
int size = field_4_format_Runs.Count;
if (size != other.field_4_format_Runs.Count)
return false;
for (int i = 0; i < size; i++)
{
FormatRun Run1 = field_4_format_Runs[(i)];
FormatRun run2 = other.field_4_format_Runs[(i)];
if (!Run1.Equals(run2))
return false;
}
// Well the format Runs are equal as well!, better check the ExtRst data
if (field_5_ext_rst == null && other.field_5_ext_rst == null)
{
// Good
}
else if (field_5_ext_rst != null && other.field_5_ext_rst != null)
{
int extCmp = field_5_ext_rst.CompareTo(other.field_5_ext_rst);
if (extCmp == 0)
{
// Good
}
else
{
return false;
}
}
else
{
return false;
}
//Phew!! After all of that we have finally worked out that the strings
//are identical.
return true;
}
/**
* construct a unicode string record and fill its fields, ID is ignored
* @param in the RecordInputstream to read the record from
*/
public UnicodeString(RecordInputStream in1)
{
field_1_charCount = in1.ReadShort();
field_2_optionflags = (byte)in1.ReadByte();
int RunCount = 0;
int extensionLength = 0;
//Read the number of rich Runs if rich text.
if (IsRichText)
{
RunCount = in1.ReadShort();
}
//Read the size of extended data if present.
if (IsExtendedText)
{
extensionLength = in1.ReadInt();
}
bool IsCompressed = ((field_2_optionflags & 1) == 0);
if (IsCompressed)
{
field_3_string = in1.ReadCompressedUnicode(CharCount);
}
else
{
field_3_string = in1.ReadUnicodeLEString(CharCount);
}
if (IsRichText && (RunCount > 0))
{
field_4_format_Runs = new List<FormatRun>(RunCount);
for (int i = 0; i < RunCount; i++)
{
field_4_format_Runs.Add(new FormatRun(in1));
}
}
if (IsExtendedText && (extensionLength > 0))
{
field_5_ext_rst = new ExtRst(new ContinuableRecordInput(in1), extensionLength);
if (field_5_ext_rst.DataSize + 4 != extensionLength)
{
_logger.Log(POILogger.WARN, "ExtRst was supposed to be " + extensionLength + " bytes long, but seems to actually be " + (field_5_ext_rst.DataSize + 4));
}
}
}
/**
* get the number of characters in the string,
* as an un-wrapped int
*
* @return number of characters
*/
public int CharCount
{
get
{
if (field_1_charCount < 0)
{
return field_1_charCount + 65536;
}
return field_1_charCount;
}
set
{
field_1_charCount = (short)value;
}
}
public short CharCountShort
{
get { return field_1_charCount; }
}
/**
* Get the option flags which among other things return if this is a 16-bit or
* 8 bit string
*
* @return optionflags bitmask
*
*/
public byte OptionFlags
{
get
{
return field_2_optionflags;
}
set
{
field_2_optionflags = value;
}
}
/**
* @return the actual string this Contains as a java String object
*/
public String String
{
get
{
return field_3_string;
}
set
{
field_3_string = value;
CharCount = ((short)field_3_string.Length);
// scan for characters greater than 255 ... if any are
// present, we have to use 16-bit encoding. Otherwise, we
// can use 8-bit encoding
bool useUTF16 = false;
int strlen = value.Length;
for (int j = 0; j < strlen; j++)
{
if (value[j] > 255)
{
useUTF16 = true;
break;
}
}
if (useUTF16)
//Set the uncompressed bit
field_2_optionflags = highByte.SetByte(field_2_optionflags);
else field_2_optionflags = highByte.ClearByte(field_2_optionflags);
}
}
public int FormatRunCount
{
get
{
if (field_4_format_Runs == null)
return 0;
return field_4_format_Runs.Count;
}
}
public FormatRun GetFormatRun(int index)
{
if (field_4_format_Runs == null)
{
return null;
}
if (index < 0 || index >= field_4_format_Runs.Count)
{
return null;
}
return field_4_format_Runs[(index)];
}
private int FindFormatRunAt(int characterPos)
{
int size = field_4_format_Runs.Count;
for (int i = 0; i < size; i++)
{
FormatRun r = field_4_format_Runs[(i)];
if (r._character == characterPos)
return i;
else if (r._character > characterPos)
return -1;
}
return -1;
}
/** Adds a font run to the formatted string.
*
* If a font run exists at the current charcter location, then it is
* Replaced with the font run to be Added.
*/
public void AddFormatRun(FormatRun r)
{
if (field_4_format_Runs == null)
{
field_4_format_Runs = new List<FormatRun>();
}
int index = FindFormatRunAt(r._character);
if (index != -1)
field_4_format_Runs.RemoveAt(index);
field_4_format_Runs.Add(r);
//Need to sort the font Runs to ensure that the font Runs appear in
//character order
//collections.Sort(field_4_format_Runs);
field_4_format_Runs.Sort();
//Make sure that we now say that we are a rich string
field_2_optionflags = richText.SetByte(field_2_optionflags);
}
public List<FormatRun> FormatIterator()
{
if (field_4_format_Runs != null)
{
return field_4_format_Runs;
}
return null;
}
public void RemoveFormatRun(FormatRun r)
{
field_4_format_Runs.Remove(r);
if (field_4_format_Runs.Count == 0)
{
field_4_format_Runs = null;
field_2_optionflags = richText.ClearByte(field_2_optionflags);
}
}
public void ClearFormatting()
{
field_4_format_Runs = null;
field_2_optionflags = richText.ClearByte(field_2_optionflags);
}
public ExtRst ExtendedRst
{
get
{
return this.field_5_ext_rst;
}
set
{
if (value != null)
{
field_2_optionflags = extBit.SetByte(field_2_optionflags);
}
else
{
field_2_optionflags = extBit.ClearByte(field_2_optionflags);
}
this.field_5_ext_rst = value;
}
}
/**
* Swaps all use in the string of one font index
* for use of a different font index.
* Normally only called when fonts have been
* Removed / re-ordered
*/
public void SwapFontUse(short oldFontIndex, short newFontIndex)
{
foreach (FormatRun run in field_4_format_Runs)
{
if (run._fontIndex == oldFontIndex)
{
run._fontIndex = newFontIndex;
}
}
}
/**
* unlike the real records we return the same as "getString()" rather than debug info
* @see #getDebugInfo()
* @return String value of the record
*/
public override String ToString()
{
return String;
}
/**
* return a character representation of the fields of this record
*
*
* @return String of output for biffviewer etc.
*
*/
public String GetDebugInfo()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("[UNICODESTRING]\n");
buffer.Append(" .charcount = ")
.Append(StringUtil.ToHexString(CharCount)).Append("\n");
buffer.Append(" .optionflags = ")
.Append(StringUtil.ToHexString(OptionFlags)).Append("\n");
buffer.Append(" .string = ").Append(String).Append("\n");
if (field_4_format_Runs != null)
{
for (int i = 0; i < field_4_format_Runs.Count; i++)
{
FormatRun r = field_4_format_Runs[(i)];
buffer.Append(" .format_Run" + i + " = ").Append(r.ToString()).Append("\n");
}
}
if (field_5_ext_rst != null)
{
buffer.Append(" .field_5_ext_rst = ").Append("\n");
buffer.Append(field_5_ext_rst.ToString()).Append("\n");
}
buffer.Append("[/UNICODESTRING]\n");
return buffer.ToString();
}
/**
* Serialises out the String. There are special rules
* about where we can and can't split onto
* Continue records.
*/
public void Serialize(ContinuableRecordOutput out1)
{
int numberOfRichTextRuns = 0;
int extendedDataSize = 0;
if (IsRichText && field_4_format_Runs != null)
{
numberOfRichTextRuns = field_4_format_Runs.Count;
}
if (IsExtendedText && field_5_ext_rst != null)
{
extendedDataSize = 4 + field_5_ext_rst.DataSize;
}
// Serialise the bulk of the String
// The WriteString handles tricky continue stuff for us
out1.WriteString(field_3_string, numberOfRichTextRuns, extendedDataSize);
if (numberOfRichTextRuns > 0)
{
//This will ensure that a run does not split a continue
for (int i = 0; i < numberOfRichTextRuns; i++)
{
if (out1.AvailableSpace < 4)
{
out1.WriteContinue();
}
FormatRun r = field_4_format_Runs[(i)];
r.Serialize(out1);
}
}
if (extendedDataSize > 0)
{
field_5_ext_rst.Serialize(out1);
}
}
public int CompareTo(UnicodeString str)
{
//int result = String.CompareTo(str.String);
int result = string.Compare(String, str.String, StringComparison.CurrentCulture);
//As per the Equals method lets do this in stages
if (result != 0)
return result;
//OK string appears to be equal but now lets compare formatting Runs
if ((field_4_format_Runs == null) && (str.field_4_format_Runs == null))
//Strings are Equal, and there are no formatting Runs.
return 0;
if ((field_4_format_Runs == null) && (str.field_4_format_Runs != null))
//Strings are Equal, but one or the other has formatting Runs
return 1;
if ((field_4_format_Runs != null) && (str.field_4_format_Runs == null))
//Strings are Equal, but one or the other has formatting Runs
return -1;
//Strings are Equal, so now compare formatting Runs.
int size = field_4_format_Runs.Count;
if (size != str.field_4_format_Runs.Count)
return size - str.field_4_format_Runs.Count;
for (int i = 0; i < size; i++)
{
FormatRun Run1 = field_4_format_Runs[(i)];
FormatRun run2 = str.field_4_format_Runs[(i)];
result = Run1.CompareTo(run2);
if (result != 0)
return result;
}
//Well the format Runs are equal as well!, better check the ExtRst data
if ((field_5_ext_rst == null) && (str.field_5_ext_rst == null))
return 0;
if ((field_5_ext_rst == null) && (str.field_5_ext_rst != null))
return 1;
if ((field_5_ext_rst != null) && (str.field_5_ext_rst == null))
return -1;
result = field_5_ext_rst.CompareTo(str.field_5_ext_rst);
if (result != 0)
return result;
//Phew!! After all of that we have finally worked out that the strings
//are identical.
return 0;
}
private bool IsRichText
{
get
{
return richText.IsSet(OptionFlags);
}
}
private bool IsExtendedText
{
get
{
return extBit.IsSet(OptionFlags);
}
}
public Object Clone()
{
UnicodeString str = new UnicodeString();
str.field_1_charCount = field_1_charCount;
str.field_2_optionflags = field_2_optionflags;
str.field_3_string = field_3_string;
if (field_4_format_Runs != null)
{
str.field_4_format_Runs = new List<FormatRun>();
foreach (FormatRun r in field_4_format_Runs)
{
str.field_4_format_Runs.Add(new FormatRun(r._character, r._fontIndex));
}
}
if (field_5_ext_rst != null)
{
str.field_5_ext_rst = field_5_ext_rst.Clone();
}
return str;
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using ASC.Api.Attributes;
using ASC.Api.Collections;
using ASC.Api.CRM.Wrappers;
using ASC.Api.Exceptions;
using ASC.Core;
using ASC.Core.Users;
using ASC.CRM.Core;
using ASC.CRM.Core.Entities;
using ASC.ElasticSearch;
using ASC.MessagingSystem;
using EnumExtension = ASC.Web.CRM.Classes.EnumExtension;
namespace ASC.Api.CRM
{
public partial class CRMApi
{
/// <summary>
/// Close the case with the ID specified in the request
/// </summary>
/// <short>Close case</short>
/// <category>Cases</category>
/// <param name="caseid" optional="false">Case ID</param>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ItemNotFoundException"></exception>
/// <returns>
/// Case
/// </returns>
[Update(@"case/{caseid:[0-9]+}/close")]
public CasesWrapper CloseCases(int caseid)
{
if (caseid <= 0) throw new ArgumentException();
var cases = DaoFactory.CasesDao.CloseCases(caseid);
if (cases == null) throw new ItemNotFoundException();
MessageService.Send(Request, MessageAction.CaseClosed, MessageTarget.Create(cases.ID), cases.Title);
return ToCasesWrapper(cases);
}
/// <summary>
/// Resume the case with the ID specified in the request
/// </summary>
/// <short>Resume case</short>
/// <category>Cases</category>
/// <param name="caseid" optional="false">Case ID</param>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ItemNotFoundException"></exception>
/// <returns>
/// Case
/// </returns>
[Update(@"case/{caseid:[0-9]+}/reopen")]
public CasesWrapper ReOpenCases(int caseid)
{
if (caseid <= 0) throw new ArgumentException();
var cases = DaoFactory.CasesDao.ReOpenCases(caseid);
if (cases == null) throw new ItemNotFoundException();
MessageService.Send(Request, MessageAction.CaseOpened, MessageTarget.Create(cases.ID), cases.Title);
return ToCasesWrapper(cases);
}
/// <summary>
/// Creates the case with the parameters specified in the request
/// </summary>
/// <short>Create case</short>
/// <param name="title" optional="false">Case title</param>
/// <param name="members" optional="true">Participants</param>
/// <param name="customFieldList" optional="true">User field list</param>
/// <param name="isPrivate" optional="true">Case privacy: private or not</param>
/// <param name="accessList" optional="true">List of users with access to the case</param>
/// <param name="isNotify" optional="true">Notify users in accessList about the case</param>
/// <returns>Case</returns>
/// <category>Cases</category>
/// <exception cref="ArgumentException"></exception>
/// <example>
/// <![CDATA[
///
/// Data transfer in application/json format:
///
/// data: {
/// title: "Exhibition organization",
/// isPrivate: false,
/// customFieldList: [{1: "value for text custom field with id = 1"}]
/// }
///
/// ]]>
/// </example>
[Create(@"case")]
public CasesWrapper CreateCases(
string title,
IEnumerable<int> members,
IEnumerable<ItemKeyValuePair<int, string>> customFieldList,
bool isPrivate,
IEnumerable<Guid> accessList,
bool isNotify)
{
if (string.IsNullOrEmpty(title)) throw new ArgumentException();
var casesID = DaoFactory.CasesDao.CreateCases(title);
var cases = new Cases
{
ID = casesID,
Title = title,
CreateBy = SecurityContext.CurrentAccount.ID,
CreateOn = DateTime.UtcNow
};
FactoryIndexer<Web.CRM.Core.Search.CasesWrapper>.IndexAsync(cases);
SetAccessToCases(cases, isPrivate, accessList, isNotify, false);
var membersList = members != null ? members.ToList() : new List<int>();
if (membersList.Any())
{
var contacts = DaoFactory.ContactDao.GetContacts(membersList.ToArray()).Where(CRMSecurity.CanAccessTo).ToList();
membersList = contacts.Select(m => m.ID).ToList();
DaoFactory.CasesDao.SetMembers(cases.ID, membersList.ToArray());
}
if (customFieldList != null)
{
var existingCustomFieldList = DaoFactory.CustomFieldDao.GetFieldsDescription(EntityType.Case).Select(fd => fd.ID).ToList();
foreach (var field in customFieldList)
{
if (string.IsNullOrEmpty(field.Value) || !existingCustomFieldList.Contains(field.Key)) continue;
DaoFactory.CustomFieldDao.SetFieldValue(EntityType.Case, cases.ID, field.Key, field.Value);
}
}
return ToCasesWrapper(DaoFactory.CasesDao.GetByID(casesID));
}
/// <summary>
/// Updates the selected case with the parameters specified in the request
/// </summary>
/// <short>Update case</short>
/// <param name="caseid" optional="false">Case ID</param>
/// <param name="title" optional="false">Case title</param>
/// <param name="members" optional="true">Participants</param>
/// <param name="customFieldList" optional="true">User field list</param>
/// <param name="isPrivate" optional="true">Case privacy: private or not</param>
/// <param name="accessList" optional="true">List of users with access to the case</param>
/// <param name="isNotify" optional="true">Notify users in accessList about the case</param>
/// <category>Cases</category>
/// <returns>Case</returns>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ItemNotFoundException"></exception>
/// <example>
/// <![CDATA[
///
/// Data transfer in application/json format:
///
/// data: {
/// caseid: 0,
/// title: "Exhibition organization",
/// isPrivate: false,
/// customFieldList: [{1: "value for text custom field with id = 1"}]
/// }
///
/// ]]>
/// </example>
[Update(@"case/{caseid:[0-9]+}")]
public CasesWrapper UpdateCases(
int caseid,
string title,
IEnumerable<int> members,
IEnumerable<ItemKeyValuePair<int, string>> customFieldList,
bool isPrivate,
IEnumerable<Guid> accessList,
bool isNotify)
{
if ((caseid <= 0) || (string.IsNullOrEmpty(title))) throw new ArgumentException();
var cases = DaoFactory.CasesDao.GetByID(caseid);
if (cases == null) throw new ItemNotFoundException();
cases.Title = title;
DaoFactory.CasesDao.UpdateCases(cases);
if (CRMSecurity.IsAdmin || cases.CreateBy == Core.SecurityContext.CurrentAccount.ID)
{
SetAccessToCases(cases, isPrivate, accessList, isNotify, false);
}
var membersList = members != null ? members.ToList() : new List<int>();
if (membersList.Any())
{
var contacts = DaoFactory.ContactDao.GetContacts(membersList.ToArray()).Where(CRMSecurity.CanAccessTo).ToList();
membersList = contacts.Select(m => m.ID).ToList();
DaoFactory.CasesDao.SetMembers(cases.ID, membersList.ToArray());
}
if (customFieldList != null)
{
var existingCustomFieldList = DaoFactory.CustomFieldDao.GetFieldsDescription(EntityType.Case).Select(fd => fd.ID).ToList();
foreach (var field in customFieldList)
{
if (string.IsNullOrEmpty(field.Value) || !existingCustomFieldList.Contains(field.Key)) continue;
DaoFactory.CustomFieldDao.SetFieldValue(EntityType.Case, cases.ID, field.Key, field.Value);
}
}
return ToCasesWrapper(cases);
}
/// <summary>
/// Sets access rights for the selected case with the parameters specified in the request
/// </summary>
/// <param name="caseid" optional="false">Case ID</param>
/// <param name="isPrivate" optional="false">Case privacy: private or not</param>
/// <param name="accessList" optional="false">List of users with access to the case</param>
/// <short>Set rights to case</short>
/// <category>Cases</category>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ItemNotFoundException"></exception>
/// <returns>
/// Case
/// </returns>
[Update(@"case/{caseid:[0-9]+}/access")]
public CasesWrapper SetAccessToCases(int caseid, bool isPrivate, IEnumerable<Guid> accessList)
{
if (caseid <= 0) throw new ArgumentException();
var cases = DaoFactory.CasesDao.GetByID(caseid);
if (cases == null) throw new ItemNotFoundException();
if (!(CRMSecurity.IsAdmin || cases.CreateBy == Core.SecurityContext.CurrentAccount.ID)) throw CRMSecurity.CreateSecurityException();
return SetAccessToCases(cases, isPrivate, accessList, false, true);
}
private CasesWrapper SetAccessToCases(Cases cases, bool isPrivate, IEnumerable<Guid> accessList, bool isNotify, bool isMessageServicSende)
{
var accessListLocal = accessList != null ? accessList.Distinct().ToList() : new List<Guid>();
if (isPrivate && accessListLocal.Any())
{
if (isNotify)
{
accessListLocal = accessListLocal.Where(u => u != SecurityContext.CurrentAccount.ID).ToList();
ASC.Web.CRM.Services.NotifyService.NotifyClient.Instance.SendAboutSetAccess(EntityType.Case, cases.ID, DaoFactory, accessListLocal.ToArray());
}
if (!accessListLocal.Contains(SecurityContext.CurrentAccount.ID))
{
accessListLocal.Add(SecurityContext.CurrentAccount.ID);
}
CRMSecurity.SetAccessTo(cases, accessListLocal);
if (isMessageServicSende)
{
var users = GetUsersByIdList(accessListLocal);
MessageService.Send(Request, MessageAction.CaseRestrictedAccess, MessageTarget.Create(cases.ID), cases.Title, users.Select(x => x.DisplayUserName(false)));
}
}
else
{
CRMSecurity.MakePublic(cases);
if (isMessageServicSende)
{
MessageService.Send(Request, MessageAction.CaseOpenedAccess, MessageTarget.Create(cases.ID), cases.Title);
}
}
return ToCasesWrapper(cases);
}
/// <summary>
/// Sets access rights for other users to the list of cases with the IDs specified in the request
/// </summary>
/// <param name="casesid">Case ID list</param>
/// <param name="isPrivate">Case privacy: private or not</param>
/// <param name="accessList">List of users with access</param>
/// <short>Set case access rights</short>
/// <category>Cases</category>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ItemNotFoundException"></exception>
/// <returns>
/// Case list
/// </returns>
[Update(@"case/access")]
public IEnumerable<CasesWrapper> SetAccessToBatchCases(IEnumerable<int> casesid, bool isPrivate, IEnumerable<Guid> accessList)
{
var result = new List<Cases>();
var cases = DaoFactory.CasesDao.GetCases(casesid);
if (!cases.Any()) return new List<CasesWrapper>();
foreach (var c in cases)
{
if (c == null) throw new ItemNotFoundException();
if (!(CRMSecurity.IsAdmin || c.CreateBy == Core.SecurityContext.CurrentAccount.ID)) continue;
SetAccessToCases(c, isPrivate, accessList, false, true);
result.Add(c);
}
return ToListCasesWrappers(result);
}
/// <summary>
/// Sets access rights for other users to the list of all cases matching the parameters specified in the request
/// </summary>
/// <param optional="true" name="contactid">Contact ID</param>
/// <param optional="true" name="isClosed">Case status</param>
/// <param optional="true" name="tags">Tags</param>
/// <param name="isPrivate">Case privacy: private or not</param>
/// <param name="accessList">List of users with access</param>
/// <short>Set case access rights</short>
/// <category>Cases</category>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ItemNotFoundException"></exception>
/// <returns>
/// Case list
/// </returns>
[Update(@"case/filter/access")]
public IEnumerable<CasesWrapper> SetAccessToBatchCases(
int contactid,
bool? isClosed,
IEnumerable<string> tags,
bool isPrivate,
IEnumerable<Guid> accessList
)
{
var result = new List<Cases>();
var caseses = DaoFactory.CasesDao.GetCases(_context.FilterValue, contactid, isClosed, tags, 0, 0, null);
if (!caseses.Any()) return new List<CasesWrapper>();
foreach (var casese in caseses)
{
if (casese == null) throw new ItemNotFoundException();
if (!(CRMSecurity.IsAdmin || casese.CreateBy == Core.SecurityContext.CurrentAccount.ID)) continue;
SetAccessToCases(casese, isPrivate, accessList, false, true);
result.Add(casese);
}
return ToListCasesWrappers(result);
}
/// <summary>
/// Returns the detailed information about the case with the ID specified in the request
/// </summary>
/// <short>Get case by ID</short>
/// <category>Cases</category>
/// <param name="caseid">Case ID</param>
///<exception cref="ArgumentException"></exception>
///<exception cref="ItemNotFoundException"></exception>
[Read(@"case/{caseid:[0-9]+}")]
public CasesWrapper GetCaseByID(int caseid)
{
if (caseid <= 0) throw new ItemNotFoundException();
var cases = DaoFactory.CasesDao.GetByID(caseid);
if (cases == null || !CRMSecurity.CanAccessTo(cases)) throw new ItemNotFoundException();
return ToCasesWrapper(cases);
}
/// <summary>
/// Returns the list of all cases matching the parameters specified in the request
/// </summary>
/// <short>Get case list</short>
/// <param optional="true" name="contactid">Contact ID</param>
/// <param optional="true" name="isClosed">Case status</param>
/// <param optional="true" name="tags">Tags</param>
/// <category>Cases</category>
/// <returns>
/// Case list
/// </returns>
[Read(@"case/filter")]
public IEnumerable<CasesWrapper> GetCases(int contactid, bool? isClosed, IEnumerable<string> tags)
{
IEnumerable<CasesWrapper> result;
SortedByType sortBy;
OrderBy casesOrderBy;
var searchString = _context.FilterValue;
if (EnumExtension.TryParse(_context.SortBy, true, out sortBy))
{
casesOrderBy = new OrderBy(sortBy, !_context.SortDescending);
}
else if (string.IsNullOrEmpty(_context.SortBy))
{
casesOrderBy = new OrderBy(SortedByType.Title, true);
}
else
{
casesOrderBy = null;
}
var fromIndex = (int)_context.StartIndex;
var count = (int)_context.Count;
if (casesOrderBy != null)
{
result = ToListCasesWrappers(
DaoFactory
.CasesDao
.GetCases(
searchString,
contactid,
isClosed,
tags,
fromIndex,
count,
casesOrderBy)).ToList();
_context.SetDataPaginated();
_context.SetDataFiltered();
_context.SetDataSorted();
}
else
{
result = ToListCasesWrappers(
DaoFactory
.CasesDao
.GetCases(
searchString, contactid, isClosed,
tags,
0,
0,
null)).ToList();
}
int totalCount;
if (result.Count() < count)
{
totalCount = fromIndex + result.Count();
}
else
{
totalCount = DaoFactory.CasesDao.GetCasesCount(searchString, contactid, isClosed, tags);
}
_context.SetTotalCount(totalCount);
return result.ToSmartList();
}
/// <summary>
/// Deletes the case with the ID specified in the request
/// </summary>
/// <short>Delete case</short>
/// <param name="caseid">Case ID</param>
/// <category>Cases</category>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ItemNotFoundException"></exception>
/// <returns>
/// Case
/// </returns>
[Delete(@"case/{caseid:[0-9]+}")]
public CasesWrapper DeleteCase(int caseid)
{
if (caseid <= 0) throw new ArgumentException();
var cases = DaoFactory.CasesDao.DeleteCases(caseid);
if (cases == null) throw new ItemNotFoundException();
FactoryIndexer<Web.CRM.Core.Search.CasesWrapper>.DeleteAsync(cases);
MessageService.Send(Request, MessageAction.CaseDeleted, MessageTarget.Create(cases.ID), cases.Title);
return ToCasesWrapper(cases);
}
/// <summary>
/// Deletes the group of cases with the IDs specified in the request
/// </summary>
/// <param name="casesids">Case ID list</param>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ItemNotFoundException"></exception>
/// <short>Delete case group</short>
/// <category>Cases</category>
/// <returns>
/// Case list
/// </returns>
[Update(@"case")]
public IEnumerable<CasesWrapper> DeleteBatchCases(IEnumerable<int> casesids)
{
if (casesids == null) throw new ArgumentException();
casesids = casesids.Distinct();
var caseses = DaoFactory.CasesDao.DeleteBatchCases(casesids.ToArray());
if (caseses == null || !caseses.Any()) return new List<CasesWrapper>();
MessageService.Send(Request, MessageAction.CasesDeleted, MessageTarget.Create(casesids), caseses.Select(c => c.Title));
return ToListCasesWrappers(caseses);
}
/// <summary>
/// Deletes the list of all cases matching the parameters specified in the request
/// </summary>
/// <param optional="true" name="contactid">Contact ID</param>
/// <param optional="true" name="isClosed">Case status</param>
/// <param optional="true" name="tags">Tags</param>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ItemNotFoundException"></exception>
/// <short>Delete case group</short>
/// <category>Cases</category>
/// <returns>
/// Case list
/// </returns>
[Delete(@"case/filter")]
public IEnumerable<CasesWrapper> DeleteBatchCases(int contactid, bool? isClosed, IEnumerable<string> tags)
{
var caseses = DaoFactory.CasesDao.GetCases(_context.FilterValue, contactid, isClosed, tags, 0, 0, null);
if (!caseses.Any()) return new List<CasesWrapper>();
caseses = DaoFactory.CasesDao.DeleteBatchCases(caseses);
MessageService.Send(Request, MessageAction.CasesDeleted, MessageTarget.Create(caseses.Select(c => c.ID)), caseses.Select(c => c.Title));
return ToListCasesWrappers(caseses);
}
/// <summary>
/// Returns the list of all contacts associated with the case with the ID specified in the request
/// </summary>
/// <short>Get all case contacts</short>
/// <param name="caseid">Case ID</param>
/// <category>Cases</category>
/// <returns>Contact list</returns>
///<exception cref="ArgumentException"></exception>
[Read(@"case/{caseid:[0-9]+}/contact")]
public IEnumerable<ContactWrapper> GetCasesMembers(int caseid)
{
var contactIDs = DaoFactory.CasesDao.GetMembers(caseid);
return contactIDs == null
? new ItemList<ContactWrapper>()
: ToListContactWrapper(DaoFactory.ContactDao.GetContacts(contactIDs));
}
/// <summary>
/// Adds the selected contact to the case with the ID specified in the request
/// </summary>
/// <short>Add case contact</short>
/// <category>Cases</category>
/// <param name="caseid">Case ID</param>
/// <param name="contactid">Contact ID</param>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ItemNotFoundException"></exception>
/// <returns>
/// Participant
/// </returns>
[Create(@"case/{caseid:[0-9]+}/contact")]
public ContactWrapper AddMemberToCases(int caseid, int contactid)
{
if ((caseid <= 0) || (contactid <= 0)) throw new ArgumentException();
var cases = DaoFactory.CasesDao.GetByID(caseid);
if (cases == null || !CRMSecurity.CanAccessTo(cases)) throw new ItemNotFoundException();
var contact = DaoFactory.ContactDao.GetByID(contactid);
if (contact == null || !CRMSecurity.CanAccessTo(contact)) throw new ItemNotFoundException();
DaoFactory.CasesDao.AddMember(caseid, contactid);
var messageAction = contact is Company ? MessageAction.CaseLinkedCompany : MessageAction.CaseLinkedPerson;
MessageService.Send(Request, messageAction, MessageTarget.Create(cases.ID), cases.Title, contact.GetTitle());
return ToContactWrapper(contact);
}
/// <summary>
/// Delete the selected contact from the case with the ID specified in the request
/// </summary>
/// <short>Delete case contact</short>
/// <category>Cases</category>
/// <param name="caseid">Case ID</param>
/// <param name="contactid">Contact ID</param>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ItemNotFoundException"></exception>
/// <returns>
/// Participant
/// </returns>
[Delete(@"case/{caseid:[0-9]+}/contact/{contactid:[0-9]+}")]
public ContactWrapper DeleteMemberFromCases(int caseid, int contactid)
{
if ((caseid <= 0) || (contactid <= 0)) throw new ArgumentException();
var cases = DaoFactory.CasesDao.GetByID(caseid);
if (cases == null || !CRMSecurity.CanAccessTo(cases)) throw new ItemNotFoundException();
var contact = DaoFactory.ContactDao.GetByID(contactid);
if (contact == null || !CRMSecurity.CanAccessTo(contact)) throw new ItemNotFoundException();
var result = ToContactWrapper(contact);
DaoFactory.CasesDao.RemoveMember(caseid, contactid);
var messageAction = contact is Company ? MessageAction.CaseUnlinkedCompany : MessageAction.CaseUnlinkedPerson;
MessageService.Send(Request, messageAction, MessageTarget.Create(cases.ID), cases.Title, contact.GetTitle());
return result;
}
/// <summary>
/// Returns the list of 30 cases in the CRM module with prefix
/// </summary>
/// <param optional="true" name="prefix"></param>
/// <param optional="true" name="contactID"></param>
/// <category>Cases</category>
/// <returns>
/// Cases list
/// </returns>
/// <visible>false</visible>
[Read(@"case/byprefix")]
public IEnumerable<CasesWrapper> GetCasesByPrefix(string prefix, int contactID)
{
var result = new List<CasesWrapper>();
if (contactID > 0)
{
var findedCases = DaoFactory.CasesDao.GetCases(string.Empty, contactID, null, null, 0, 0, null);
foreach (var item in findedCases)
{
if (item.Title.IndexOf(prefix, StringComparison.Ordinal) != -1)
{
result.Add(ToCasesWrapper(item));
}
}
_context.SetTotalCount(findedCases.Count);
}
else
{
const int maxItemCount = 30;
var findedCases = DaoFactory.CasesDao.GetCasesByPrefix(prefix, 0, maxItemCount);
foreach (var item in findedCases)
{
result.Add(ToCasesWrapper(item));
}
}
return result;
}
private IEnumerable<CasesWrapper> ToListCasesWrappers(ICollection<Cases> items)
{
if (items == null || items.Count == 0) return new List<CasesWrapper>();
var result = new List<CasesWrapper>();
var contactIDs = new List<int>();
var casesIDs = items.Select(item => item.ID).ToArray();
var customFields = DaoFactory.CustomFieldDao
.GetEntityFields(EntityType.Case, casesIDs)
.GroupBy(item => item.EntityID)
.ToDictionary(item => item.Key, item => item.Select(ToCustomFieldBaseWrapper));
var casesMembers = DaoFactory.CasesDao.GetMembers(casesIDs);
foreach (var value in casesMembers.Values)
{
contactIDs.AddRange(value);
}
var contacts = DaoFactory
.ContactDao
.GetContacts(contactIDs.Distinct().ToArray())
.ToDictionary(item => item.ID, ToContactBaseWrapper);
foreach (var cases in items)
{
var casesWrapper = new CasesWrapper(cases)
{
CustomFields = customFields.ContainsKey(cases.ID)
? customFields[cases.ID]
: new List<CustomFieldBaseWrapper>(),
Members = casesMembers.ContainsKey(cases.ID)
? casesMembers[cases.ID].Where(contacts.ContainsKey).Select(item => contacts[item])
: new List<ContactBaseWrapper>()
};
result.Add(casesWrapper);
}
return result;
}
private CasesWrapper ToCasesWrapper(Cases cases)
{
var casesWrapper = new CasesWrapper(cases)
{
CustomFields = DaoFactory
.CustomFieldDao
.GetEntityFields(EntityType.Case, cases.ID, false)
.ConvertAll(item => new CustomFieldBaseWrapper(item))
.ToSmartList(),
Members = new List<ContactBaseWrapper>()
};
var memberIDs = DaoFactory.CasesDao.GetMembers(cases.ID);
var membersList = DaoFactory.ContactDao.GetContacts(memberIDs);
var membersWrapperList = new List<ContactBaseWrapper>();
foreach (var member in membersList)
{
if (member == null) continue;
membersWrapperList.Add(ToContactBaseWrapper(member));
}
casesWrapper.Members = membersWrapperList;
return casesWrapper;
}
private IEnumerable<UserInfo> GetUsersByIdList(IEnumerable<Guid> ids)
{
return CoreContext.UserManager.GetUsers().Where(x => ids.Contains(x.ID));
}
}
}
| |
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Net;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NakedFramework.DependencyInjection.Extensions;
using NakedFramework.Persistor.EFCore.Extensions;
using NakedFramework.Rest.API;
using NakedFramework.Rest.Model;
using NakedFramework.Test.TestCase;
using NakedObjects.Reflector.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NOF2.Reflector.Extensions;
using NOF2.Rest.Test.Data;
using NOF2.Rest.Test.Data.AppLib;
using NUnit.Framework;
namespace NOF2.Rest.Test;
public class NOF2NOTest : AcceptanceTestCase {
protected Type[] NOF2Types { get; } = {
typeof(ClassWithTextString),
typeof(ClassWithInternalCollection),
typeof(ClassWithActionAbout),
typeof(ClassWithFieldAbout),
typeof(ClassWithLinkToNOFClass),
typeof(ClassWithNOFInternalCollection),
typeof(NOF2ClassWithInterface),
typeof(INOF2RoleInterface),
typeof(ClassWithMenu),
typeof(ClassWithDate),
typeof(ClassWithTimeStamp),
typeof(ClassWithWholeNumber),
typeof(ClassWithLogical),
typeof(ClassWithMoney),
typeof(ClassWithReferenceProperty)
};
protected Type[] NOF2Services { get; } = { typeof(SimpleService) };
protected Type[] NOF2ValueHolders { get; } = {
typeof(TextString),
typeof(Money),
typeof(Logical),
typeof(MultiLineTextString),
typeof(WholeNumber),
typeof(NODate),
typeof(TimeStamp)
};
protected override Type[] ObjectTypes { get; } = {
typeof(ClassWithString),
typeof(ClassWithNOF2Interface),
typeof(IRoleInterface)
};
protected override Type[] Services { get; } = { typeof(SimpleNOService) };
protected override bool EnforceProxies => false;
protected override Action<NakedFrameworkOptions> AddNakedFunctions => _ => { };
protected Action<NOF2Options> NOF2Options =>
options => {
options.DomainModelTypes = NOF2Types;
options.DomainModelServices = NOF2Services;
options.ValueHolderTypes = NOF2ValueHolders;
};
protected virtual Action<NakedFrameworkOptions> AddNOF2 => builder => builder.AddNOF2(NOF2Options);
protected override Action<NakedFrameworkOptions> NakedFrameworkOptions =>
builder => {
AddCoreOptions(builder);
AddPersistor(builder);
AddNakedObjects(builder);
//AddNakedFunctions(builder);
AddRestfulObjects(builder);
AddNOF2(builder);
};
protected new Func<IConfiguration, DbContext>[] ContextCreators => new Func<IConfiguration, DbContext>[] {
config => {
var context = new EFCoreObjectDbContext();
context.Create();
return context;
}
};
protected virtual Action<EFCorePersistorOptions> EFCorePersistorOptions =>
options => { options.ContextCreators = ContextCreators; };
protected override Action<NakedFrameworkOptions> AddPersistor => builder => { builder.AddEFCorePersistor(EFCorePersistorOptions); };
protected void CleanUpDatabase() {
new EFCoreObjectDbContext().Delete();
}
protected override void RegisterTypes(IServiceCollection services) {
base.RegisterTypes(services);
services.AddTransient<RestfulObjectsController, RestfulObjectsController>();
services.AddMvc(options => options.EnableEndpointRouting = false)
.AddNewtonsoftJson(options => options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc);
}
[SetUp]
public void SetUp() => StartTest();
[TearDown]
public void TearDown() => EndTest();
[OneTimeSetUp]
public void FixtureSetUp() {
ObjectReflectorConfiguration.NoValidate = true;
InitializeNakedObjectsFramework(this);
}
[OneTimeTearDown]
public void FixtureTearDown() {
CleanupNakedObjectsFramework(this);
CleanUpDatabase();
}
protected RestfulObjectsControllerBase Api() {
var sp = GetConfiguredContainer();
var api = sp.GetService<RestfulObjectsController>();
return Helpers.SetMockContext(api, sp);
}
private JObject GetObject(string type, string id) {
var api = Api().AsGet();
var result = api.GetObject(type, id);
var (json, sc, _) = Helpers.ReadActionResult(result, api.ControllerContext.HttpContext);
Assert.AreEqual((int)HttpStatusCode.OK, sc);
return JObject.Parse(json);
}
private static string FullName<T>() => typeof(T).FullName;
//[Test]
//public void TestInvokeUpdateAndPersistObjectWithInternalCollection() {
// var api = Api().AsPost();
// var map = new ArgumentMap { Map = new Dictionary<string, IValue> { { "newName", new ScalarValue("Bill") } } };
// var result = api.PostInvoke(FullName<ClassWithInternalCollection>(), "2", nameof(ClassWithInternalCollection.ActionUpdateTestCollection), map);
// var (json, sc, _) = Helpers.ReadActionResult(result, api.ControllerContext.HttpContext);
// Assert.AreEqual((int)HttpStatusCode.OK, sc);
// var parsedResult = JObject.Parse(json);
// var resultObj = parsedResult["result"];
// Assert.AreEqual("1", resultObj["members"]["TestCollection"]["size"].ToString());
// Assert.AreEqual("collection", resultObj["members"]["TestCollection"]["memberType"].ToString());
//}
//[Test]
//public void TestAboutCaching() {
// ClassWithActionAbout.AboutCount = 0;
// var api = Api();
// var result = api.GetObject(FullName<ClassWithActionAbout>(), "1");
// var (json, sc, _) = Helpers.ReadActionResult(result, api.ControllerContext.HttpContext);
// Assert.AreEqual((int)HttpStatusCode.OK, sc);
// var parsedResult = JObject.Parse(json);
// Assert.AreEqual(1, ((JContainer)parsedResult["members"]).Count);
// Assert.AreEqual(1, ClassWithActionAbout.AboutCount);
// //Assert.IsNotNull(parsedResult["members"]["Id"]);
//}
//[Test]
//public void TestNOFToNOF2() {
// var api = Api();
// var result = api.GetObject(FullName<ClassWithString>(), "1");
// var (json, sc, _) = Helpers.ReadActionResult(result, api.ControllerContext.HttpContext);
// Assert.AreEqual((int)HttpStatusCode.OK, sc);
// var parsedResult = JObject.Parse(json);
// Assert.AreEqual(4, ((JContainer)parsedResult["members"]).Count);
// Assert.IsNotNull(parsedResult["members"]["LinkToNOF2Class"]);
// Assert.IsNotNull(parsedResult["members"]["CollectionOfNOF2Class"]);
// Assert.AreEqual("Ted", parsedResult["members"]["LinkToNOF2Class"]["value"]["title"].ToString());
//}
[Test]
public void TestNOFToNOF2Collection() {
var api = Api();
var result = api.GetObject(FullName<ClassWithString>(), "2");
var (json, sc, _) = Helpers.ReadActionResult(result, api.ControllerContext.HttpContext);
Assert.AreEqual((int)HttpStatusCode.OK, sc);
var parsedResult = JObject.Parse(json);
Assert.AreEqual(4, ((JContainer)parsedResult["members"]).Count);
Assert.IsNotNull(parsedResult["members"]["LinkToNOF2Class"]);
Assert.IsNotNull(parsedResult["members"]["CollectionOfNOF2Class"]);
Assert.AreEqual("2", parsedResult["members"]["CollectionOfNOF2Class"]["size"].ToString());
}
//[Test]
//public void TestNOF2ToNOF() {
// var api = Api();
// var result = api.GetObject(FullName<ClassWithLinkToNOFClass>(), "1");
// var (json, sc, _) = Helpers.ReadActionResult(result, api.ControllerContext.HttpContext);
// Assert.AreEqual((int)HttpStatusCode.OK, sc);
// var parsedResult = JObject.Parse(json);
// Assert.AreEqual(1, ((JContainer)parsedResult["members"]).Count);
// Assert.IsNotNull(parsedResult["members"]["LinkToNOFClass"]);
// Assert.AreEqual("Untitled Class With String", parsedResult["members"]["LinkToNOFClass"]["value"]["title"].ToString());
//}
[Test]
public void TestNOF2ToNOFCollection() {
var api = Api();
var result = api.GetObject(FullName<ClassWithNOFInternalCollection>(), "1");
var (json, sc, _) = Helpers.ReadActionResult(result, api.ControllerContext.HttpContext);
Assert.AreEqual((int)HttpStatusCode.OK, sc);
var parsedResult = JObject.Parse(json);
Assert.AreEqual(1, ((JContainer)parsedResult["members"]).Count);
Assert.IsNotNull(parsedResult["members"]["CollectionOfNOFClass"]);
Assert.AreEqual("2", parsedResult["members"]["CollectionOfNOFClass"]["size"].ToString());
}
[Test]
public void TestGetObjectWithNOF2Interface() {
ClassWithFieldAbout.TestInvisibleFlag = false;
var api = Api();
var result = api.GetObject(FullName<ClassWithNOF2Interface>(), "10");
var (json, sc, _) = Helpers.ReadActionResult(result, api.ControllerContext.HttpContext);
Assert.AreEqual((int)HttpStatusCode.OK, sc);
var parsedResult = JObject.Parse(json);
Assert.AreEqual(1, ((JContainer)parsedResult["members"]).Count);
Assert.IsNotNull(parsedResult["members"]["Id"]);
}
[Test]
public void TestGetObjectWithNOF2InterfaceConfirmSubtype() {
ClassWithFieldAbout.TestInvisibleFlag = false;
var map = new ArgumentMap { Map = new Dictionary<string, IValue> { { "supertype", new ScalarValue(FullName<INOF2RoleInterface>()) } } };
var api = Api();
var result = api.GetInvokeTypeActions(FullName<ClassWithNOF2Interface>(), "isSubtypeOf", map);
var (json, sc, _) = Helpers.ReadActionResult(result, api.ControllerContext.HttpContext);
Assert.AreEqual((int)HttpStatusCode.OK, sc);
var parsedResult = JObject.Parse(json);
Assert.AreEqual("True", parsedResult["value"].ToString());
}
[Test]
public void TestGetNOF2ObjectWithInterface() {
ClassWithFieldAbout.TestInvisibleFlag = false;
var api = Api();
var result = api.GetObject(FullName<NOF2ClassWithInterface>(), "10");
var (json, sc, _) = Helpers.ReadActionResult(result, api.ControllerContext.HttpContext);
Assert.AreEqual((int)HttpStatusCode.OK, sc);
var parsedResult = JObject.Parse(json);
Assert.AreEqual(1, ((JContainer)parsedResult["members"]).Count);
Assert.IsNull(parsedResult["members"]["Id"]);
}
[Test]
public void TestGetNOF2ObjectWithContributedAction() {
ClassWithFieldAbout.TestInvisibleFlag = false;
var api = Api();
var result = api.GetObject(FullName<NOF2ClassWithInterface>(), "10");
var (json, sc, _) = Helpers.ReadActionResult(result, api.ControllerContext.HttpContext);
Assert.AreEqual((int)HttpStatusCode.OK, sc);
var parsedResult = JObject.Parse(json);
Assert.AreEqual(1, ((JContainer)parsedResult["members"]).Count);
Assert.IsNotNull(parsedResult["members"]["ContributedAction"]);
}
[Test]
public void TestGetNOF2ObjectWithInterfaceConfirmSubtype() {
ClassWithFieldAbout.TestInvisibleFlag = false;
var map = new ArgumentMap { Map = new Dictionary<string, IValue> { { "supertype", new ScalarValue(FullName<IRoleInterface>()) } } };
var api = Api();
var result = api.GetInvokeTypeActions(FullName<NOF2ClassWithInterface>(), "isSubtypeOf", map);
var (json, sc, _) = Helpers.ReadActionResult(result, api.ControllerContext.HttpContext);
Assert.AreEqual((int)HttpStatusCode.OK, sc);
var parsedResult = JObject.Parse(json);
Assert.AreEqual("True", parsedResult["value"].ToString());
}
}
| |
/*
* Debug.cs - Implementation of the
* "System.Diagnostics.Debug" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#define DEBUG
#define TRACE
namespace System.Diagnostics
{
#if !ECMA_COMPAT
public sealed class Debug
{
// This class cannot be instantiated.
private Debug() {}
// Global trace properties.
public static bool AutoFlush
{
get
{
return Trace.AutoFlush;
}
set
{
Trace.AutoFlush = value;
}
}
public static int IndentLevel
{
get
{
return Trace.IndentLevel;
}
set
{
Trace.IndentLevel = value;
}
}
public static int IndentSize
{
get
{
return Trace.IndentSize;
}
set
{
Trace.IndentSize = value;
}
}
public static TraceListenerCollection Listeners
{
get
{
return Trace.Listeners;
}
}
// Assert on a particular condition.
[Conditional("DEBUG")]
public static void Assert(bool condition)
{
Trace.Assert(condition);
}
[Conditional("DEBUG")]
public static void Assert(bool condition, String message)
{
Trace.Assert(condition, message);
}
[Conditional("DEBUG")]
public static void Assert(bool condition, String message,
String detailMessage)
{
Trace.Assert(condition, message, detailMessage);
}
// Flush and close all listeners.
[Conditional("DEBUG")]
public static void Close()
{
Trace.Close();
}
// Record that some condition has failed.
[Conditional("DEBUG")]
public static void Fail(String message)
{
Trace.Fail(message);
}
[Conditional("DEBUG")]
public static void Fail(String message, String detailMessage)
{
Trace.Fail(message, detailMessage);
}
// Flush all trace listeners.
[Conditional("DEBUG")]
public static void Flush()
{
Trace.Flush();
}
// Increase the indent level by one.
[Conditional("DEBUG")]
public static void Indent()
{
Trace.Indent();
}
// Decrease the indent level by one.
[Conditional("DEBUG")]
public static void Unindent()
{
Trace.Unindent();
}
// Write a message to all trace listeners.
[Conditional("DEBUG")]
public static void Write(Object value)
{
Trace.Write(value);
}
[Conditional("DEBUG")]
public static void Write(String message)
{
Trace.Write(message);
}
[Conditional("DEBUG")]
public static void Write(Object value, String category)
{
Trace.Write(value, category);
}
[Conditional("DEBUG")]
public static void Write(String message, String category)
{
Trace.Write(message, category);
}
// Write a message to all trace listeners if a condition is true.
[Conditional("DEBUG")]
public static void WriteIf(bool condition, Object value)
{
Trace.WriteIf(condition, value);
}
[Conditional("DEBUG")]
public static void WriteIf(bool condition, String message)
{
Trace.WriteIf(condition, message);
}
[Conditional("DEBUG")]
public static void WriteIf(bool condition, Object value, String category)
{
Trace.WriteIf(condition, value, category);
}
[Conditional("DEBUG")]
public static void WriteIf(bool condition, String message, String category)
{
Trace.WriteIf(condition, message, category);
}
// Write a message to all trace listeners.
[Conditional("DEBUG")]
public static void WriteLine(Object value)
{
Trace.WriteLine(value);
}
[Conditional("DEBUG")]
public static void WriteLine(String message)
{
Trace.WriteLine(message);
}
[Conditional("DEBUG")]
public static void WriteLine(Object value, String category)
{
Trace.WriteLine(value, category);
}
[Conditional("DEBUG")]
public static void WriteLine(String message, String category)
{
Trace.WriteLine(message, category);
}
// Write a message to all trace listeners if a condition is true.
[Conditional("DEBUG")]
public static void WriteLineIf(bool condition, Object value)
{
Trace.WriteLineIf(condition, value);
}
[Conditional("DEBUG")]
public static void WriteLineIf(bool condition, String message)
{
Trace.WriteLineIf(condition, message);
}
[Conditional("DEBUG")]
public static void WriteLineIf
(bool condition, Object value, String category)
{
Trace.WriteLineIf(condition, value, category);
}
[Conditional("DEBUG")]
public static void WriteLineIf
(bool condition, String message, String category)
{
Trace.WriteLineIf(condition, message, category);
}
}; // class Debug
#endif // !ECMA_COMPAT
}; // namespace System.Diagnostics
| |
using System;
using System.Data;
using System.Data.OleDb;
using PCSComUtils.Common;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
namespace PCSComMaterials.Inventory.DS
{
public class IV_StockTakingDifferentDS
{
public IV_StockTakingDifferentDS()
{
}
private const string THIS = "PCSComMaterials.Inventory.DS.DS.IV_StockTakingDifferentDS";
//**************************************************************************
/// <Description>
/// This method uses to add data to IV_StockTakingDifferent
/// </Description>
/// <Inputs>
/// IV_StockTakingDifferentVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// Code generate
/// </Authors>
/// <History>
/// Tuesday, December 26, 2006
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
IV_StockTakingDifferentVO objObject = (IV_StockTakingDifferentVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql = "INSERT INTO IV_StockTakingDifferent("
+ IV_StockTakingDifferentTable.STOCKTAKINGDATE_FLD + ","
+ IV_StockTakingDifferentTable.OHQUANTITY_FLD + ","
+ IV_StockTakingDifferentTable.ACTUALQUANTITY_FLD + ","
+ IV_StockTakingDifferentTable.DIFFERENTQUANTITY_FLD + ","
+ IV_StockTakingDifferentTable.STOCKTAKINGPERIODID_FLD + ","
+ IV_StockTakingDifferentTable.PRODUCTID_FLD + ","
+ IV_StockTakingDifferentTable.LOCATIONID_FLD + ","
+ IV_StockTakingDifferentTable.BINID_FLD + ")"
+ "VALUES(?,?,?,?,?,?,?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(IV_StockTakingDifferentTable.STOCKTAKINGDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[IV_StockTakingDifferentTable.STOCKTAKINGDATE_FLD].Value = objObject.StockTakingDate;
ocmdPCS.Parameters.Add(new OleDbParameter(IV_StockTakingDifferentTable.OHQUANTITY_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[IV_StockTakingDifferentTable.OHQUANTITY_FLD].Value = objObject.OHQuantity;
ocmdPCS.Parameters.Add(new OleDbParameter(IV_StockTakingDifferentTable.ACTUALQUANTITY_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[IV_StockTakingDifferentTable.ACTUALQUANTITY_FLD].Value = objObject.ActualQuantity;
ocmdPCS.Parameters.Add(new OleDbParameter(IV_StockTakingDifferentTable.DIFFERENTQUANTITY_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[IV_StockTakingDifferentTable.DIFFERENTQUANTITY_FLD].Value = objObject.DifferentQuantity;
ocmdPCS.Parameters.Add(new OleDbParameter(IV_StockTakingDifferentTable.STOCKTAKINGPERIODID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[IV_StockTakingDifferentTable.STOCKTAKINGPERIODID_FLD].Value = objObject.StockTakingPeriodID;
ocmdPCS.Parameters.Add(new OleDbParameter(IV_StockTakingDifferentTable.PRODUCTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[IV_StockTakingDifferentTable.PRODUCTID_FLD].Value = objObject.ProductID;
ocmdPCS.Parameters.Add(new OleDbParameter(IV_StockTakingDifferentTable.LOCATIONID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[IV_StockTakingDifferentTable.LOCATIONID_FLD].Value = objObject.LocationID;
ocmdPCS.Parameters.Add(new OleDbParameter(IV_StockTakingDifferentTable.BINID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[IV_StockTakingDifferentTable.BINID_FLD].Value = objObject.BinID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from IV_StockTakingDifferent
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// Code generate
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql = "DELETE " + IV_StockTakingDifferentTable.TABLE_NAME + " WHERE " + "StockTakingDifferentID" + "=" + pintID.ToString();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from IV_StockTakingDifferent
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// IV_StockTakingDifferentVO
/// </Outputs>
/// <Returns>
/// IV_StockTakingDifferentVO
/// </Returns>
/// <Authors>
/// Code Generate
/// </Authors>
/// <History>
/// Tuesday, December 26, 2006
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT "
+ IV_StockTakingDifferentTable.STOCKTAKINGDIFFERENTID_FLD + ","
+ IV_StockTakingDifferentTable.STOCKTAKINGDATE_FLD + ","
+ IV_StockTakingDifferentTable.OHQUANTITY_FLD + ","
+ IV_StockTakingDifferentTable.ACTUALQUANTITY_FLD + ","
+ IV_StockTakingDifferentTable.DIFFERENTQUANTITY_FLD + ","
+ IV_StockTakingDifferentTable.STOCKTAKINGPERIODID_FLD + ","
+ IV_StockTakingDifferentTable.PRODUCTID_FLD + ","
+ IV_StockTakingDifferentTable.LOCATIONID_FLD + ","
+ IV_StockTakingDifferentTable.BINID_FLD
+ " FROM " + IV_StockTakingDifferentTable.TABLE_NAME
+ " WHERE " + IV_StockTakingDifferentTable.STOCKTAKINGDIFFERENTID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
IV_StockTakingDifferentVO objObject = new IV_StockTakingDifferentVO();
while (odrPCS.Read())
{
objObject.StockTakingDifferentID = int.Parse(odrPCS[IV_StockTakingDifferentTable.STOCKTAKINGDIFFERENTID_FLD].ToString());
objObject.StockTakingDate = DateTime.Parse(odrPCS[IV_StockTakingDifferentTable.STOCKTAKINGDATE_FLD].ToString());
objObject.OHQuantity = Decimal.Parse(odrPCS[IV_StockTakingDifferentTable.OHQUANTITY_FLD].ToString());
objObject.ActualQuantity = Decimal.Parse(odrPCS[IV_StockTakingDifferentTable.ACTUALQUANTITY_FLD].ToString());
objObject.DifferentQuantity = Decimal.Parse(odrPCS[IV_StockTakingDifferentTable.DIFFERENTQUANTITY_FLD].ToString());
objObject.StockTakingPeriodID = int.Parse(odrPCS[IV_StockTakingDifferentTable.STOCKTAKINGPERIODID_FLD].ToString());
objObject.ProductID = int.Parse(odrPCS[IV_StockTakingDifferentTable.PRODUCTID_FLD].ToString());
objObject.LocationID = int.Parse(odrPCS[IV_StockTakingDifferentTable.LOCATIONID_FLD].ToString());
objObject.BinID = int.Parse(odrPCS[IV_StockTakingDifferentTable.BINID_FLD].ToString());
}
return objObject;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to IV_StockTakingDifferent
/// </Description>
/// <Inputs>
/// IV_StockTakingDifferentVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// Code Generate
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
IV_StockTakingDifferentVO objObject = (IV_StockTakingDifferentVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql = "UPDATE IV_StockTakingDifferent SET "
+ IV_StockTakingDifferentTable.STOCKTAKINGDATE_FLD + "= ?" + ","
+ IV_StockTakingDifferentTable.OHQUANTITY_FLD + "= ?" + ","
+ IV_StockTakingDifferentTable.ACTUALQUANTITY_FLD + "= ?" + ","
+ IV_StockTakingDifferentTable.DIFFERENTQUANTITY_FLD + "= ?" + ","
+ IV_StockTakingDifferentTable.STOCKTAKINGPERIODID_FLD + "= ?" + ","
+ IV_StockTakingDifferentTable.PRODUCTID_FLD + "= ?" + ","
+ IV_StockTakingDifferentTable.LOCATIONID_FLD + "= ?" + ","
+ IV_StockTakingDifferentTable.BINID_FLD + "= ?"
+ " WHERE " + IV_StockTakingDifferentTable.STOCKTAKINGDIFFERENTID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(IV_StockTakingDifferentTable.STOCKTAKINGDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[IV_StockTakingDifferentTable.STOCKTAKINGDATE_FLD].Value = objObject.StockTakingDate;
ocmdPCS.Parameters.Add(new OleDbParameter(IV_StockTakingDifferentTable.OHQUANTITY_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[IV_StockTakingDifferentTable.OHQUANTITY_FLD].Value = objObject.OHQuantity;
ocmdPCS.Parameters.Add(new OleDbParameter(IV_StockTakingDifferentTable.ACTUALQUANTITY_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[IV_StockTakingDifferentTable.ACTUALQUANTITY_FLD].Value = objObject.ActualQuantity;
ocmdPCS.Parameters.Add(new OleDbParameter(IV_StockTakingDifferentTable.DIFFERENTQUANTITY_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[IV_StockTakingDifferentTable.DIFFERENTQUANTITY_FLD].Value = objObject.DifferentQuantity;
ocmdPCS.Parameters.Add(new OleDbParameter(IV_StockTakingDifferentTable.STOCKTAKINGPERIODID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[IV_StockTakingDifferentTable.STOCKTAKINGPERIODID_FLD].Value = objObject.StockTakingPeriodID;
ocmdPCS.Parameters.Add(new OleDbParameter(IV_StockTakingDifferentTable.PRODUCTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[IV_StockTakingDifferentTable.PRODUCTID_FLD].Value = objObject.ProductID;
ocmdPCS.Parameters.Add(new OleDbParameter(IV_StockTakingDifferentTable.LOCATIONID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[IV_StockTakingDifferentTable.LOCATIONID_FLD].Value = objObject.LocationID;
ocmdPCS.Parameters.Add(new OleDbParameter(IV_StockTakingDifferentTable.BINID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[IV_StockTakingDifferentTable.BINID_FLD].Value = objObject.BinID;
ocmdPCS.Parameters.Add(new OleDbParameter(IV_StockTakingDifferentTable.STOCKTAKINGDIFFERENTID_FLD, OleDbType.BigInt));
ocmdPCS.Parameters[IV_StockTakingDifferentTable.STOCKTAKINGDIFFERENTID_FLD].Value = objObject.StockTakingDifferentID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from IV_StockTakingDifferent
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// Code Generate
/// </Authors>
/// <History>
/// Tuesday, December 26, 2006
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT "
+ IV_StockTakingDifferentTable.STOCKTAKINGDIFFERENTID_FLD + ","
+ IV_StockTakingDifferentTable.STOCKTAKINGDATE_FLD + ","
+ IV_StockTakingDifferentTable.OHQUANTITY_FLD + ","
+ IV_StockTakingDifferentTable.ACTUALQUANTITY_FLD + ","
+ IV_StockTakingDifferentTable.DIFFERENTQUANTITY_FLD + ","
+ IV_StockTakingDifferentTable.STOCKTAKINGPERIODID_FLD + ","
+ IV_StockTakingDifferentTable.PRODUCTID_FLD + ","
+ IV_StockTakingDifferentTable.LOCATIONID_FLD + ","
+ IV_StockTakingDifferentTable.BINID_FLD
+ " FROM " + IV_StockTakingDifferentTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, IV_StockTakingDifferentTable.TABLE_NAME);
return dstPCS;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public DataTable List(int pintPeriodID)
{
const string METHOD_NAME = THIS + ".List()";
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT "
+ IV_StockTakingDifferentTable.STOCKTAKINGDIFFERENTID_FLD + ","
+ IV_StockTakingDifferentTable.STOCKTAKINGDATE_FLD + ","
+ IV_StockTakingDifferentTable.OHQUANTITY_FLD + ","
+ IV_StockTakingDifferentTable.ACTUALQUANTITY_FLD + ","
+ IV_StockTakingDifferentTable.DIFFERENTQUANTITY_FLD + ","
+ IV_StockTakingDifferentTable.HISTORYQUANTITY_FLD + ","
+ IV_StockTakingDifferentTable.STOCKTAKINGPERIODID_FLD + ","
+ IV_StockTakingDifferentTable.PRODUCTID_FLD + ","
+ IV_StockTakingDifferentTable.LOCATIONID_FLD + ","
+ IV_StockTakingDifferentTable.BINID_FLD
+ " FROM " + IV_StockTakingDifferentTable.TABLE_NAME
+ " WHERE " + IV_StockTakingDifferentTable.STOCKTAKINGPERIODID_FLD + "=" + pintPeriodID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
DataTable dtbData = new DataTable(IV_StockTakingDifferentTable.TABLE_NAME);
odadPCS.Fill(dtbData);
return dtbData;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// Code Generate
/// </Authors>
/// <History>
/// Tuesday, December 26, 2006
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS = null;
OleDbCommandBuilder odcbPCS;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql = "SELECT "
+ IV_StockTakingDifferentTable.STOCKTAKINGDIFFERENTID_FLD + ","
+ IV_StockTakingDifferentTable.STOCKTAKINGDATE_FLD + ","
+ IV_StockTakingDifferentTable.OHQUANTITY_FLD + ","
+ IV_StockTakingDifferentTable.ACTUALQUANTITY_FLD + ","
+ IV_StockTakingDifferentTable.DIFFERENTQUANTITY_FLD + ","
+ IV_StockTakingDifferentTable.HISTORYQUANTITY_FLD + ","
+ IV_StockTakingDifferentTable.STOCKTAKINGPERIODID_FLD + ","
+ IV_StockTakingDifferentTable.PRODUCTID_FLD + ","
+ IV_StockTakingDifferentTable.LOCATIONID_FLD + ","
+ IV_StockTakingDifferentTable.BINID_FLD
+ " FROM " + IV_StockTakingDifferentTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData, IV_StockTakingDifferentTable.TABLE_NAME);
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.