context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text.Encodings.Web; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using OpenIddict.Core; using OrchardCore.OpenId.Abstractions.Descriptors; using OrchardCore.OpenId.Abstractions.Managers; using OrchardCore.OpenId.Abstractions.Stores; namespace OrchardCore.OpenId.Services.Managers { public class OpenIdApplicationManager<TApplication> : OpenIddictApplicationManager<TApplication>, IOpenIdApplicationManager where TApplication : class { public OpenIdApplicationManager( IOpenIddictApplicationCache<TApplication> cache, ILogger<OpenIdApplicationManager<TApplication>> logger, IOptionsMonitor<OpenIddictCoreOptions> options, IOpenIddictApplicationStoreResolver resolver) : base(cache, logger, options, resolver) { } /// <summary> /// Retrieves an application using its physical identifier. /// </summary> /// <param name="identifier">The unique identifier associated with the application.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <returns> /// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation, /// whose result returns the client application corresponding to the identifier. /// </returns> public virtual ValueTask<TApplication> FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(identifier)) { throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } return Store is IOpenIdApplicationStore<TApplication> store ? store.FindByPhysicalIdAsync(identifier, cancellationToken) : Store.FindByIdAsync(identifier, cancellationToken); } /// <summary> /// Retrieves the physical identifier associated with an application. /// </summary> /// <param name="application">The application.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <returns> /// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation, /// whose result returns the physical identifier associated with the application. /// </returns> public virtual ValueTask<string> GetPhysicalIdAsync(TApplication application, CancellationToken cancellationToken = default) { if (application == null) { throw new ArgumentNullException(nameof(application)); } return Store is IOpenIdApplicationStore<TApplication> store ? store.GetPhysicalIdAsync(application, cancellationToken) : Store.GetIdAsync(application, cancellationToken); } public virtual async ValueTask<ImmutableArray<string>> GetRolesAsync( TApplication application, CancellationToken cancellationToken = default) { if (application == null) { throw new ArgumentNullException(nameof(application)); } if (Store is IOpenIdApplicationStore<TApplication> store) { return await store.GetRolesAsync(application, cancellationToken); } else { var properties = await Store.GetPropertiesAsync(application, cancellationToken); if (properties.TryGetValue(OpenIdConstants.Properties.Roles, out JsonElement value)) { var builder = ImmutableArray.CreateBuilder<string>(); foreach (var item in value.EnumerateArray()) { builder.Add(item.GetString()); } return builder.ToImmutable(); } return ImmutableArray.Create<string>(); } } public virtual IAsyncEnumerable<TApplication> ListInRoleAsync( string role, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(role)) { throw new ArgumentException("The role name cannot be null or empty.", nameof(role)); } if (Store is IOpenIdApplicationStore<TApplication> store) { return store.ListInRoleAsync(role, cancellationToken); } return ExecuteAsync(); async IAsyncEnumerable<TApplication> ExecuteAsync() { for (var offset = 0; ; offset += 1_000) { await foreach (var application in Store.ListAsync(1_000, offset, cancellationToken)) { var roles = await GetRolesAsync(application, cancellationToken); if (roles.Contains(role, StringComparer.OrdinalIgnoreCase)) { yield return application; } } } } } public virtual async ValueTask SetRolesAsync(TApplication application, ImmutableArray<string> roles, CancellationToken cancellationToken = default) { if (application == null) { throw new ArgumentNullException(nameof(application)); } if (roles.Any(role => string.IsNullOrEmpty(role))) { throw new ArgumentException("Role names cannot be null or empty.", nameof(roles)); } if (Store is IOpenIdApplicationStore<TApplication> store) { await store.SetRolesAsync(application, roles, cancellationToken); } else { var properties = await Store.GetPropertiesAsync(application, cancellationToken); properties = properties.SetItem(OpenIdConstants.Properties.Roles, JsonSerializer.Deserialize<JsonElement>( JsonSerializer.Serialize(roles, new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }))); await Store.SetPropertiesAsync(application, properties, cancellationToken); } await UpdateAsync(application, cancellationToken); } public override async ValueTask PopulateAsync(TApplication application, OpenIddictApplicationDescriptor descriptor, CancellationToken cancellationToken = default) { if (application == null) { throw new ArgumentNullException(nameof(application)); } if (descriptor == null) { throw new ArgumentNullException(nameof(descriptor)); } if (descriptor is OpenIdApplicationDescriptor model) { if (Store is IOpenIdApplicationStore<TApplication> store) { await store.SetRolesAsync(application, model.Roles.ToImmutableArray(), cancellationToken); } else { var properties = await Store.GetPropertiesAsync(application, cancellationToken); properties = properties.SetItem(OpenIdConstants.Properties.Roles, JsonSerializer.Deserialize<JsonElement>( JsonSerializer.Serialize(model.Roles, new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }))); await Store.SetPropertiesAsync(application, properties, cancellationToken); } } await base.PopulateAsync(application, descriptor, cancellationToken); } public override async ValueTask PopulateAsync(OpenIddictApplicationDescriptor descriptor, TApplication application, CancellationToken cancellationToken = default) { if (descriptor == null) { throw new ArgumentNullException(nameof(descriptor)); } if (application == null) { throw new ArgumentNullException(nameof(application)); } if (descriptor is OpenIdApplicationDescriptor model) { model.Roles.UnionWith(await GetRolesAsync(application, cancellationToken)); } await base.PopulateAsync(descriptor, application, cancellationToken); } public override IAsyncEnumerable<ValidationResult> ValidateAsync( TApplication application, CancellationToken cancellationToken = default) { if (application == null) { throw new ArgumentNullException(nameof(application)); } return ExecuteAsync(); async IAsyncEnumerable<ValidationResult> ExecuteAsync() { await foreach (var result in base.ValidateAsync(application, cancellationToken)) { yield return result; } foreach (var role in await GetRolesAsync(application, cancellationToken)) { if (string.IsNullOrEmpty(role)) { yield return new ValidationResult("Roles cannot be null or empty."); break; } } } } async ValueTask<object> IOpenIdApplicationManager.FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken) => await FindByPhysicalIdAsync(identifier, cancellationToken); ValueTask<string> IOpenIdApplicationManager.GetPhysicalIdAsync(object application, CancellationToken cancellationToken) => GetPhysicalIdAsync((TApplication)application, cancellationToken); ValueTask<ImmutableArray<string>> IOpenIdApplicationManager.GetRolesAsync(object application, CancellationToken cancellationToken) => GetRolesAsync((TApplication)application, cancellationToken); IAsyncEnumerable<object> IOpenIdApplicationManager.ListInRoleAsync(string role, CancellationToken cancellationToken) => ListInRoleAsync(role, cancellationToken); ValueTask IOpenIdApplicationManager.SetRolesAsync(object application, ImmutableArray<string> roles, CancellationToken cancellationToken) => SetRolesAsync((TApplication)application, roles, cancellationToken); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System; namespace MigAz.Azure.Core.ArmTemplate { public class Extension : ArmResource { public Extension(Guid executionGuid) : base(executionGuid) { type = "extensions"; } } public class Extension_Properties { public string publisher; public string type; public string typeHandlerVersion; public bool autoUpgradeMinorVersion; public Dictionary<string, string> settings; } public class VirtualNetworkGateway : ArmResource { public VirtualNetworkGateway(Guid executionGuid) : base(executionGuid) { type = "Microsoft.Network/virtualNetworkGateways"; } } public class VirtualNetworkGateway_Properties { public List<IpConfiguration> ipConfigurations; public VirtualNetworkGateway_Sku sku; public string gatewayType; // VPN or ER public string vpnType; // RouteBased or PolicyBased public string enableBgp = "false"; public string activeActive = "false"; public VPNClientConfiguration vpnClientConfiguration; } public class VirtualNetworkGateway_Sku { public string name; public string tier; public int capacity; } public class LocalNetworkGateway : ArmResource { public LocalNetworkGateway(Guid executionGuid) : base(executionGuid) { type = "Microsoft.Network/localNetworkGateways"; } } public class LocalNetworkGateway_Properties { public AddressSpace localNetworkAddressSpace; public string gatewayIpAddress; } public class GatewayConnection : ArmResource { public GatewayConnection(Guid executionGuid) : base(executionGuid) { type = "Microsoft.Network/connections"; } } public class GatewayConnection_Properties { public Reference virtualNetworkGateway1; public Reference localNetworkGateway2; public string connectionType; public Reference peer; public long routingWeight = 10; public string sharedKey; } public class VPNClientConfiguration { public AddressSpace vpnClientAddressPool; public List<VPNClientCertificate> vpnClientRootCertificates; public List<VPNClientCertificate> vpnClientRevokedCertificates; } public class VPNClientCertificate { public string name; public VPNClientCertificate_Properties properties; } public class VPNClientCertificate_Properties { public string PublicCertData; public string Thumbprint; } public class RouteTable : ArmResource { public RouteTable(Guid executionGuid) : base(executionGuid) { type = "Microsoft.Network/routeTables"; } } public class RouteTable_Properties { public List<Route> routes; } public class Route { public string name; public Route_Properties properties; } public class Route_Properties { public string addressPrefix; public string nextHopType; public string nextHopIpAddress; } public class NetworkSecurityGroup : ArmResource { public NetworkSecurityGroup(Guid executionGuid) : base(executionGuid) { type = "Microsoft.Network/networkSecurityGroups"; } } public class NetworkSecurityGroup_Properties { public List<SecurityRule> securityRules; } public class SecurityRule { public string name; public SecurityRule_Properties properties; } public class SecurityRule_Properties { public string description; public string protocol; public string sourcePortRange; public string destinationPortRange; public string sourceAddressPrefix; public string destinationAddressPrefix; public string access; public long priority; public string direction; } public class VirtualNetwork : ArmResource { public VirtualNetwork(Guid executionGuid) : base(executionGuid) { type = "Microsoft.Network/virtualNetworks"; } } public class AddressSpace { public List<string> addressPrefixes; } public class VirtualNetwork_Properties { public AddressSpace addressSpace; public List<Subnet> subnets; public VirtualNetwork_dhcpOptions dhcpOptions; } public class Subnet { public string name; public Subnet_Properties properties; } public class Subnet_Properties { public string addressPrefix; public Reference networkSecurityGroup; public Reference routeTable; } public class VirtualNetwork_dhcpOptions { public List<string> dnsServers; } public class StorageAccount : ArmResource { public StorageAccount(Guid executionGuid) : base(executionGuid) { type = "Microsoft.Storage/storageAccounts"; } } public class StorageAccount_Properties { public string accountType; } public class LoadBalancer : ArmResource { public LoadBalancer(Guid executionGuid) : base(executionGuid) { type = "Microsoft.Network/loadBalancers"; } } public class LoadBalancer_Properties { public List<FrontendIPConfiguration> frontendIPConfigurations; public List<Hashtable> backendAddressPools; public List<InboundNatRule> inboundNatRules; public List<LoadBalancingRule> loadBalancingRules; public List<Probe> probes; } public class FrontendIPConfiguration { public string name = "default"; public FrontendIPConfiguration_Properties properties; } public class FrontendIPConfiguration_Properties { public Reference publicIPAddress; public string privateIPAllocationMethod; public string privateIPAddress; public Reference subnet; } public class InboundNatRule { public string name; public InboundNatRule_Properties properties; public override bool Equals(object obj) { if (obj.GetType() != typeof(InboundNatRule)) return false; return ((InboundNatRule)obj).name == this.name; } } public class InboundNatRule_Properties { public long frontendPort; public long backendPort; public bool enableFloatingIP; public long idleTimeoutInMinutes = 4; // https://azure.microsoft.com/en-us/blog/new-configurable-idle-timeout-for-azure-load-balancer/ public string protocol; public Reference frontendIPConfiguration; } public class LoadBalancingRule { public string name; public LoadBalancingRule_Properties properties; public override bool Equals(object obj) { if (obj.GetType() != typeof(LoadBalancingRule)) return false; return ((LoadBalancingRule)obj).name == this.name; } } public class LoadBalancingRule_Properties { public Reference frontendIPConfiguration; public Reference backendAddressPool; public Reference probe; public string protocol; public long frontendPort; public long backendPort; public long idleTimeoutInMinutes = 15; public string loadDistribution = "SourceIP"; public bool enableFloatingIP = false; } public class Probe { public string name; public Probe_Properties properties; public override bool Equals(object obj) { if (obj.GetType() != typeof(Probe)) return false; return ((Probe)obj).name == this.name; } } public class Probe_Properties { public string protocol; public long port; public long intervalInSeconds = 15; public long numberOfProbes = 2; public string requestPath; } public class PublicIPAddress : ArmResource { public PublicIPAddress(Guid executionGuid) : base(executionGuid) { type = "Microsoft.Network/publicIPAddresses"; } } public class PublicIPAddress_Properties { public string publicIPAllocationMethod = "Dynamic"; public Hashtable dnsSettings; } public class NetworkInterface : ArmResource { public NetworkInterface(Guid executionGuid) : base(executionGuid) { type = "Microsoft.Network/networkInterfaces"; } } public class NetworkInterface_Properties { public List<IpConfiguration> ipConfigurations; public bool enableIPForwarding = false; public bool enableAcceleratedNetworking = false; public Reference NetworkSecurityGroup; } public class IpConfiguration { public string name; public IpConfiguration_Properties properties; } public class IpConfiguration_Properties { public string privateIPAllocationMethod = "Dynamic"; public string privateIPAddress; public Reference publicIPAddress; public Reference subnet; public List<Reference> loadBalancerBackendAddressPools; public List<Reference> loadBalancerInboundNatRules; } public class AvailabilitySet : ArmResource { public AvailabilitySet(Guid executionGuid) : base(executionGuid) { type = "Microsoft.Compute/availabilitySets"; } } public class AvailabilitySet_Properties { public long platformUpdateDomainCount; public long platformFaultDomainCount; } public class VirtualMachine : ArmResource { public List<ArmResource> resources; public VirtualMachine(Guid executionGuid) : base(executionGuid) { type = "Microsoft.Compute/virtualMachines"; } public Dictionary<string, string> plan; } public class VirtualMachine_Properties { public HardwareProfile hardwareProfile; public Reference availabilitySet; public OsProfile osProfile; public StorageProfile storageProfile; public NetworkProfile networkProfile; public DiagnosticsProfile diagnosticsProfile; } public class HardwareProfile { public string vmSize; } public class OsProfile { public string computerName; public string adminUsername; public string adminPassword; } public class StorageProfile { public ImageReference imageReference; public OsDisk osDisk; public List<DataDisk> dataDisks; } public class ImageReference { public string publisher; public string offer; public string sku; public string version; } public class OsDisk { public string name; public string osType; public Vhd vhd; public Reference managedDisk; public string caching; public string createOption; public DiskEncrpytionSettings encryptionSettings; } public class DataDisk { public string name; public Vhd vhd; public Reference managedDisk; public string caching; public string createOption; public long? diskSizeGB; public long lun; public DiskEncrpytionSettings encryptionSettings; } public class DiskEncrpytionSettings { public bool enabled; public DiskEncryptionKeySettings diskEncryptionKey; public KeyEncryptionKeySettings keyEncryptionKey; } public class KeyEncryptionKeySettings { public Reference sourceVault; public string keyUrl; } public class DiskEncryptionKeySettings { public Reference sourceVault; public string secretUrl; } public class Vhd { public string uri; } public class ManagedDisk : Disk { public ManagedDisk(Guid executionGuid) : base(executionGuid) { } } public class ManagedDisk_Sku { public string name = "Premium_LRS"; } public class ManagedDisk_Properties { public ManagedDiskCreationData_Properties creationData; public int diskSizeGb; } public class ManagedDiskCreationData_Properties { public string createOption = "Empty"; public string sourceUri ; } public class Snapshot : Disk { public Snapshot(Guid executionGuid) : base(executionGuid) { type = "Microsoft.Compute/snapshots"; } } public class Disk : ArmResource { public Disk(Guid executionGuid) : base(executionGuid) { type = "Microsoft.Compute/disks"; } } public class Disk_Properties { public Disk_CreationData creationData; public string accountType; public string diskSizeGB; public string osType; } public class Disk_CreationData { public string createOption; // Copy (from Snapshot), Empty, Import (from blob) public string sourceUri; public string sourceResourceId; } public class NetworkProfile { public List<NetworkProfile_NetworkInterface> networkInterfaces; } public class NetworkProfile_NetworkInterface { public string id; public NetworkProfile_NetworkInterface_Properties properties; } public class NetworkProfile_NetworkInterface_Properties { public bool primary = true; } public class DiagnosticsProfile { public BootDiagnostics bootDiagnostics; } public class BootDiagnostics { public bool enabled; public string storageUri; } public class Reference { public string id; } public class ArmResource { public string type; public string apiVersion; public string name; public string location = "[resourceGroup().location]"; public Dictionary<string, string> tags; public List<string> dependsOn; public Dictionary<string, string> sku = null; public object properties; private ArmResource() { } public ArmResource(Guid executionGuid) { //if (app.Default.AllowTag) // TODO //{ tags = new Dictionary<string, string>(); tags.Add("migAz", executionGuid.ToString()); //} } public override bool Equals(object obj) { try { ArmResource other = (ArmResource)obj; return this.type == other.type && this.name == other.name; } catch { return false; } } } public class Parameter { public string type; public string value; } public class Template { public string schemalink = "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#"; public string contentVersion = "1.0.0.0"; public Dictionary<string, Parameter> parameters; public Dictionary<string, string> variables; public List<ArmResource> resources; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; using JetBrains.Annotations; using UnicornHack.Utils.DataStructures; namespace UnicornHack.Utils { public static class Extensions { public static IReadOnlyCollection<T> GetFlags<T>(this T flags) { var values = new List<T>(); var defaultValue = Enum.ToObject(typeof(T), value: 0); foreach (Enum currValue in Enum.GetValues(typeof(T))) { if (currValue.Equals(defaultValue)) { continue; } if (((Enum)(object)flags).HasFlag(currValue)) { values.Add((T)(object)currValue); } } return values; } public static IReadOnlyCollection<T> GetNonRedundantFlags<T>(this T flags, bool removeComposites) { var values = new HashSet<T>(flags.GetFlags()); foreach (var currentValue in values.ToList()) { var decomposedValues = currentValue.GetFlags(); if (decomposedValues.Count > 1) { if (removeComposites) { values.Remove(currentValue); } else { values.ExceptWith(decomposedValues.Where(v => !Equals(v, currentValue))); } } } return values; } public static ICollection<T> With<T>(this ICollection<T> list, T item) { list.Add(item); return list; } public static ICollection<T> AddRange<T>(this ICollection<T> collection, IEnumerable<T> items) { foreach (var item in items) { collection.Add(item); } return collection; } public static Dictionary<TKey, TValue> AddRange<TKey, TValue>( this Dictionary<TKey, TValue> dictionary, IEnumerable<TKey> items, Func<TKey, TValue> selector) { foreach (var item in items) { dictionary.Add(item, selector(item)); } return dictionary; } public static Queue<T> EnqueueRange<T>(this Queue<T> queue, IEnumerable<T> items) { foreach (var item in items) { queue.Enqueue(item); } return queue; } public static IEnumerable<Point> AsPoints(this IEnumerable<byte> bytes) { using (var enumerable = bytes.GetEnumerator()) { while (enumerable.MoveNext()) { var x = enumerable.Current; enumerable.MoveNext(); var y = enumerable.Current; yield return new Point(x, y); } } } public static IEnumerable<byte> AsBytes(this IEnumerable<Point> points) { foreach (var point in points) { yield return point.X; yield return point.Y; } } public static PropertyInfo GetPropertyAccess([NotNull] this LambdaExpression propertyAccessExpression) { Debug.Assert(propertyAccessExpression.Parameters.Count == 1); var parameterExpression = propertyAccessExpression.Parameters.Single(); var propertyInfo = parameterExpression.MatchSimplePropertyAccess(propertyAccessExpression.Body); if (propertyInfo == null) { throw new ArgumentException(nameof(propertyAccessExpression)); } var declaringType = propertyInfo.DeclaringType; var parameterType = parameterExpression.Type; if (declaringType != null && declaringType != parameterType && declaringType.GetTypeInfo().IsInterface && declaringType.GetTypeInfo().IsAssignableFrom(parameterType.GetTypeInfo())) { var propertyGetter = propertyInfo.GetMethod; var interfaceMapping = parameterType.GetTypeInfo().GetRuntimeInterfaceMap(declaringType); var index = Array.FindIndex(interfaceMapping.InterfaceMethods, p => propertyGetter.Equals(p)); var targetMethod = interfaceMapping.TargetMethods[index]; foreach (var runtimeProperty in parameterType.GetRuntimeProperties()) { if (targetMethod.Equals(runtimeProperty.GetMethod)) { return runtimeProperty; } } } return propertyInfo; } private static PropertyInfo MatchSimplePropertyAccess( this Expression parameterExpression, Expression propertyAccessExpression) { var propertyInfos = MatchPropertyAccess(parameterExpression, propertyAccessExpression); return propertyInfos?.Count == 1 ? propertyInfos[0] : null; } private static IReadOnlyList<PropertyInfo> MatchPropertyAccess( this Expression parameterExpression, Expression propertyAccessExpression) { var propertyInfos = new List<PropertyInfo>(); MemberExpression memberExpression; do { memberExpression = RemoveTypeAs(RemoveConvert(propertyAccessExpression)) as MemberExpression; var propertyInfo = memberExpression?.Member as PropertyInfo; if (propertyInfo == null) { return null; } propertyInfos.Insert(0, propertyInfo); propertyAccessExpression = memberExpression.Expression; } while (RemoveTypeAs(RemoveConvert(memberExpression.Expression)) != parameterExpression); return propertyInfos; } public static Expression RemoveConvert([CanBeNull] this Expression expression) { while (expression != null && (expression.NodeType == ExpressionType.Convert || expression.NodeType == ExpressionType.ConvertChecked)) { expression = RemoveConvert(((UnaryExpression)expression).Operand); } return expression; } public static Expression RemoveTypeAs([CanBeNull] this Expression expression) { while (expression?.NodeType == ExpressionType.TypeAs) { expression = RemoveConvert(((UnaryExpression)expression).Operand); } return expression; } public static MethodInfo GetRequiredRuntimeMethod(this Type type, string name, params Type[] parameters) { var method = type.GetTypeInfo().GetRuntimeMethod(name, parameters); if (method == null) { throw new InvalidOperationException(); } return method; } public static Type UnwrapNullableType(this Type type) => Nullable.GetUnderlyingType(type) ?? type; public static bool IsNumeric(this Type type) { type = type.UnwrapNullableType(); return type.IsInteger() || type == typeof(decimal) || type == typeof(float) || type == typeof(double); } public static bool IsInteger(this Type type) { type = type.UnwrapNullableType(); return type == typeof(int) || type == typeof(long) || type == typeof(short) || type == typeof(byte) || type == typeof(uint) || type == typeof(ulong) || type == typeof(ushort) || type == typeof(sbyte) || type == typeof(char); } public static bool IsSignedInteger(this Type type) => type == typeof(int) || type == typeof(long) || type == typeof(short) || type == typeof(sbyte); } }
using System; using System.Collections; using System.Collections.Generic; using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.TeamFoundation.DistributedTask.Expressions; using System.Text; namespace Microsoft.VisualStudio.Services.Agent.Worker { [ServiceLocator(Default = typeof(ExpressionManager))] public interface IExpressionManager : IAgentService { IExpressionNode Parse(IExecutionContext context, string condition); ConditionResult Evaluate(IExecutionContext context, IExpressionNode tree, bool hostTracingOnly = false); } public sealed class ExpressionManager : AgentService, IExpressionManager { public static IExpressionNode Always = new AlwaysNode(); public static IExpressionNode Succeeded = new SucceededNode(); public static IExpressionNode SucceededOrFailed = new SucceededOrFailedNode(); public IExpressionNode Parse(IExecutionContext executionContext, string condition) { ArgUtil.NotNull(executionContext, nameof(executionContext)); var expressionTrace = new TraceWriter(Trace, executionContext); var parser = new ExpressionParser(); var namedValues = new INamedValueInfo[] { new NamedValueInfo<VariablesNode>(name: Constants.Expressions.Variables), }; var functions = new IFunctionInfo[] { new FunctionInfo<AlwaysNode>(name: Constants.Expressions.Always, minParameters: 0, maxParameters: 0), new FunctionInfo<CanceledNode>(name: Constants.Expressions.Canceled, minParameters: 0, maxParameters: 0), new FunctionInfo<FailedNode>(name: Constants.Expressions.Failed, minParameters: 0, maxParameters: 0), new FunctionInfo<SucceededNode>(name: Constants.Expressions.Succeeded, minParameters: 0, maxParameters: 0), new FunctionInfo<SucceededOrFailedNode>(name: Constants.Expressions.SucceededOrFailed, minParameters: 0, maxParameters: 0), }; return parser.CreateTree(condition, expressionTrace, namedValues, functions) ?? new SucceededNode(); } public ConditionResult Evaluate(IExecutionContext executionContext, IExpressionNode tree, bool hostTracingOnly = false) { ArgUtil.NotNull(executionContext, nameof(executionContext)); ArgUtil.NotNull(tree, nameof(tree)); ConditionResult result = new ConditionResult(); var expressionTrace = new TraceWriter(Trace, hostTracingOnly ? null : executionContext); result.Value = tree.Evaluate<bool>(trace: expressionTrace, secretMasker: HostContext.SecretMasker, state: executionContext); result.Trace = expressionTrace.Trace; return result; } private sealed class TraceWriter : ITraceWriter { private readonly IExecutionContext _executionContext; private readonly Tracing _trace; private readonly StringBuilder _traceBuilder = new StringBuilder(); public string Trace => _traceBuilder.ToString(); public TraceWriter(Tracing trace, IExecutionContext executionContext) { ArgUtil.NotNull(trace, nameof(trace)); _trace = trace; _executionContext = executionContext; } public void Info(string message) { _trace.Info(message); _executionContext?.Debug(message); _traceBuilder.AppendLine(message); } public void Verbose(string message) { _trace.Verbose(message); _executionContext?.Debug(message); } } private sealed class AlwaysNode : FunctionNode { protected override Object EvaluateCore(EvaluationContext context) { return true; } } private sealed class CanceledNode : FunctionNode { protected sealed override object EvaluateCore(EvaluationContext evaluationContext) { var executionContext = evaluationContext.State as IExecutionContext; ArgUtil.NotNull(executionContext, nameof(executionContext)); TaskResult jobStatus = executionContext.Variables.Agent_JobStatus ?? TaskResult.Succeeded; return jobStatus == TaskResult.Canceled; } } private sealed class FailedNode : FunctionNode { protected sealed override object EvaluateCore(EvaluationContext evaluationContext) { var executionContext = evaluationContext.State as IExecutionContext; ArgUtil.NotNull(executionContext, nameof(executionContext)); TaskResult jobStatus = executionContext.Variables.Agent_JobStatus ?? TaskResult.Succeeded; return jobStatus == TaskResult.Failed; } } private sealed class SucceededNode : FunctionNode { protected sealed override object EvaluateCore(EvaluationContext evaluationContext) { var executionContext = evaluationContext.State as IExecutionContext; ArgUtil.NotNull(executionContext, nameof(executionContext)); TaskResult jobStatus = executionContext.Variables.Agent_JobStatus ?? TaskResult.Succeeded; return jobStatus == TaskResult.Succeeded || jobStatus == TaskResult.SucceededWithIssues; } } private sealed class SucceededOrFailedNode : FunctionNode { protected sealed override object EvaluateCore(EvaluationContext evaluationContext) { var executionContext = evaluationContext.State as IExecutionContext; ArgUtil.NotNull(executionContext, nameof(executionContext)); TaskResult jobStatus = executionContext.Variables.Agent_JobStatus ?? TaskResult.Succeeded; return jobStatus == TaskResult.Succeeded || jobStatus == TaskResult.SucceededWithIssues || jobStatus == TaskResult.Failed; } } private sealed class VariablesNode : NamedValueNode { protected sealed override object EvaluateCore(EvaluationContext evaluationContext) { var jobContext = evaluationContext.State as IExecutionContext; ArgUtil.NotNull(jobContext, nameof(jobContext)); return new VariablesDictionary(jobContext.Variables); } } private sealed class VariablesDictionary : IReadOnlyDictionary<string, object> { private readonly Variables _variables; public VariablesDictionary(Variables variables) { _variables = variables; } // IReadOnlyDictionary<string object> members public object this[string key] => _variables.Get(key); public IEnumerable<string> Keys => throw new NotSupportedException(); public IEnumerable<object> Values => throw new NotSupportedException(); public bool ContainsKey(string key) { string val; return _variables.TryGetValue(key, out val); } public bool TryGetValue(string key, out object value) { string s; bool found = _variables.TryGetValue(key, out s); value = s; return found; } // IReadOnlyCollection<KeyValuePair<string, object>> members public int Count => throw new NotSupportedException(); // IEnumerable<KeyValuePair<string, object>> members IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator() => throw new NotSupportedException(); // IEnumerable members IEnumerator IEnumerable.GetEnumerator() => throw new NotSupportedException(); } } public class ConditionResult { public ConditionResult(bool value = false, string trace = null) { this.Value = value; this.Trace = trace; } public bool Value { get; set; } public string Trace { get; set; } public static implicit operator ConditionResult(bool value) { return new ConditionResult(value); } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // System.Configuration.ConfigurationManagerTest.cs - Unit tests // for System.Configuration.ConfigurationManager. // // Author: // Chris Toshok <[email protected]> // Atsushi Enomoto <[email protected]> // // Copyright (C) 2005-2006 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Specialized; using System.Configuration; using System.IO; using Xunit; using SysConfig = System.Configuration.Configuration; namespace MonoTests.System.Configuration { using Util; public class ConfigurationManagerTest { [Fact] // OpenExeConfiguration (ConfigurationUserLevel) [ActiveIssue("dotnet/corefx #19384", TargetFrameworkMonikers.NetFramework)] public void OpenExeConfiguration1_UserLevel_None() { SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal(TestUtil.ThisConfigFileName, fi.Name); } [Fact] public void OpenExeConfiguration1_UserLevel_PerUserRoaming() { string applicationData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // If there is not ApplicationData folder PerUserRoaming won't work if (string.IsNullOrEmpty(applicationData)) return; SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming); Assert.False(string.IsNullOrEmpty(config.FilePath), "should have some file path"); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("user.config", fi.Name); } [Fact] [ActiveIssue(15065, TestPlatforms.AnyUnix)] public void OpenExeConfiguration1_UserLevel_PerUserRoamingAndLocal() { SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("user.config", fi.Name); } [Fact] // OpenExeConfiguration (String) public void OpenExeConfiguration2() { using (var temp = new TempDirectory()) { string exePath; SysConfig config; exePath = Path.Combine(temp.Path, "DoesNotExist.whatever"); File.Create(exePath).Close(); config = ConfigurationManager.OpenExeConfiguration(exePath); Assert.Equal(exePath + ".config", config.FilePath); exePath = Path.Combine(temp.Path, "SomeExecutable.exe"); File.Create(exePath).Close(); config = ConfigurationManager.OpenExeConfiguration(exePath); Assert.Equal(exePath + ".config", config.FilePath); exePath = Path.Combine(temp.Path, "Foo.exe.config"); File.Create(exePath).Close(); config = ConfigurationManager.OpenExeConfiguration(exePath); Assert.Equal(exePath + ".config", config.FilePath); } } [Fact] // OpenExeConfiguration (String) public void OpenExeConfiguration2_ExePath_DoesNotExist() { using (var temp = new TempDirectory()) { string exePath = Path.Combine(temp.Path, "DoesNotExist.exe"); ConfigurationErrorsException ex = Assert.Throws<ConfigurationErrorsException>( () => ConfigurationManager.OpenExeConfiguration(exePath)); // An error occurred loading a configuration file: // The parameter 'exePath' is invalid Assert.Equal(typeof(ConfigurationErrorsException), ex.GetType()); Assert.Null(ex.Filename); Assert.NotNull(ex.InnerException); Assert.Equal(0, ex.Line); Assert.NotNull(ex.Message); // The parameter 'exePath' is invalid ArgumentException inner = ex.InnerException as ArgumentException; Assert.NotNull(inner); Assert.Equal(typeof(ArgumentException), inner.GetType()); Assert.Null(inner.InnerException); Assert.NotNull(inner.Message); Assert.Equal("exePath", inner.ParamName); } } [Fact] [ActiveIssue("dotnet/corefx #18831", TargetFrameworkMonikers.NetFramework)] public void exePath_UserLevelNone() { string name = TestUtil.ThisApplicationPath; SysConfig config = ConfigurationManager.OpenExeConfiguration(name); Assert.Equal(TestUtil.ThisApplicationPath + ".config", config.FilePath); } [Fact] public void exePath_UserLevelPerRoaming() { string applicationData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // If there is not ApplicationData folder PerUserRoaming won't work if (string.IsNullOrEmpty(applicationData)) return; SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming); string filePath = config.FilePath; Assert.False(string.IsNullOrEmpty(filePath), "should have some file path"); Assert.Equal("user.config", Path.GetFileName(filePath)); } [Fact] [ActiveIssue(15066, TestPlatforms.AnyUnix)] public void exePath_UserLevelPerRoamingAndLocal() { SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal); string filePath = config.FilePath; string applicationData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); Assert.True(filePath.StartsWith(applicationData), "#1:" + filePath); Assert.Equal("user.config", Path.GetFileName(filePath)); } [Fact] public void mapped_UserLevelNone() { ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.ExeConfigFilename = "execonfig"; SysConfig config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("execonfig", fi.Name); } [Fact] public void mapped_UserLevelPerRoaming() { ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.ExeConfigFilename = "execonfig"; map.RoamingUserConfigFilename = "roaminguser"; SysConfig config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoaming); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("roaminguser", fi.Name); } [Fact] // Doesn't pass on Mono // [Category("NotWorking")] public void mapped_UserLevelPerRoaming_no_execonfig() { ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.RoamingUserConfigFilename = "roaminguser"; AssertExtensions.Throws<ArgumentException>("fileMap.ExeConfigFilename", () => ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoaming)); } [Fact] public void mapped_UserLevelPerRoamingAndLocal() { ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.ExeConfigFilename = "execonfig"; map.RoamingUserConfigFilename = "roaminguser"; map.LocalUserConfigFilename = "localuser"; SysConfig config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoamingAndLocal); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("localuser", fi.Name); } [Fact] // Doesn't pass on Mono // [Category("NotWorking")] public void mapped_UserLevelPerRoamingAndLocal_no_execonfig() { ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.RoamingUserConfigFilename = "roaminguser"; map.LocalUserConfigFilename = "localuser"; AssertExtensions.Throws<ArgumentException>("fileMap.ExeConfigFilename", () => ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoamingAndLocal)); } [Fact] // Doesn't pass on Mono // [Category("NotWorking")] public void mapped_UserLevelPerRoamingAndLocal_no_roaminguser() { ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.ExeConfigFilename = "execonfig"; map.LocalUserConfigFilename = "localuser"; AssertExtensions.Throws<ArgumentException>("fileMap.RoamingUserConfigFilename", () => ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoamingAndLocal)); } [Fact] public void MachineConfig() { SysConfig config = ConfigurationManager.OpenMachineConfiguration(); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("machine.config", fi.Name); } [Fact] public void mapped_MachineConfig() { ConfigurationFileMap map = new ConfigurationFileMap(); map.MachineConfigFilename = "machineconfig"; SysConfig config = ConfigurationManager.OpenMappedMachineConfiguration(map); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("machineconfig", fi.Name); } [Fact] // Doesn't pass on Mono // [Category("NotWorking")] [ActiveIssue("dotnet/corefx #19384", TargetFrameworkMonikers.NetFramework)] public void mapped_ExeConfiguration_null() { SysConfig config = ConfigurationManager.OpenMappedExeConfiguration(null, ConfigurationUserLevel.None); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal(TestUtil.ThisConfigFileName, fi.Name); } [Fact] // Doesn't pass on Mono // [Category("NotWorking")] public void mapped_MachineConfig_null() { SysConfig config = ConfigurationManager.OpenMappedMachineConfiguration(null); FileInfo fi = new FileInfo(config.FilePath); Assert.Equal("machine.config", fi.Name); } [Fact] public void GetSectionReturnsNativeObject() { Assert.True(ConfigurationManager.GetSection("appSettings") is NameValueCollection); } [Fact] // Test for bug #3412 // Doesn't pass on Mono // [Category("NotWorking")] public void TestAddRemoveSection() { const string name = "testsection"; var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // ensure not present if (config.Sections.Get(name) != null) { config.Sections.Remove(name); } // add config.Sections.Add(name, new TestSection()); // remove var section = config.Sections.Get(name); Assert.NotNull(section); Assert.NotNull(section as TestSection); config.Sections.Remove(name); // add config.Sections.Add(name, new TestSection()); // remove section = config.Sections.Get(name); Assert.NotNull(section); Assert.NotNull(section as TestSection); config.Sections.Remove(name); } [Fact] public void TestFileMap() { using (var temp = new TempDirectory()) { string configPath = Path.Combine(temp.Path, Path.GetRandomFileName() + ".config"); Assert.False(File.Exists(configPath)); var map = new ExeConfigurationFileMap(); map.ExeConfigFilename = configPath; var config = ConfigurationManager.OpenMappedExeConfiguration( map, ConfigurationUserLevel.None); config.Sections.Add("testsection", new TestSection()); config.Save(); Assert.True(File.Exists(configPath), "#1"); Assert.True(File.Exists(Path.GetFullPath(configPath)), "#2"); } } [Fact] public void TestContext() { var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); const string name = "testsection"; // ensure not present if (config.GetSection(name) != null) config.Sections.Remove(name); var section = new TestContextSection(); // Can't access EvaluationContext .... Assert.Throws<ConfigurationErrorsException>(() => section.TestContext(null)); // ... until it's been added to a section. config.Sections.Add(name, section); section.TestContext("#2"); // Remove ... config.Sections.Remove(name); // ... and it doesn't lose its context section.TestContext(null); } [Fact] public void TestContext2() { using (var temp = new TempDirectory()) { string configPath = Path.Combine(temp.Path, Path.GetRandomFileName() + ".config"); Assert.False(File.Exists(configPath)); var map = new ExeConfigurationFileMap(); map.ExeConfigFilename = configPath; var config = ConfigurationManager.OpenMappedExeConfiguration( map, ConfigurationUserLevel.None); config.Sections.Add("testsection", new TestSection()); config.Sections.Add("testcontext", new TestContextSection()); config.Save(); Assert.True(File.Exists(configPath), "#1"); } } class TestSection : ConfigurationSection { } class TestContextSection : ConfigurationSection { public void TestContext(string label) { Assert.NotNull(EvaluationContext); } } [Fact] public void BadConfig() { using (var temp = new TempDirectory()) { string xml = @" badXml"; var file = Path.Combine(temp.Path, "badConfig.config"); File.WriteAllText(file, xml); var fileMap = new ConfigurationFileMap(file); Assert.Equal(file, Assert.Throws<ConfigurationErrorsException>(() => ConfigurationManager.OpenMappedMachineConfiguration(fileMap)).Filename); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml; using Hyak.Common; using Microsoft.Azure.Insights; using Microsoft.Azure.Insights.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Insights { /// <summary> /// Operations for metric values. /// </summary> internal partial class MetricOperations : IServiceOperations<InsightsClient>, IMetricOperations { /// <summary> /// Initializes a new instance of the MetricOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal MetricOperations(InsightsClient client) { this._client = client; } private InsightsClient _client; /// <summary> /// Gets a reference to the Microsoft.Azure.Insights.InsightsClient. /// </summary> public InsightsClient Client { get { return this._client; } } /// <summary> /// The List Metric operation lists the metric value sets for the /// resource metrics. /// </summary> /// <param name='resourceUri'> /// Required. The resource identifier of the target resource to get /// metrics for. /// </param> /// <param name='filterString'> /// Optional. An OData $filter expression that supports querying by the /// name, startTime, endTime and timeGrain of the metric value sets. /// For example, "(name.value eq 'Percentage CPU') and startTime eq /// 2014-07-02T01:00Z and endTime eq 2014-08-21T01:00:00Z and /// timeGrain eq duration'PT1H'". In the expression, startTime, /// endTime and timeGrain are required. Name is optional. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Metric values operation response. /// </returns> public async Task<MetricListResponse> GetMetricsAsync(string resourceUri, string filterString, CancellationToken cancellationToken) { // Validate if (resourceUri == null) { throw new ArgumentNullException("resourceUri"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceUri", resourceUri); tracingParameters.Add("filterString", filterString); TracingAdapter.Enter(invocationId, this, "GetMetricsAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; url = url + resourceUri; url = url + "/metrics"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); List<string> odataFilter = new List<string>(); if (filterString != null) { odataFilter.Add(Uri.EscapeDataString(filterString)); } if (odataFilter.Count > 0) { queryParameters.Add("$filter=" + string.Join(null, odataFilter)); } if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-04-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result MetricListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new MetricListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { MetricCollection metricCollectionInstance = new MetricCollection(); result.MetricCollection = metricCollectionInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Metric metricInstance = new Metric(); metricCollectionInstance.Value.Add(metricInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { LocalizableString nameInstance = new LocalizableString(); metricInstance.Name = nameInstance; JToken valueValue2 = nameValue["value"]; if (valueValue2 != null && valueValue2.Type != JTokenType.Null) { string valueInstance = ((string)valueValue2); nameInstance.Value = valueInstance; } JToken localizedValueValue = nameValue["localizedValue"]; if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null) { string localizedValueInstance = ((string)localizedValueValue); nameInstance.LocalizedValue = localizedValueInstance; } } JToken unitValue = valueValue["unit"]; if (unitValue != null && unitValue.Type != JTokenType.Null) { Unit unitInstance = ((Unit)Enum.Parse(typeof(Unit), ((string)unitValue), true)); metricInstance.Unit = unitInstance; } JToken timeGrainValue = valueValue["timeGrain"]; if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null) { TimeSpan timeGrainInstance = XmlConvert.ToTimeSpan(((string)timeGrainValue)); metricInstance.TimeGrain = timeGrainInstance; } JToken startTimeValue = valueValue["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTime startTimeInstance = ((DateTime)startTimeValue); metricInstance.StartTime = startTimeInstance; } JToken endTimeValue = valueValue["endTime"]; if (endTimeValue != null && endTimeValue.Type != JTokenType.Null) { DateTime endTimeInstance = ((DateTime)endTimeValue); metricInstance.EndTime = endTimeInstance; } JToken metricValuesArray = valueValue["metricValues"]; if (metricValuesArray != null && metricValuesArray.Type != JTokenType.Null) { foreach (JToken metricValuesValue in ((JArray)metricValuesArray)) { MetricValue metricValueInstance = new MetricValue(); metricInstance.MetricValues.Add(metricValueInstance); JToken timestampValue = metricValuesValue["timestamp"]; if (timestampValue != null && timestampValue.Type != JTokenType.Null) { DateTime timestampInstance = ((DateTime)timestampValue); metricValueInstance.Timestamp = timestampInstance; } JToken averageValue = metricValuesValue["average"]; if (averageValue != null && averageValue.Type != JTokenType.Null) { double averageInstance = ((double)averageValue); metricValueInstance.Average = averageInstance; } JToken minimumValue = metricValuesValue["minimum"]; if (minimumValue != null && minimumValue.Type != JTokenType.Null) { double minimumInstance = ((double)minimumValue); metricValueInstance.Minimum = minimumInstance; } JToken maximumValue = metricValuesValue["maximum"]; if (maximumValue != null && maximumValue.Type != JTokenType.Null) { double maximumInstance = ((double)maximumValue); metricValueInstance.Maximum = maximumInstance; } JToken totalValue = metricValuesValue["total"]; if (totalValue != null && totalValue.Type != JTokenType.Null) { double totalInstance = ((double)totalValue); metricValueInstance.Total = totalInstance; } JToken countValue = metricValuesValue["count"]; if (countValue != null && countValue.Type != JTokenType.Null) { long countInstance = ((long)countValue); metricValueInstance.Count = countInstance; } JToken lastValue = metricValuesValue["last"]; if (lastValue != null && lastValue.Type != JTokenType.Null) { double lastInstance = ((double)lastValue); metricValueInstance.Last = lastInstance; } JToken propertiesSequenceElement = ((JToken)metricValuesValue["properties"]); if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in propertiesSequenceElement) { string propertiesKey = ((string)property.Name); string propertiesValue = ((string)property.Value); metricValueInstance.Properties.Add(propertiesKey, propertiesValue); } } } } JToken resourceIdValue = valueValue["resourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { string resourceIdInstance = ((string)resourceIdValue); metricInstance.ResourceId = resourceIdInstance; } JToken propertiesSequenceElement2 = ((JToken)valueValue["properties"]); if (propertiesSequenceElement2 != null && propertiesSequenceElement2.Type != JTokenType.Null) { foreach (JProperty property2 in propertiesSequenceElement2) { string propertiesKey2 = ((string)property2.Name); string propertiesValue2 = ((string)property2.Value); metricInstance.Properties.Add(propertiesKey2, propertiesValue2); } } JToken dimensionNameValue = valueValue["dimensionName"]; if (dimensionNameValue != null && dimensionNameValue.Type != JTokenType.Null) { LocalizableString dimensionNameInstance = new LocalizableString(); metricInstance.DimensionName = dimensionNameInstance; JToken valueValue3 = dimensionNameValue["value"]; if (valueValue3 != null && valueValue3.Type != JTokenType.Null) { string valueInstance2 = ((string)valueValue3); dimensionNameInstance.Value = valueInstance2; } JToken localizedValueValue2 = dimensionNameValue["localizedValue"]; if (localizedValueValue2 != null && localizedValueValue2.Type != JTokenType.Null) { string localizedValueInstance2 = ((string)localizedValueValue2); dimensionNameInstance.LocalizedValue = localizedValueInstance2; } } JToken dimensionValueValue = valueValue["dimensionValue"]; if (dimensionValueValue != null && dimensionValueValue.Type != JTokenType.Null) { LocalizableString dimensionValueInstance = new LocalizableString(); metricInstance.DimensionValue = dimensionValueInstance; JToken valueValue4 = dimensionValueValue["value"]; if (valueValue4 != null && valueValue4.Type != JTokenType.Null) { string valueInstance3 = ((string)valueValue4); dimensionValueInstance.Value = valueInstance3; } JToken localizedValueValue3 = dimensionValueValue["localizedValue"]; if (localizedValueValue3 != null && localizedValueValue3.Type != JTokenType.Null) { string localizedValueInstance3 = ((string)localizedValueValue3); dimensionValueInstance.LocalizedValue = localizedValueInstance3; } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
/* * * (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.Globalization; using System.Linq; using System.Security; using System.Security.Principal; using System.Threading; using System.Threading.Tasks; using ASC.Common.Logging; using ASC.Common.Security.Authentication; using ASC.Common.Security.Authorizing; using ASC.Common.Threading; using ASC.Core; using ASC.Core.Tenants; using ASC.Files.Core; using ASC.Files.Core.Security; using ASC.Web.Files.Classes; using ASC.Web.Files.Resources; namespace ASC.Web.Files.Services.WCFService.FileOperations { abstract class FileOperation { public const string SPLIT_CHAR = ":"; public const string OWNER = "Owner"; public const string OPERATION_TYPE = "OperationType"; public const string SOURCE = "Source"; public const string PROGRESS = "Progress"; public const string RESULT = "Result"; public const string ERROR = "Error"; public const string PROCESSED = "Processed"; public const string FINISHED = "Finished"; public const string HOLD = "Hold"; private readonly IPrincipal principal; private readonly string culture; private int total; private int processed; private int successProcessed; protected DistributedTask TaskInfo { get; private set; } protected string Status { get; set; } protected string Error { get; set; } protected Tenant CurrentTenant { get; private set; } protected FileSecurity FilesSecurity { get; private set; } protected IFolderDao FolderDao { get; private set; } protected IFileDao FileDao { get; private set; } protected ITagDao TagDao { get; private set; } protected ILinkDao LinkDao { get; private set; } protected IProviderDao ProviderDao { get; private set; } protected ILog Logger { get; private set; } protected CancellationToken CancellationToken { get; private set; } protected List<object> Folders { get; private set; } protected List<object> Files { get; private set; } protected bool HoldResult { get; private set; } public abstract FileOperationType OperationType { get; } protected FileOperation(List<object> folders, List<object> files, bool holdResult = true, Tenant tenant = null) { CurrentTenant = tenant ?? CoreContext.TenantManager.GetCurrentTenant(); principal = Thread.CurrentPrincipal; culture = Thread.CurrentThread.CurrentCulture.Name; Folders = folders ?? new List<object>(); Files = files ?? new List<object>(); HoldResult = holdResult; TaskInfo = new DistributedTask(); } public void RunJob(DistributedTask _, CancellationToken cancellationToken) { try { CancellationToken = cancellationToken; CoreContext.TenantManager.SetCurrentTenant(CurrentTenant); Thread.CurrentPrincipal = principal; Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(culture); Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(culture); FolderDao = Global.DaoFactory.GetFolderDao(); FileDao = Global.DaoFactory.GetFileDao(); TagDao = Global.DaoFactory.GetTagDao(); ProviderDao = Global.DaoFactory.GetProviderDao(); FilesSecurity = new FileSecurity(Global.DaoFactory); LinkDao = Global.GetLinkDao(); Logger = Global.Logger; total = InitTotalProgressSteps(); Do(); } catch (AuthorizingException authError) { Error = FilesCommonResource.ErrorMassage_SecurityException; Logger.Error(Error, new SecurityException(Error, authError)); } catch (AggregateException ae) { ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException); } catch (Exception error) { Error = error is TaskCanceledException || error is OperationCanceledException ? FilesCommonResource.ErrorMassage_OperationCanceledException : error.Message; Logger.Error(error, error); } finally { try { TaskInfo.SetProperty(FINISHED, true); PublishTaskInfo(); FolderDao.Dispose(); FileDao.Dispose(); TagDao.Dispose(); LinkDao.Dispose(); if (ProviderDao != null) ProviderDao.Dispose(); } catch { /* ignore */ } } } public virtual DistributedTask GetDistributedTask() { FillDistributedTask(); return TaskInfo; } protected virtual void FillDistributedTask() { var progress = total != 0 ? 100 * processed / total : 0; TaskInfo.SetProperty(SOURCE, string.Join(SPLIT_CHAR, Folders.Select(f => "folder_" + f).Concat(Files.Select(f => "file_" + f)).ToArray())); TaskInfo.SetProperty(OPERATION_TYPE, OperationType); TaskInfo.SetProperty(OWNER, ((IAccount)Thread.CurrentPrincipal.Identity).ID); TaskInfo.SetProperty(PROGRESS, progress < 100 ? progress : 100); TaskInfo.SetProperty(RESULT, Status); TaskInfo.SetProperty(ERROR, Error); TaskInfo.SetProperty(PROCESSED, successProcessed); TaskInfo.SetProperty(HOLD, HoldResult); } protected virtual int InitTotalProgressSteps() { var count = Files.Count; Folders.ForEach(f => count += 1 + (FolderDao.CanCalculateSubitems(f) ? FolderDao.GetItemsCount(f) : 0)); return count; } protected void ProgressStep(object folderId = null, object fileId = null) { if (folderId == null && fileId == null || folderId != null && Folders.Contains(folderId) || fileId != null && Files.Contains(fileId)) { processed++; PublishTaskInfo(); } } protected bool ProcessedFolder(object folderId) { successProcessed++; if (Folders.Contains(folderId)) { Status += string.Format("folder_{0}{1}", folderId, SPLIT_CHAR); return true; } return false; } protected bool ProcessedFile(object fileId) { successProcessed++; if (Files.Contains(fileId)) { Status += string.Format("file_{0}{1}", fileId, SPLIT_CHAR); return true; } return false; } protected void PublishTaskInfo() { FillDistributedTask(); TaskInfo.PublishChanges(); } protected abstract void Do(); } }
//------------------------------------------------------------------------------ // <copyright file="DbGeometry.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner willa // @backupOwner [....] //------------------------------------------------------------------------------ using System.Data.Common.Internal; using System.ComponentModel.DataAnnotations; using System.Data.Spatial.Internal; using System.Diagnostics; using System.Runtime.Serialization; using System.Globalization; namespace System.Data.Spatial { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")] [DataContract] [Serializable] [BindableType] public class DbGeometry { private DbSpatialServices spatialSvcs; private object providerValue; internal DbGeometry(DbSpatialServices spatialServices, object spatialProviderValue) { Debug.Assert(spatialServices != null, "Spatial services are required"); Debug.Assert(spatialProviderValue != null, "Provider value is required"); this.spatialSvcs = spatialServices; this.providerValue = spatialProviderValue; } /// <summary> /// Gets the default coordinate system id (SRID) for geometry values. /// </summary> public static int DefaultCoordinateSystemId { get { return 0; } } /// <summary> /// Gets a representation of this DbGeometry value that is specific to the underlying provider that constructed it. /// </summary> public object ProviderValue { get { return this.providerValue; } } /// <summary> /// Gets or sets a data contract serializable well known representation of this DbGeometry value. /// </summary> [DataMember(Name = "Geometry")] public DbGeometryWellKnownValue WellKnownValue { get { return this.spatialSvcs.CreateWellKnownValue(this); } set { if (this.spatialSvcs != null) { throw SpatialExceptions.WellKnownValueSerializationPropertyNotDirectlySettable(); } DbSpatialServices resolvedServices = DbSpatialServices.Default; this.providerValue = resolvedServices.CreateProviderValue(value); this.spatialSvcs = resolvedServices; } } #region Well Known Binary Static Constructors /// <summary> /// Creates a new <see cref="DbGeometry"/> value based on the specified well known binary value. /// </summary> /// <param name="wellKnownBinary">A byte array that contains a well known binary representation of the geometry value.</param> /// <returns>A new DbGeometry value as defined by the well known binary value with the default geometry coordinate system identifier (<see cref="DbGeometry.DefaultCoordinateSystemId"/>).</returns> /// <exception cref="ArgumentNullException"><paramref name="wellKnownBinary"/> is null.</exception> public static DbGeometry FromBinary(byte[] wellKnownBinary) { wellKnownBinary.CheckNull("wellKnownBinary"); return DbSpatialServices.Default.GeometryFromBinary(wellKnownBinary); } /// <summary> /// Creates a new <see cref="DbGeometry"/> value based on the specified well known binary value and coordinate system identifier (SRID). /// </summary> /// <param name="wellKnownBinary">A byte array that contains a well known binary representation of the geometry value.</param> /// <param name="coordinateSystemId">The identifier of the coordinate system that the new DbGeometry value should use.</param> /// <returns>A new DbGeometry value as defined by the well known binary value with the specified coordinate system identifier.</returns> /// <exception cref="ArgumentNullException"><paramref name="wellKnownBinary"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="coordinateSystemId"/> is not valid.</exception> public static DbGeometry FromBinary(byte[] wellKnownBinary, int coordinateSystemId) { wellKnownBinary.CheckNull("wellKnownBinary"); return DbSpatialServices.Default.GeometryFromBinary(wellKnownBinary, coordinateSystemId); } /// <summary> /// Creates a new <see cref="DbGeometry"/> line value based on the specified well known binary value and coordinate system identifier (SRID). /// </summary> /// <param name="lineWellKnownBinary">A byte array that contains a well known binary representation of the geometry value.</param> /// <param name="coordinateSystemId">The identifier of the coordinate system that the new DbGeometry value should use.</param> /// <returns>A new DbGeometry value as defined by the well known binary value with the specified coordinate system identifier.</returns> /// <exception cref="ArgumentNullException"><paramref name="lineWellKnownBinary"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="coordinateSystemId"/> is not valid.</exception> public static DbGeometry LineFromBinary(byte[] lineWellKnownBinary, int coordinateSystemId) { lineWellKnownBinary.CheckNull("lineWellKnownBinary"); return DbSpatialServices.Default.GeometryLineFromBinary(lineWellKnownBinary, coordinateSystemId); } /// <summary> /// Creates a new <see cref="DbGeometry"/> point value based on the specified well known binary value and coordinate system identifier (SRID). /// </summary> /// <param name="pointWellKnownBinary">A byte array that contains a well known binary representation of the geometry value.</param> /// <param name="coordinateSystemId">The identifier of the coordinate system that the new DbGeometry value should use.</param> /// <returns>A new DbGeometry value as defined by the well known binary value with the specified coordinate system identifier.</returns> /// <exception cref="ArgumentNullException"><paramref name="pointWellKnownBinary"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="coordinateSystemId"/> is not valid.</exception> public static DbGeometry PointFromBinary(byte[] pointWellKnownBinary, int coordinateSystemId) { pointWellKnownBinary.CheckNull("pointWellKnownBinary"); return DbSpatialServices.Default.GeometryPointFromBinary(pointWellKnownBinary, coordinateSystemId); } /// <summary> /// Creates a new <see cref="DbGeometry"/> polygon value based on the specified well known binary value and coordinate system identifier (SRID). /// </summary> /// <param name="polygonWellKnownBinary">A byte array that contains a well known binary representation of the geometry value.</param> /// <param name="coordinateSystemId">The identifier of the coordinate system that the new DbGeometry value should use.</param> /// <returns>A new DbGeometry value as defined by the well known binary value with the specified coordinate system identifier.</returns> /// <exception cref="ArgumentNullException"><paramref name="polygonWellKnownBinary"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="coordinateSystemId"/> is not valid.</exception> public static DbGeometry PolygonFromBinary(byte[] polygonWellKnownBinary, int coordinateSystemId) { polygonWellKnownBinary.CheckNull("polygonWellKnownBinary"); return DbSpatialServices.Default.GeometryPolygonFromBinary(polygonWellKnownBinary, coordinateSystemId); } /// <summary> /// Creates a new <see cref="DbGeometry"/> multi-line value based on the specified well known binary value and coordinate system identifier (SRID). /// </summary> /// <param name="multiLineWellKnownBinary">A byte array that contains a well known binary representation of the geometry value.</param> /// <param name="coordinateSystemId">The identifier of the coordinate system that the new DbGeometry value should use.</param> /// <returns>A new DbGeometry value as defined by the well known binary value with the specified coordinate system identifier.</returns> /// <exception cref="ArgumentNullException"><paramref name="multiLineWellKnownBinary"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="coordinateSystemId"/> is not valid.</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "MultiLine", Justification = "Match OGC, EDM")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi", Justification = "Match OGC, EDM")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "multiLine", Justification = "Match OGC, EDM")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "multi", Justification = "Match OGC, EDM")] public static DbGeometry MultiLineFromBinary(byte[] multiLineWellKnownBinary, int coordinateSystemId) { multiLineWellKnownBinary.CheckNull("multiLineWellKnownBinary"); return DbSpatialServices.Default.GeometryMultiLineFromBinary(multiLineWellKnownBinary, coordinateSystemId); } /// <summary> /// Creates a new <see cref="DbGeometry"/> multi-point value based on the specified well known binary value and coordinate system identifier (SRID). /// </summary> /// <param name="multiPointWellKnownBinary">A byte array that contains a well known binary representation of the geometry value.</param> /// <param name="coordinateSystemId">The identifier of the coordinate system that the new DbGeometry value should use.</param> /// <returns>A new DbGeometry value as defined by the well known binary value with the specified coordinate system identifier.</returns> /// <exception cref="ArgumentNullException"><paramref name="multiPointWellKnownBinary"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="coordinateSystemId"/> is not valid.</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "MultiPoint", Justification = "Match OGC, EDM")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi", Justification = "Match OGC, EDM")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "multiPoint", Justification = "Match OGC, EDM")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "multi", Justification = "Match OGC, EDM")] public static DbGeometry MultiPointFromBinary(byte[] multiPointWellKnownBinary, int coordinateSystemId) { multiPointWellKnownBinary.CheckNull("multiPointWellKnownBinary"); return DbSpatialServices.Default.GeometryMultiPointFromBinary(multiPointWellKnownBinary, coordinateSystemId); } /// <summary> /// Creates a new <see cref="DbGeometry"/> multi-polygon value based on the specified well known binary value and coordinate system identifier (SRID). /// </summary> /// <param name="multiPolygonWellKnownBinary">A byte array that contains a well known binary representation of the geometry value.</param> /// <param name="coordinateSystemId">The identifier of the coordinate system that the new DbGeometry value should use.</param> /// <returns>A new DbGeometry value as defined by the well known binary value with the specified coordinate system identifier.</returns> /// <exception cref="ArgumentNullException"><paramref name="multiPolygonWellKnownBinary"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="coordinateSystemId"/> is not valid.</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi", Justification = "Match OGC, EDM")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "multi", Justification = "Match OGC, EDM")] public static DbGeometry MultiPolygonFromBinary(byte[] multiPolygonWellKnownBinary, int coordinateSystemId) { multiPolygonWellKnownBinary.CheckNull("multiPolygonWellKnownBinary"); return DbSpatialServices.Default.GeometryMultiPolygonFromBinary(multiPolygonWellKnownBinary, coordinateSystemId); } /// <summary> /// Creates a new <see cref="DbGeometry"/> collection value based on the specified well known binary value and coordinate system identifier (SRID). /// </summary> /// <param name="geometryCollectionWellKnownBinary">A byte array that contains a well known binary representation of the geometry value.</param> /// <param name="coordinateSystemId">The identifier of the coordinate system that the new DbGeometry value should use.</param> /// <returns>A new DbGeometry value as defined by the well known binary value with the specified coordinate system identifier.</returns> /// <exception cref="ArgumentNullException"><paramref name="geometryCollectionWellKnownBinary"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="coordinateSystemId"/> is not valid.</exception> public static DbGeometry GeometryCollectionFromBinary(byte[] geometryCollectionWellKnownBinary, int coordinateSystemId) { geometryCollectionWellKnownBinary.CheckNull("geometryCollectionWellKnownBinary"); return DbSpatialServices.Default.GeometryCollectionFromBinary(geometryCollectionWellKnownBinary, coordinateSystemId); } #endregion #region GML Static Constructors /// <summary> /// Creates a new <see cref="DbGeometry"/> value based on the specified Geography Markup Language (GML) value. /// </summary> /// <param name="geometryMarkup">A string that contains a Geography Markup Language (GML) representation of the geometry value.</param> /// <returns>A new DbGeometry value as defined by the GML value with the default geometry coordinate system identifier (SRID) (<see cref="DbGeometry.DefaultCoordinateSystemId"/>).</returns> /// <exception cref="ArgumentNullException"><paramref name="geometryMarkup"/> is null.</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gml")] public static DbGeometry FromGml(string geometryMarkup) { geometryMarkup.CheckNull("geometryMarkup"); return DbSpatialServices.Default.GeometryFromGml(geometryMarkup); } /// <summary> /// Creates a new <see cref="DbGeometry"/> value based on the specified Geography Markup Language (GML) value and coordinate system identifier (SRID). /// </summary> /// <param name="geometryMarkup">A string that contains a Geography Markup Language (GML) representation of the geometry value.</param> /// <param name="coordinateSystemId">The identifier of the coordinate system that the new DbGeometry value should use.</param> /// <returns>A new DbGeometry value as defined by the GML value with the specified coordinate system identifier.</returns> /// <exception cref="ArgumentNullException"><paramref name="geometryMarkup"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="coordinateSystemId"/> is not valid.</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gml")] public static DbGeometry FromGml(string geometryMarkup, int coordinateSystemId) { geometryMarkup.CheckNull("geometryMarkup"); return DbSpatialServices.Default.GeometryFromGml(geometryMarkup, coordinateSystemId); } #endregion #region Well Known Text Static Constructors /// <summary> /// Creates a new <see cref="DbGeometry"/> value based on the specified well known text value. /// </summary> /// <param name="wellKnownText">A string that contains a well known text representation of the geometry value.</param> /// <returns>A new DbGeometry value as defined by the well known text value with the default geometry coordinate system identifier (SRID) (<see cref="DbGeometry.DefaultCoordinateSystemId"/>).</returns> /// <exception cref="ArgumentNullException"><paramref name="wellKnownText"/> is null.</exception> public static DbGeometry FromText(string wellKnownText) { wellKnownText.CheckNull("wellKnownText"); return DbSpatialServices.Default.GeometryFromText(wellKnownText); } /// <summary> /// Creates a new <see cref="DbGeometry"/> value based on the specified well known text value and coordinate system identifier (SRID). /// </summary> /// <param name="wellKnownText">A string that contains a well known text representation of the geometry value.</param> /// <param name="coordinateSystemId">The identifier of the coordinate system that the new DbGeometry value should use.</param> /// <returns>A new DbGeometry value as defined by the well known text value with the specified coordinate system identifier.</returns> /// <exception cref="ArgumentNullException"><paramref name="wellKnownText"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="coordinateSystemId"/> is not valid.</exception> public static DbGeometry FromText(string wellKnownText, int coordinateSystemId) { wellKnownText.CheckNull("wellKnownText"); return DbSpatialServices.Default.GeometryFromText(wellKnownText, coordinateSystemId); } /// <summary> /// Creates a new <see cref="DbGeometry"/> line value based on the specified well known text value and coordinate system identifier (SRID). /// </summary> /// <param name="lineWellKnownText">A string that contains a well known text representation of the geometry value.</param> /// <param name="coordinateSystemId">The identifier of the coordinate system that the new DbGeometry value should use.</param> /// <returns>A new DbGeometry value as defined by the well known text value with the specified coordinate system identifier.</returns> /// <exception cref="ArgumentNullException"><paramref name="lineWellKnownText"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="coordinateSystemId"/> is not valid.</exception> public static DbGeometry LineFromText(string lineWellKnownText, int coordinateSystemId) { lineWellKnownText.CheckNull("lineWellKnownText"); return DbSpatialServices.Default.GeometryLineFromText(lineWellKnownText, coordinateSystemId); } /// <summary> /// Creates a new <see cref="DbGeometry"/> point value based on the specified well known text value and coordinate system identifier (SRID). /// </summary> /// <param name="pointWellKnownText">A string that contains a well known text representation of the geometry value.</param> /// <param name="coordinateSystemId">The identifier of the coordinate system that the new DbGeometry value should use.</param> /// <returns>A new DbGeometry value as defined by the well known text value with the specified coordinate system identifier.</returns> /// <exception cref="ArgumentNullException"><paramref name="pointWellKnownText"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="coordinateSystemId"/> is not valid.</exception> public static DbGeometry PointFromText(string pointWellKnownText, int coordinateSystemId) { pointWellKnownText.CheckNull("pointWellKnownText"); return DbSpatialServices.Default.GeometryPointFromText(pointWellKnownText, coordinateSystemId); } /// <summary> /// Creates a new <see cref="DbGeometry"/> polygon value based on the specified well known text value and coordinate system identifier (SRID). /// </summary> /// <param name="polygonWellKnownText">A string that contains a well known text representation of the geometry value.</param> /// <param name="coordinateSystemId">The identifier of the coordinate system that the new DbGeometry value should use.</param> /// <returns>A new DbGeometry value as defined by the well known text value with the specified coordinate system identifier.</returns> /// <exception cref="ArgumentNullException"><paramref name="polygonWellKnownText"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="coordinateSystemId"/> is not valid.</exception> public static DbGeometry PolygonFromText(string polygonWellKnownText, int coordinateSystemId) { polygonWellKnownText.CheckNull("polygonWellKnownText"); return DbSpatialServices.Default.GeometryPolygonFromText(polygonWellKnownText, coordinateSystemId); } /// <summary> /// Creates a new <see cref="DbGeometry"/> multi-line value based on the specified well known text value and coordinate system identifier (SRID). /// </summary> /// <param name="multiLineWellKnownText">A string that contains a well known text representation of the geometry value.</param> /// <param name="coordinateSystemId">The identifier of the coordinate system that the new DbGeometry value should use.</param> /// <returns>A new DbGeometry value as defined by the well known text value with the specified coordinate system identifier.</returns> /// <exception cref="ArgumentNullException"><paramref name="multiLineWellKnownText"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="coordinateSystemId"/> is not valid.</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "MultiLine", Justification = "Match OGC, EDM")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi", Justification = "Match OGC, EDM")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "multiLine", Justification = "Match OGC, EDM")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "multi", Justification = "Match OGC, EDM")] public static DbGeometry MultiLineFromText(string multiLineWellKnownText, int coordinateSystemId) { multiLineWellKnownText.CheckNull("multiLineWellKnownText"); return DbSpatialServices.Default.GeometryMultiLineFromText(multiLineWellKnownText, coordinateSystemId); } /// <summary> /// Creates a new <see cref="DbGeometry"/> multi-point value based on the specified well known text value and coordinate system identifier (SRID). /// </summary> /// <param name="multiPointWellKnownText">A string that contains a well known text representation of the geometry value.</param> /// <param name="coordinateSystemId">The identifier of the coordinate system that the new DbGeometry value should use.</param> /// <returns>A new DbGeometry value as defined by the well known text value with the specified coordinate system identifier.</returns> /// <exception cref="ArgumentNullException"><paramref name="multiPointWellKnownText"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="coordinateSystemId"/> is not valid.</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "MultiPoint", Justification = "Match OGC, EDM")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi", Justification = "Match OGC, EDM")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "multiPoint", Justification = "Match OGC, EDM")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "multi", Justification = "Match OGC, EDM")] public static DbGeometry MultiPointFromText(string multiPointWellKnownText, int coordinateSystemId) { multiPointWellKnownText.CheckNull("multiPointWellKnownText"); return DbSpatialServices.Default.GeometryMultiPointFromText(multiPointWellKnownText, coordinateSystemId); } /// <summary> /// Creates a new <see cref="DbGeometry"/> multi-polygon value based on the specified well known text value and coordinate system identifier (SRID). /// </summary> /// <param name="multiPolygonWellKnownText">A string that contains a well known text representation of the geometry value.</param> /// <param name="coordinateSystemId">The identifier of the coordinate system that the new DbGeometry value should use.</param> /// <returns>A new DbGeometry value as defined by the well known text value with the specified coordinate system identifier.</returns> /// <exception cref="ArgumentNullException"><paramref name="multiPolygonWellKnownText"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="coordinateSystemId"/> is not valid.</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi", Justification = "Match OGC, EDM")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "multi", Justification = "Match OGC, EDM")] public static DbGeometry MultiPolygonFromText(string multiPolygonWellKnownText, int coordinateSystemId) { multiPolygonWellKnownText.CheckNull("multiPolygonWellKnownText"); return DbSpatialServices.Default.GeometryMultiPolygonFromText(multiPolygonWellKnownText, coordinateSystemId); } /// <summary> /// Creates a new <see cref="DbGeometry"/> collection value based on the specified well known text value and coordinate system identifier (SRID). /// </summary> /// <param name="geometryCollectionWellKnownText">A string that contains a well known text representation of the geometry value.</param> /// <param name="coordinateSystemId">The identifier of the coordinate system that the new DbGeometry value should use.</param> /// <returns>A new DbGeometry value as defined by the well known text value with the specified coordinate system identifier.</returns> /// <exception cref="ArgumentNullException"><paramref name="geometryCollectionWellKnownText"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="coordinateSystemId"/> is not valid.</exception> public static DbGeometry GeometryCollectionFromText(string geometryCollectionWellKnownText, int coordinateSystemId) { geometryCollectionWellKnownText.CheckNull("geometryCollectionWellKnownText"); return DbSpatialServices.Default.GeometryCollectionFromText(geometryCollectionWellKnownText, coordinateSystemId); } #endregion #region Geometry Instance Properties /// </summary> /// Gets the coordinate system identifier (SRID) of the coordinate system used by this DbGeometry value. /// </summary> public int CoordinateSystemId { get { return this.spatialSvcs.GetCoordinateSystemId(this); } } /// </summary> /// Gets the boundary of this DbGeometry value. /// </summary> public DbGeometry Boundary { get { return this.spatialSvcs.GetBoundary(this); } } /// <summary> /// Gets the dimension of the given <see cref="DbGeometry"/> value or, if the value is a collection, the dimension of its largest element. /// </summary> public int Dimension { get { return this.spatialSvcs.GetDimension(this); } } /// <summary> /// Gets the envelope (minimum bounding box) of this DbGeometry value, as a geometry value. /// </summary> public DbGeometry Envelope { get { return this.spatialSvcs.GetEnvelope(this); } } /// </summary> /// Gets the spatial type name, as a string, of this DbGeometry value. /// </summary> public string SpatialTypeName { get { return this.spatialSvcs.GetSpatialTypeName(this); } } /// </summary> /// Gets a Boolean value indicating whether this DbGeometry value represents the empty geometry. /// </summary> public bool IsEmpty { get { return this.spatialSvcs.GetIsEmpty(this); } } /// </summary> /// Gets a Boolean value indicating whether this DbGeometry is simple. /// </summary> public bool IsSimple { get { return this.spatialSvcs.GetIsSimple(this); } } /// </summary> /// Gets a Boolean value indicating whether this DbGeometry value is considered valid. /// </summary> public bool IsValid { get { return this.spatialSvcs.GetIsValid(this); } } #endregion #region Geometry Well Known Format Conversion /// <summary> /// Generates the well known text representation of this DbGeometry value. Includes only X and Y coordinates for points. /// </summary> /// <returns>A string containing the well known text representation of this DbGeometry value.</returns> public string AsText() { return this.spatialSvcs.AsText(this); } /// <summary> /// Generates the well known text representation of this DbGeometry value. Includes X coordinate, Y coordinate, Elevation (Z) and Measure (M) for points. /// </summary> /// <returns>A string containing the well known text representation of this DbGeometry value.</returns> internal string AsTextIncludingElevationAndMeasure() { return this.spatialSvcs.AsTextIncludingElevationAndMeasure(this); } /// <summary> /// Generates the well known binary representation of this DbGeometry value. /// </summary> /// <returns>A byte array containing the well known binary representation of this DbGeometry value.</returns> public byte[] AsBinary() { return this.spatialSvcs.AsBinary(this); } // Non-OGC /// <summary> /// Generates the Geography Markup Language (GML) representation of this DbGeometry value. /// </summary> /// <returns>A string containing the GML representation of this DbGeometry value.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gml")] public string AsGml() { return this.spatialSvcs.AsGml(this); } #endregion #region Geometry Operations - Spatial Relation /// <summary> /// Determines whether this DbGeometry is spatially equal to the specified DbGeometry argument. /// </summary> /// <param name="other">The geometry value that should be compared with this geometry value for equality.</param> /// <returns><c>true</c> if <paramref name="other"/> is spatially equal to this geometry value; otherwise <c>false</c>.</returns> /// <exception cref="ArgumentNullException"><paramref name="other"/> is null.</exception> public bool SpatialEquals(DbGeometry other) { other.CheckNull("other"); return this.spatialSvcs.SpatialEquals(this, other); } /// <summary> /// Determines whether this DbGeometry is spatially disjoint from the specified DbGeometry argument. /// </summary> /// <param name="other">The geometry value that should be compared with this geometry value for disjointness.</param> /// <returns><c>true</c> if <paramref name="other"/> is disjoint from this geometry value; otherwise <c>false</c>.</returns> /// <exception cref="ArgumentNullException"><paramref name="other"/> is null.</exception> public bool Disjoint(DbGeometry other) { other.CheckNull("other"); return this.spatialSvcs.Disjoint(this, other); } /// <summary> /// Determines whether this DbGeometry value spatially intersects the specified DbGeometry argument. /// </summary> /// <param name="other">The geometry value that should be compared with this geometry value for intersection.</param> /// <returns><c>true</c> if <paramref name="other"/> intersects this geometry value; otherwise <c>false</c>.</returns> /// <exception cref="ArgumentNullException"><paramref name="other"/> is null.</exception> public bool Intersects(DbGeometry other) { other.CheckNull("other"); return this.spatialSvcs.Intersects(this, other); } /// <summary> /// Determines whether this DbGeometry value spatially touches the specified DbGeometry argument. /// </summary> /// <param name="other">The geometry value that should be compared with this geometry value.</param> /// <returns><c>true</c> if <paramref name="other"/> touches this geometry value; otherwise <c>false</c>.</returns> /// <exception cref="ArgumentNullException"><paramref name="other"/> is null.</exception> public bool Touches(DbGeometry other) { other.CheckNull("other"); return this.spatialSvcs.Touches(this, other); } /// <summary> /// Determines whether this DbGeometry value spatially crosses the specified DbGeometry argument. /// </summary> /// <param name="other">The geometry value that should be compared with this geometry value.</param> /// <returns><c>true</c> if <paramref name="other"/> crosses this geometry value; otherwise <c>false</c>.</returns> /// <exception cref="ArgumentNullException"><paramref name="other"/> is null.</exception> public bool Crosses(DbGeometry other) { other.CheckNull("other"); return this.spatialSvcs.Crosses(this, other); } /// <summary> /// Determines whether this DbGeometry value is spatially within the specified DbGeometry argument. /// </summary> /// <param name="other">The geometry value that should be compared with this geometry value for containment.</param> /// <returns><c>true</c> if this geometry value is within <paramref name="other"/>; otherwise <c>false</c>.</returns> /// <exception cref="ArgumentNullException"><paramref name="other"/> is null.</exception> public bool Within(DbGeometry other) { other.CheckNull("other"); return this.spatialSvcs.Within(this, other); } /// <summary> /// Determines whether this DbGeometry value spatially contains the specified DbGeometry argument. /// </summary> /// <param name="other">The geometry value that should be compared with this geometry value for containment.</param> /// <returns><c>true</c> if this geometry value contains <paramref name="other"/>; otherwise <c>false</c>.</returns> /// <exception cref="ArgumentNullException"><paramref name="other"/> is null.</exception> public bool Contains(DbGeometry other) { other.CheckNull("other"); return this.spatialSvcs.Contains(this, other); } /// <summary> /// Determines whether this DbGeometry value spatially overlaps the specified DbGeometry argument. /// </summary> /// <param name="other">The geometry value that should be compared with this geometry value for overlap.</param> /// <returns><c>true</c> if this geometry value overlaps <paramref name="other"/>; otherwise <c>false</c>.</returns> /// <exception cref="ArgumentNullException"><paramref name="other"/> is null.</exception> public bool Overlaps(DbGeometry other) { other.CheckNull("other"); return this.spatialSvcs.Overlaps(this, other); } /// <summary> /// Determines whether this DbGeometry value spatially relates to the specified DbGeometry argument according to the /// given Dimensionally Extended Nine-Intersection Model (DE-9IM) intersection pattern. /// </summary> /// <param name="other">The geometry value that should be compared with this geometry value for relation.</param> /// <param name="matrix">A string that contains the text representation of the (DE-9IM) intersection pattern that defines the relation.</param> /// <returns><c>true</c> if this geometry value relates to <paramref name="other"/> according to the specified intersection pattern matrix; otherwise <c>false</c>.</returns> /// <exception cref="ArgumentNullException"><paramref name="other"/> or <paramref name="matrix"/> is null.</exception> public bool Relate(DbGeometry other, string matrix) { other.CheckNull("other"); matrix.CheckNull("matrix"); return this.spatialSvcs.Relate(this, other, matrix); } #endregion #region Geometry Operations - Spatial Analysis /// <summary> /// Creates a geometry value representing all points less than or equal to <paramref name="distance"/> from this DbGeometry value. /// </summary> /// <param name="distance">A double value specifying how far from this geometry value to buffer.</param> /// <returns>A new DbGeometry value representing all points less than or equal to <paramref name="distance"/> from this geometry value.</returns> /// <exception cref="ArgumentNullException"><paramref name="distance"/> is null.</exception> public DbGeometry Buffer(double? distance) { if (!distance.HasValue) { throw EntityUtil.ArgumentNull("distance"); } return this.spatialSvcs.Buffer(this, distance.Value); } /// <summary> /// Computes the distance between the closest points in this DbGeometry value and another DbGeometry value. /// </summary> /// <param name="other">The geometry value for which the distance from this value should be computed.</param> /// <returns>A double value that specifies the distance between the two closest points in this geometry value and <paramref name="other"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="other"/> is null.</exception> public double? Distance(DbGeometry other) { other.CheckNull("other"); return this.spatialSvcs.Distance(this, other); } /// <summary> /// Gets the convex hull of this DbGeometry value as another DbGeometry value. /// </summary> public DbGeometry ConvexHull { get { return this.spatialSvcs.GetConvexHull(this); } } /// <summary> /// Computes the intersection of this DbGeometry value and another DbGeometry value. /// </summary> /// <param name="other">The geometry value for which the intersection with this value should be computed.</param> /// <returns>A new DbGeometry value representing the intersection between this geometry value and <paramref name="other"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="other"/> is null.</exception> public DbGeometry Intersection(DbGeometry other) { other.CheckNull("other"); return this.spatialSvcs.Intersection(this, other); } /// <summary> /// Computes the union of this DbGeometry value and another DbGeometry value. /// </summary> /// <param name="other">The geometry value for which the union with this value should be computed.</param> /// <returns>A new DbGeometry value representing the union between this geometry value and <paramref name="other"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="other"/> is null.</exception> public DbGeometry Union(DbGeometry other) { other.CheckNull("other"); return this.spatialSvcs.Union(this, other); } /// <summary> /// Computes the difference between this DbGeometry value and another DbGeometry value. /// </summary> /// <param name="other">The geometry value for which the difference with this value should be computed.</param> /// <returns>A new DbGeometry value representing the difference between this geometry value and <paramref name="other"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="other"/> is null.</exception> public DbGeometry Difference(DbGeometry other) { other.CheckNull("other"); return this.spatialSvcs.Difference(this, other); } /// <summary> /// Computes the symmetric difference between this DbGeometry value and another DbGeometry value. /// </summary> /// <param name="other">The geometry value for which the symmetric difference with this value should be computed.</param> /// <returns>A new DbGeometry value representing the symmetric difference between this geometry value and <paramref name="other"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="other"/> is null.</exception> public DbGeometry SymmetricDifference(DbGeometry other) { other.CheckNull("other"); return this.spatialSvcs.SymmetricDifference(this, other); } #endregion #region Geometry Collection /// <summary> /// Gets the number of elements in this DbGeometry value, if it represents a geometry collection. /// <returns>The number of elements in this geometry value, if it represents a collection of other geometry values; otherwise <c>null</c>.</returns> /// </summary> public int? ElementCount { get { return this.spatialSvcs.GetElementCount(this); } } /// <summary> /// Returns an element of this DbGeometry value from a specific position, if it represents a geometry collection. /// <param name="index">The position within this geometry value from which the element should be taken.</param> /// <returns>The element in this geometry value at the specified position, if it represents a collection of other geometry values; otherwise <c>null</c>.</returns> /// </summary> public DbGeometry ElementAt(int index) { return this.spatialSvcs.ElementAt(this, index); } #endregion #region Point /// <summary> /// Gets the X coordinate of this DbGeometry value, if it represents a point. /// <returns>The X coordinate value of this geometry value, if it represents a point; otherwise <c>null</c>.</returns> /// </summary> public double? XCoordinate { get { return this.spatialSvcs.GetXCoordinate(this); } } /// <summary> /// Gets the Y coordinate of this DbGeometry value, if it represents a point. /// <returns>The Y coordinate value of this geometry value, if it represents a point; otherwise <c>null</c>.</returns> /// </summary> public double? YCoordinate { get { return this.spatialSvcs.GetYCoordinate(this); } } /// <summary> /// Gets the elevation (Z coordinate) of this DbGeometry value, if it represents a point. /// <returns>The elevation (Z coordinate) of this geometry value, if it represents a point; otherwise <c>null</c>.</returns> /// </summary> public double? Elevation { get { return this.spatialSvcs.GetElevation(this); } } /// <summary> /// Gets the Measure (M coordinate) of this DbGeometry value, if it represents a point. /// <returns>The Measure (M coordinate) value of this geometry value, if it represents a point; otherwise <c>null</c>.</returns> /// </summary> public double? Measure { get { return this.spatialSvcs.GetMeasure(this); } } #endregion #region Curve /// <summary> /// Gets a nullable double value that indicates the length of this DbGeometry value, which may be null if this value does not represent a curve. /// </summary> public double? Length { get { return this.spatialSvcs.GetLength(this); } } /// <summary> /// Gets a DbGeometry value representing the start point of this value, which may be null if this DbGeometry value does not represent a curve. /// </summary> public DbGeometry StartPoint { get { return this.spatialSvcs.GetStartPoint(this); } } /// <summary> /// Gets a DbGeometry value representing the start point of this value, which may be null if this DbGeometry value does not represent a curve. /// </summary> public DbGeometry EndPoint { get { return this.spatialSvcs.GetEndPoint(this); } } /// <summary> /// Gets a nullable Boolean value indicating whether this DbGeometry value is closed, which may be null if this value does not represent a curve. /// </summary> public bool? IsClosed { get { return this.spatialSvcs.GetIsClosed(this); } } /// <summary> /// Gets a nullable Boolean value indicating whether this DbGeometry value is a ring, which may be null if this value does not represent a curve. /// </summary> public bool? IsRing { get { return this.spatialSvcs.GetIsRing(this); } } #endregion #region LineString, Line, LinearRing /// <summary> /// Gets the number of points in this DbGeometry value, if it represents a linestring or linear ring. /// <returns>The number of elements in this geometry value, if it represents a linestring or linear ring; otherwise <c>null</c>.</returns> /// </summary> public int? PointCount { get { return this.spatialSvcs.GetPointCount(this); } } /// <summary> /// Returns an element of this DbGeometry value from a specific position, if it represents a linestring or linear ring. /// <param name="index">The position within this geometry value from which the element should be taken.</param> /// <returns>The element in this geometry value at the specified position, if it represents a linestring or linear ring; otherwise <c>null</c>.</returns> /// </summary> public DbGeometry PointAt(int index) { return this.spatialSvcs.PointAt(this, index); } #endregion #region Surface /// <summary> /// Gets a nullable double value that indicates the area of this DbGeometry value, which may be null if this value does not represent a surface. /// </summary> public double? Area { get { return this.spatialSvcs.GetArea(this); } } /// <summary> /// Gets the DbGeometry value that represents the centroid of this DbGeometry value, which may be null if this value does not represent a surface. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Centroid", Justification = "Naming convention prescribed by OGC specification")] public DbGeometry Centroid { get { return this.spatialSvcs.GetCentroid(this); } } /// <summary> /// Gets a point on the surface of this DbGeometry value, which may be null if this value does not represent a surface. /// </summary> public DbGeometry PointOnSurface { get { return this.spatialSvcs.GetPointOnSurface(this); } } #endregion #region Polygon /// <summary> /// Gets the DbGeometry value that represents the exterior ring of this DbGeometry value, which may be null if this value does not represent a polygon. /// </summary> public DbGeometry ExteriorRing { get { return this.spatialSvcs.GetExteriorRing(this); } } /// <summary> /// Gets the number of interior rings in this DbGeometry value, if it represents a polygon. /// <returns>The number of elements in this geometry value, if it represents a polygon; otherwise <c>null</c>.</returns> /// </summary> public int? InteriorRingCount { get { return this.spatialSvcs.GetInteriorRingCount(this); } } /// <summary> /// Returns an interior ring from this DbGeometry value at a specific position, if it represents a polygon. /// <param name="index">The position within this geometry value from which the interior ring should be taken.</param> /// <returns>The interior ring in this geometry value at the specified position, if it represents a polygon; otherwise <c>null</c>.</returns> /// </summary> public DbGeometry InteriorRingAt(int index) { return this.spatialSvcs.InteriorRingAt(this, index); } #endregion #region ToString /// <summary> /// Returns a string representation of the geometry value. /// </summary> public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "SRID={1};{0}", this.WellKnownValue.WellKnownText ?? base.ToString(), this.CoordinateSystemId); } #endregion } }
#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.Globalization; using Quartz.Util; namespace Quartz.Impl { /// <summary> /// Conveys the detail properties of a given job instance. /// </summary> /// <remarks> /// Quartz does not store an actual instance of a <see cref="IJob" /> type, but /// instead allows you to define an instance of one, through the use of a <see cref="IJobDetail" />. /// <para> /// <see cref="IJob" />s have a name and group associated with them, which /// should uniquely identify them within a single <see cref="IScheduler" />. /// </para> /// <para> /// <see cref="ITrigger" /> s are the 'mechanism' by which <see cref="IJob" /> s /// are scheduled. Many <see cref="ITrigger" /> s can point to the same <see cref="IJob" />, /// but a single <see cref="ITrigger" /> can only point to one <see cref="IJob" />. /// </para> /// </remarks> /// <seealso cref="IJob" /> /// <seealso cref="DisallowConcurrentExecutionAttribute"/> /// <seealso cref="PersistJobDataAfterExecutionAttribute"/> /// <seealso cref="JobDataMap"/> /// <seealso cref="ITrigger"/> /// <author>James House</author> /// <author>Marko Lahma (.NET)</author> [Serializable] public class JobDetailImpl : IJobDetail { private string name; private string group = SchedulerConstants.DefaultGroup; private string description; private Type jobType; private JobDataMap jobDataMap; private bool durability; private bool shouldRecover; [NonSerialized] // we have the key in string fields private JobKey key; /// <summary> /// Create a <see cref="IJobDetail" /> with no specified name or group, and /// the default settings of all the other properties. /// <para> /// Note that the <see cref="Name" />,<see cref="Group" /> and /// <see cref="JobType" /> properties must be set before the job can be /// placed into a <see cref="IScheduler" />. /// </para> /// </summary> public JobDetailImpl() { // do nothing... } /// <summary> /// Create a <see cref="IJobDetail" /> with the given name, default group, and /// the default settings of all the other properties. /// If <see langword="null" />, SchedulerConstants.DefaultGroup will be used. /// </summary> /// <exception cref="ArgumentException"> /// If name is null or empty, or the group is an empty string. /// </exception> public JobDetailImpl(string name, Type jobType) : this(name, null, jobType) { } /// <summary> /// Create a <see cref="IJobDetail" /> with the given name, and group, and /// the default settings of all the other properties. /// If <see langword="null" />, SchedulerConstants.DefaultGroup will be used. /// </summary> /// <exception cref="ArgumentException"> /// If name is null or empty, or the group is an empty string. /// </exception> public JobDetailImpl(string name, string group, Type jobType) { Name = name; Group = group; JobType = jobType; } /// <summary> /// Create a <see cref="IJobDetail" /> with the given name, and group, and /// the given settings of all the other properties. /// </summary> /// <param name="name">The name.</param> /// <param name="group">if <see langword="null" />, SchedulerConstants.DefaultGroup will be used.</param> /// <param name="jobType">Type of the job.</param> /// <param name="isDurable">if set to <c>true</c>, job will be durable.</param> /// <param name="requestsRecovery">if set to <c>true</c>, job will request recovery.</param> /// <exception cref="ArgumentException"> /// ArgumentException if name is null or empty, or the group is an empty string. /// </exception> public JobDetailImpl(string name, string group, Type jobType, bool isDurable, bool requestsRecovery) { Name = name; Group = group; JobType = jobType; Durable = isDurable; RequestsRecovery = requestsRecovery; } /// <summary> /// Get or sets the name of this <see cref="IJob" />. /// </summary> /// <exception cref="ArgumentException"> /// if name is null or empty. /// </exception> public virtual string Name { get { return name; } set { if (value == null || value.Trim().Length == 0) { throw new ArgumentException("Job name cannot be empty."); } name = value; } } /// <summary> /// Get or sets the group of this <see cref="IJob" />. /// If <see langword="null" />, <see cref="SchedulerConstants.DefaultGroup" /> will be used. /// </summary> /// <exception cref="ArgumentException"> /// If the group is an empty string. /// </exception> public virtual string Group { get { return group; } set { if (value != null && value.Trim().Length == 0) { throw new ArgumentException("Group name cannot be empty."); } if (value == null) { value = SchedulerConstants.DefaultGroup; } group = value; } } /// <summary> /// Returns the 'full name' of the <see cref="ITrigger" /> in the format /// "group.name". /// </summary> public virtual string FullName { get { return group + "." + name; } } /// <summary> /// Gets the key. /// </summary> /// <value>The key.</value> public virtual JobKey Key { get { if (key == null) { if (Name == null) { return null; } key = new JobKey(Name, Group); } return key; } set { Name = value != null ? value.Name : null; Group = value != null ? value.Group : null; key = value; } } /// <summary> /// Get or set the description given to the <see cref="IJob" /> instance by its /// creator (if any). /// </summary> /// <remarks> /// May be useful for remembering/displaying the purpose of the job, though the /// description has no meaning to Quartz. /// </remarks> public virtual string Description { get { return description; } set { description = value; } } /// <summary> /// Get or sets the instance of <see cref="IJob" /> that will be executed. /// </summary> /// <exception cref="ArgumentException"> /// if jobType is null or the class is not a <see cref="IJob" />. /// </exception> public virtual Type JobType { get { return jobType; } set { if (value == null) { throw new ArgumentException("Job class cannot be null."); } if (!typeof (IJob).IsAssignableFrom(value)) { throw new ArgumentException("Job class must implement the Job interface."); } jobType = value; } } /// <summary> /// Get or set the <see cref="JobDataMap" /> that is associated with the <see cref="IJob" />. /// </summary> public virtual JobDataMap JobDataMap { get { if (jobDataMap == null) { jobDataMap = new JobDataMap(); } return jobDataMap; } set { jobDataMap = value; } } /// <summary> /// Set whether or not the the <see cref="IScheduler" /> should re-Execute /// the <see cref="IJob" /> if a 'recovery' or 'fail-over' situation is /// encountered. /// <para> /// If not explicitly set, the default value is <see langword="false" />. /// </para> /// </summary> /// <seealso cref="IJobExecutionContext.Recovering" /> public virtual bool RequestsRecovery { set { shouldRecover = value; } get { return shouldRecover; } } /// <summary> /// Whether or not the <see cref="IJob" /> should remain stored after it is /// orphaned (no <see cref="ITrigger" />s point to it). /// <para> /// If not explicitly set, the default value is <see langword="false" />. /// </para> /// </summary> /// <returns> /// <see langword="true" /> if the Job should remain persisted after /// being orphaned. /// </returns> public virtual bool Durable { get { return durability; } set { durability = value; } } /// <summary> /// Whether the associated Job class carries the <see cref="PersistJobDataAfterExecution" /> attribute. /// </summary> public virtual bool PersistJobDataAfterExecution { get { return ObjectUtils.IsAttributePresent(jobType, typeof (PersistJobDataAfterExecutionAttribute)); } } /// <summary> /// Whether the associated Job class carries the <see cref="DisallowConcurrentExecutionAttribute" /> attribute. /// </summary> public virtual bool ConcurrentExecutionDisallowed { get { return ObjectUtils.IsAttributePresent(jobType, typeof (DisallowConcurrentExecutionAttribute)); } } /// <summary> /// Validates whether the properties of the <see cref="IJobDetail" /> are /// valid for submission into a <see cref="IScheduler" />. /// </summary> public virtual void Validate() { if (name == null) { throw new SchedulerException("Job's name cannot be null"); } if (group == null) { throw new SchedulerException("Job's group cannot be null"); } if (jobType == null) { throw new SchedulerException("Job's class cannot be null"); } } /// <summary> /// Return a simple string representation of this object. /// </summary> public override string ToString() { return string.Format( CultureInfo.InvariantCulture, "JobDetail '{0}': jobType: '{1} persistJobDataAfterExecution: {2} concurrentExecutionDisallowed: {3} isDurable: {4} requestsRecovers: {5}", FullName, ((JobType == null) ? null : JobType.FullName), PersistJobDataAfterExecution, ConcurrentExecutionDisallowed, Durable, RequestsRecovery); } /// <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 virtual object Clone() { JobDetailImpl copy; try { copy = (JobDetailImpl) MemberwiseClone(); if (jobDataMap != null) { copy.jobDataMap = (JobDataMap) jobDataMap.Clone(); } } catch (Exception) { throw new Exception("Not Cloneable."); } return copy; } /// <summary> /// Determines whether the specified detail is equal to this instance. /// </summary> /// <param name="detail">The detail to examine.</param> /// <returns> /// <c>true</c> if the specified detail is equal; otherwise, <c>false</c>. /// </returns> protected virtual bool IsEqual(JobDetailImpl detail) { //doesn't consider job's saved data, //durability etc return (detail != null) && (detail.Name == Name) && (detail.Group == Group) && (detail.JobType == JobType); } /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param> /// <returns> /// <see langword="true"/> if the specified <see cref="T:System.Object"/> is equal to the /// current <see cref="T:System.Object"/>; otherwise, <see langword="false"/>. /// </returns> public override bool Equals(object obj) { JobDetailImpl jd = obj as JobDetailImpl; if (jd == null) { return false; } return IsEqual(jd); } /// <summary> /// Checks equality between given job detail and this instance. /// </summary> /// <param name="detail">The detail to compare this instance with.</param> /// <returns></returns> public virtual bool Equals(JobDetailImpl detail) { return IsEqual(detail); } /// <summary> /// Serves as a hash function for a particular type, suitable /// for use in hashing algorithms and data structures like a hash table. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { return FullName.GetHashCode(); } public virtual JobBuilder GetJobBuilder() { JobBuilder b = JobBuilder.Create() .OfType(JobType) .RequestRecovery(RequestsRecovery) .StoreDurably(Durable) .UsingJobData(JobDataMap) .WithDescription(description) .WithIdentity(Key); return b; } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Microsoft.PythonTools.Analysis; using Microsoft.PythonTools.Parsing; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestUtilities; namespace AnalysisTests { public static class TestRunner { static bool HELP, PERF, TRACE, VERBOSE, STDLIB, DJANGO, PATH; static IEnumerable<PythonVersion> VERSIONS; static HashSet<string> OTHER_ARGS; public static int Main(string[] args) { var argset = new HashSet<string>(args, StringComparer.InvariantCultureIgnoreCase); HELP = argset.Count == 0 || (argset.Remove("H") | argset.Remove("HELP")); PERF = argset.Remove("PERF"); VERBOSE = argset.Remove("VERBOSE") | argset.Remove("V"); TRACE = VERBOSE | (argset.Remove("TRACE") | argset.Remove("T")); STDLIB = argset.Remove("STDLIB"); DJANGO = argset.Remove("DJANGO"); PATH = argset.Remove("PATH"); var versionSpecs = new HashSet<string>(argset.Where(arg => Regex.IsMatch(arg, "^V[23][0-9]$", RegexOptions.IgnoreCase)), StringComparer.InvariantCultureIgnoreCase); OTHER_ARGS = new HashSet<string>(argset.Except(versionSpecs), StringComparer.InvariantCultureIgnoreCase); if (versionSpecs.Any()) { VERSIONS = PythonPaths.Versions .Where(v => versionSpecs.Contains(Enum.GetName(typeof(PythonLanguageVersion), v.Version))) .Where(v => v.IsCPython) .ToList(); } else { VERSIONS = PythonPaths.Versions; } if (HELP) { Console.WriteLine(@"AnalysisTest.exe [TRACE] [VERBOSE|V] [test names...] Runs the specified tests. Test names are the short method name only. AnalysisTest.exe [TRACE|VERBOSE|V] [test name ...] AnalysisTest.exe [TRACE|VERBOSE|V] PERF Runs all performance related tests. AnalysisTest.exe [TRACE|VERBOSE|V] STDLIB [V## ...] Runs standard library analyses against the specified versions. Version numbers are V25, V26, V27, V30, V31, V32 or V33. Specifying V27 will only include CPython. Omitting all specifiers will include CPython 2.7 and IronPython 2.7 if installed. AnalysisTest.exe [TRACE|VERBOSE|V] DJANGO [V## ...] Runs Django analyses against the specified versions. AnalysisTest.exe [TRACE|VERBOSE|V] PATH ""library path"" [V## ...] Analyses the specified path with the specified versions. Specifying TRACE will log messages to a file. Specifying VERBOSE or V implies TRACE and will also log detailed analysis information to CSV file. "); return 0; } if (TRACE) { Stream traceOutput; try { traceOutput = new FileStream("AnalysisTests.Trace.txt", FileMode.Create, FileAccess.Write, FileShare.Read); } catch (IOException) { traceOutput = new FileStream(string.Format("AnalysisTests.Trace.{0}.txt", Process.GetCurrentProcess().Id), FileMode.Create, FileAccess.Write, FileShare.Read); } Trace.Listeners.Add(new TextWriterTraceListener(new StreamWriter(traceOutput, Encoding.UTF8))); Trace.AutoFlush = true; if (VERBOSE & !(STDLIB | DJANGO | PATH)) { AnalysisLog.Output = new StreamWriter(new FileStream("AnalysisTests.Trace.csv", FileMode.Create, FileAccess.Write, FileShare.Read), Encoding.UTF8); AnalysisLog.AsCSV = true; } } else { Trace.Listeners.Add(new ConsoleTraceListener()); } int res = 0; if (STDLIB) { res += RunStdLibTests(); } if (DJANGO) { res += RunDjangoTests(); } if (PATH) { res += RunPathTests(); } if (!(STDLIB | DJANGO | PATH)) { Type attrType = PERF ? typeof(PerfMethodAttribute) : typeof(TestMethodAttribute); foreach (var type in typeof(AnalysisTest).Assembly.GetTypes()) { if (type.IsDefined(typeof(TestClassAttribute), false)) { res += RunTests(type, attrType); } } } return res; } private static bool RunOneTest(Action test, string name) { if (Debugger.IsAttached) { return RunOneTestWithoutEH(test, name); } var sw = new Stopwatch(); try { sw.Start(); return RunOneTestWithoutEH(test, name); } catch (Exception e) { sw.Stop(); Console.ForegroundColor = ConsoleColor.Red; #if TRACE Trace.TraceError("Test failed: {0}, {1} ({2}ms)", name, sw.Elapsed, sw.ElapsedMilliseconds); #endif Console.WriteLine("Test failed: {0}, {1} ({2}ms)", name, sw.Elapsed, sw.ElapsedMilliseconds); Console.WriteLine(e); AnalysisLog.Flush(); return false; } } private static bool RunOneTestWithoutEH(Action test, string name) { var sw = new Stopwatch(); sw.Start(); test(); sw.Stop(); Console.ForegroundColor = ConsoleColor.Green; #if TRACE Trace.TraceInformation("Test passed: {0}, {1} ({2}ms)", name, sw.Elapsed, sw.ElapsedMilliseconds); #endif Console.WriteLine("Test passed: {0}, {1} ({2}ms)", name, sw.Elapsed, sw.ElapsedMilliseconds); return true; } private static int RunStdLibTests() { var fg = Console.ForegroundColor; foreach (var ver in VERSIONS) { if (VERBOSE) { try { if (File.Exists(string.Format("AnalysisTests.StdLib.{0}.csv", ver.Version))) { File.Delete(string.Format("AnalysisTests.StdLib.{0}.csv", ver.Version)); } } catch { } } } int failures = 0; foreach (var ver in VERSIONS) { if (VERBOSE) { AnalysisLog.ResetTime(); AnalysisLog.Output = new StreamWriter(new FileStream(string.Format("AnalysisTests.StdLib.{0}.csv", ver.Version), FileMode.Append, FileAccess.Write, FileShare.Read), Encoding.UTF8); AnalysisLog.AsCSV = true; AnalysisLog.Add("StdLib Start", ver.InterpreterPath, ver.Version, DateTime.Now); } if (!RunOneTest(() => { new AnalysisTest().AnalyzeDir(ver.LibPath, ver.Version, new[] { "site-packages" }); }, ver.InterpreterPath)) { failures += 1; } Console.ForegroundColor = fg; if (VERBOSE) { AnalysisLog.Flush(); } IdDispenser.Clear(); } return failures; } private static int RunDjangoTests() { var fg = Console.ForegroundColor; foreach (var ver in VERSIONS) { if (VERBOSE) { try { if (File.Exists(string.Format("AnalysisTests.Django.{0}.csv", ver.Version))) { File.Delete(string.Format("AnalysisTests.Django.{0}.csv", ver.Version)); } } catch { } } } int failures = 0; foreach (var ver in VERSIONS) { var djangoPath = Path.Combine(ver.LibPath, "site-packages", "django"); if (!Directory.Exists(djangoPath)) { Trace.TraceInformation("Path {0} not found; skipping {1}", djangoPath, ver.Version); continue; } if (VERBOSE) { AnalysisLog.ResetTime(); AnalysisLog.Output = new StreamWriter(new FileStream(string.Format("AnalysisTests.Django.{0}.csv", ver.Version), FileMode.Append, FileAccess.Write, FileShare.Read), Encoding.UTF8); AnalysisLog.AsCSV = true; AnalysisLog.Add("Django Start", ver.InterpreterPath, ver.Version, DateTime.Now); } if (!RunOneTest(() => { new AnalysisTest().AnalyzeDir(djangoPath, ver.Version); }, ver.InterpreterPath)) { failures += 1; } Console.ForegroundColor = fg; if (VERBOSE) { AnalysisLog.Flush(); } IdDispenser.Clear(); } return failures; } private static int RunPathTests() { var fg = Console.ForegroundColor; foreach (var ver in VERSIONS) { if (VERBOSE) { try { if (File.Exists(string.Format("AnalysisTests.Path.{0}.csv", ver.Version))) { File.Delete(string.Format("AnalysisTests.Path.{0}.csv", ver.Version)); } } catch { } } } int failures = 0; foreach (var path in OTHER_ARGS) { if (!Directory.Exists(path)) { continue; } foreach (var ver in VERSIONS) { if (VERBOSE) { AnalysisLog.ResetTime(); AnalysisLog.Output = new StreamWriter(new FileStream(string.Format("AnalysisTests.Path.{0}.csv", ver.Version), FileMode.Append, FileAccess.Write, FileShare.Read), Encoding.UTF8); AnalysisLog.AsCSV = true; AnalysisLog.Add("Path Start", path, ver.Version, DateTime.Now); } if (!RunOneTest(() => { new AnalysisTest().AnalyzeDir(path, ver.Version); }, string.Format("{0}: {1}", ver.Version, path))) { failures += 1; } Console.ForegroundColor = fg; if (VERBOSE) { AnalysisLog.Flush(); } IdDispenser.Clear(); } } return failures; } private static int RunTests(Type instType, Type attrType) { var fg = Console.ForegroundColor; int failures = 0; object inst = null; foreach (var mi in instType.GetMethods()) { if ((!OTHER_ARGS.Any() || OTHER_ARGS.Contains(mi.Name)) && mi.IsDefined(attrType, false)) { if (inst == null) { inst = Activator.CreateInstance(instType); Console.WriteLine("Running tests against: {0}", instType.FullName); } if (!RunOneTest(() => { mi.Invoke(inst, new object[0]); }, mi.Name)) { failures += 1; } Console.ForegroundColor = fg; } } if (inst != null) { Console.WriteLine(); if (failures == 0) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("No failures"); } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("{0} failures", failures); } Console.ForegroundColor = fg; } return failures; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections; using System.Diagnostics; namespace System.Xml { // Represents a collection of attributes that can be accessed by name or index. public sealed class XmlAttributeCollection : XmlNamedNodeMap, ICollection { internal XmlAttributeCollection(XmlNode parent) : base(parent) { } // Gets the attribute with the specified index. [System.Runtime.CompilerServices.IndexerName("ItemOf")] public XmlAttribute this[int i] { get { try { return (XmlAttribute)nodes[i]; } catch (ArgumentOutOfRangeException) { throw new IndexOutOfRangeException(SR.Xdom_IndexOutOfRange); } } } // Gets the attribute with the specified name. [System.Runtime.CompilerServices.IndexerName("ItemOf")] public XmlAttribute this[string name] { get { int hash = XmlNameHelper.GetHashCode(name); for (int i = 0; i < nodes.Count; i++) { XmlAttribute node = (XmlAttribute)nodes[i]; if (hash == node.LocalNameHash && name == node.Name) { return node; } } return null; } } // Gets the attribute with the specified LocalName and NamespaceUri. [System.Runtime.CompilerServices.IndexerName("ItemOf")] public XmlAttribute this[string localName, string namespaceURI] { get { int hash = XmlNameHelper.GetHashCode(localName); for (int i = 0; i < nodes.Count; i++) { XmlAttribute node = (XmlAttribute)nodes[i]; if (hash == node.LocalNameHash && localName == node.LocalName && namespaceURI == node.NamespaceURI) { return node; } } return null; } } internal int FindNodeOffset(XmlAttribute node) { for (int i = 0; i < nodes.Count; i++) { XmlAttribute tmp = (XmlAttribute)nodes[i]; if (tmp.LocalNameHash == node.LocalNameHash && tmp.Name == node.Name && tmp.NamespaceURI == node.NamespaceURI) { return i; } } return -1; } // Adds a XmlNode using its Name property public override XmlNode SetNamedItem(XmlNode node) { if (node == null) return null; if (!(node is XmlAttribute)) throw new ArgumentException(SR.Xdom_AttrCol_Object); int offset = FindNodeOffset(node.LocalName, node.NamespaceURI); if (offset == -1) { return InternalAppendAttribute((XmlAttribute)node); } else { XmlNode oldNode = base.RemoveNodeAt(offset); InsertNodeAt(offset, node); return oldNode; } } // Inserts the specified node as the first node in the collection. public XmlAttribute Prepend(XmlAttribute node) { if (node.OwnerDocument != null && node.OwnerDocument != parent.OwnerDocument) throw new ArgumentException(SR.Xdom_NamedNode_Context); if (node.OwnerElement != null) Detach(node); RemoveDuplicateAttribute(node); InsertNodeAt(0, node); return node; } // Inserts the specified node as the last node in the collection. public XmlAttribute Append(XmlAttribute node) { XmlDocument doc = node.OwnerDocument; if (doc == null || doc.IsLoading == false) { if (doc != null && doc != parent.OwnerDocument) { throw new ArgumentException(SR.Xdom_NamedNode_Context); } if (node.OwnerElement != null) { Detach(node); } AddNode(node); } else { base.AddNodeForLoad(node, doc); InsertParentIntoElementIdAttrMap(node); } return node; } // Inserts the specified attribute immediately before the specified reference attribute. public XmlAttribute InsertBefore(XmlAttribute newNode, XmlAttribute refNode) { if (newNode == refNode) return newNode; if (refNode == null) return Append(newNode); if (refNode.OwnerElement != parent) throw new ArgumentException(SR.Xdom_AttrCol_Insert); if (newNode.OwnerDocument != null && newNode.OwnerDocument != parent.OwnerDocument) throw new ArgumentException(SR.Xdom_NamedNode_Context); if (newNode.OwnerElement != null) Detach(newNode); int offset = FindNodeOffset(refNode.LocalName, refNode.NamespaceURI); Debug.Assert(offset != -1); // the if statement above guarantees that the ref node is in the collection int dupoff = RemoveDuplicateAttribute(newNode); if (dupoff >= 0 && dupoff < offset) offset--; InsertNodeAt(offset, newNode); return newNode; } // Inserts the specified attribute immediately after the specified reference attribute. public XmlAttribute InsertAfter(XmlAttribute newNode, XmlAttribute refNode) { if (newNode == refNode) return newNode; if (refNode == null) return Prepend(newNode); if (refNode.OwnerElement != parent) throw new ArgumentException(SR.Xdom_AttrCol_Insert); if (newNode.OwnerDocument != null && newNode.OwnerDocument != parent.OwnerDocument) throw new ArgumentException(SR.Xdom_NamedNode_Context); if (newNode.OwnerElement != null) Detach(newNode); int offset = FindNodeOffset(refNode.LocalName, refNode.NamespaceURI); Debug.Assert(offset != -1); // the if statement above guarantees that the ref node is in the collection int dupoff = RemoveDuplicateAttribute(newNode); if (dupoff >= 0 && dupoff < offset) offset--; InsertNodeAt(offset + 1, newNode); return newNode; } // Removes the specified attribute node from the map. public XmlAttribute Remove(XmlAttribute node) { int cNodes = nodes.Count; for (int offset = 0; offset < cNodes; offset++) { if (nodes[offset] == node) { RemoveNodeAt(offset); return node; } } return null; } // Removes the attribute node with the specified index from the map. public XmlAttribute RemoveAt(int i) { if (i < 0 || i >= Count) return null; return (XmlAttribute)RemoveNodeAt(i); } // Removes all attributes from the map. public void RemoveAll() { int n = Count; while (n > 0) { n--; RemoveAt(n); } } void ICollection.CopyTo(Array array, int index) { if (Count == 0) { return; } int[] indices = new int[1]; // SetValue takes a params array; lifting out the implicit allocation from the loop for (int i = 0, max = Count; i < max; i++, index++) { indices[0] = index; array.SetValue(nodes[i], indices); } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return this; } } int ICollection.Count { get { return base.Count; } } public void CopyTo(XmlAttribute[] array, int index) { for (int i = 0, max = Count; i < max; i++, index++) array[index] = (XmlAttribute)(((XmlNode)nodes[i]).CloneNode(true)); } internal override XmlNode AddNode(XmlNode node) { //should be sure by now that the node doesn't have the same name with an existing node in the collection RemoveDuplicateAttribute((XmlAttribute)node); XmlNode retNode = base.AddNode(node); Debug.Assert(retNode is XmlAttribute); InsertParentIntoElementIdAttrMap((XmlAttribute)node); return retNode; } internal override XmlNode InsertNodeAt(int i, XmlNode node) { XmlNode retNode = base.InsertNodeAt(i, node); InsertParentIntoElementIdAttrMap((XmlAttribute)node); return retNode; } internal override XmlNode RemoveNodeAt(int i) { //remove the node without checking replacement XmlNode retNode = base.RemoveNodeAt(i); Debug.Assert(retNode is XmlAttribute); RemoveParentFromElementIdAttrMap((XmlAttribute)retNode); // after remove the attribute, we need to check if a default attribute node should be created and inserted into the tree XmlAttribute defattr = parent.OwnerDocument.GetDefaultAttribute((XmlElement)parent, retNode.Prefix, retNode.LocalName, retNode.NamespaceURI); if (defattr != null) InsertNodeAt(i, defattr); return retNode; } internal void Detach(XmlAttribute attr) { attr.OwnerElement.Attributes.Remove(attr); } //insert the parent element node into the map internal void InsertParentIntoElementIdAttrMap(XmlAttribute attr) { XmlElement parentElem = parent as XmlElement; if (parentElem != null) { if (parent.OwnerDocument == null) return; XmlName attrname = parent.OwnerDocument.GetIDInfoByElement(parentElem.XmlName); if (attrname != null && attrname.Prefix == attr.XmlName.Prefix && attrname.LocalName == attr.XmlName.LocalName) { parent.OwnerDocument.AddElementWithId(attr.Value, parentElem); //add the element into the hashtable } } } //remove the parent element node from the map when the ID attribute is removed internal void RemoveParentFromElementIdAttrMap(XmlAttribute attr) { XmlElement parentElem = parent as XmlElement; if (parentElem != null) { if (parent.OwnerDocument == null) return; XmlName attrname = parent.OwnerDocument.GetIDInfoByElement(parentElem.XmlName); if (attrname != null && attrname.Prefix == attr.XmlName.Prefix && attrname.LocalName == attr.XmlName.LocalName) { parent.OwnerDocument.RemoveElementWithId(attr.Value, parentElem); //remove the element from the hashtable } } } //the function checks if there is already node with the same name existing in the collection // if so, remove it because the new one will be inserted to replace this one (could be in different position though ) // by the calling function later internal int RemoveDuplicateAttribute(XmlAttribute attr) { int ind = FindNodeOffset(attr.LocalName, attr.NamespaceURI); if (ind != -1) { XmlAttribute at = (XmlAttribute)nodes[ind]; base.RemoveNodeAt(ind); RemoveParentFromElementIdAttrMap(at); } return ind; } internal void ResetParentInElementIdAttrMap(string oldVal, string newVal) { XmlElement parentElem = parent as XmlElement; Debug.Assert(parentElem != null); XmlDocument doc = parent.OwnerDocument; Debug.Assert(doc != null); doc.RemoveElementWithId(oldVal, parentElem); //add the element into the hashtable doc.AddElementWithId(newVal, parentElem); } // WARNING: // For performance reasons, this function does not check // for xml attributes within the collection with the same full name. // This means that any caller of this function must be sure that // a duplicate attribute does not exist. internal XmlAttribute InternalAppendAttribute(XmlAttribute node) { // a duplicate node better not exist Debug.Assert(-1 == FindNodeOffset(node)); XmlNode retNode = base.AddNode(node); Debug.Assert(retNode is XmlAttribute); InsertParentIntoElementIdAttrMap((XmlAttribute)node); return (XmlAttribute)retNode; } } }
/*----------------------------------------------------------------------------------------- C#Prolog -- Copyright (C) 2007-2009 John Pool -- [email protected] Contributions 2009 by Lars Iwer -- [email protected] This library 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 any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for details, or enter 'license.' at the command prompt. -------------------------------------------------------------------------------------------*/ using System; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Specialized; using System.Globalization; #if mswindows using System.Runtime.InteropServices; #endif namespace Prolog { public class Globals { #region static readonly properties public static readonly string DefaultExtension = ".pl"; public static readonly TextReader StdIn = Console.In; public static readonly TextWriter StdOut = Console.Out; #endregion #region private properties private static Hashtable variables = new Hashtable(); // static -> SINGLE ADDRESS SPACE !!!!!!!!! private static Parser currentParser = null; private static TextWriter currentOut = StdOut; // static -> nested tell-constructions may lead to problems private static TextWriter saveCurrentOut; #endregion #region public fields public static Hashtable Variables { get { return variables; } } public static string SpecialAtomChars = @"+-*/\^<=>`~:.?@#$&"; public static CultureInfo CI = CultureInfo.InvariantCulture; public static Hashtable ConsultedFiles = new Hashtable(); public static string ConsultFileName = null; // file being currently consulted public static string ConsultModuleName = null; // name of cutrrent module (if any) in file being consulted public static Parser CurrentParser { get { return currentParser; } set { currentParser = value; } } public static int LineNo { get { return (currentParser == null || currentParser.InQueryMode) ? -1 : currentParser.LineNo; } } public static int ColNo { get { return (currentParser == null) ? -1 : currentParser.ColNo; } } #endregion // named variables in queries public static Term GetVariable(string s) { return (Term)variables[s]; } public static void SetVariable(Term t, string s) { variables[s] = t; // overwrite if exists } public static void EraseVariables() { variables.Clear(); } public static string VariableName(Term t) { t = t.LinkEnd; foreach (DictionaryEntry de in variables) if (de.Value == t) return de.Key.ToString(); return "_"; } public static string Answer { get { StringBuilder s = new StringBuilder(); string ans; Term t; foreach (DictionaryEntry de in variables) if ((t = ((Term)de.Value)).IsUnified) s.Append(String.Format("{0}{1} = {2}", Environment.NewLine, de.Key.ToString(), t)); return ((ans = s.ToString()) == "") ? PrologEngine.YES : ans; } } // output public static void SetStandardOutput() { saveCurrentOut = currentOut; currentOut = StdOut; Console.SetOut(currentOut); } public static bool SetCurrentOutput(string outFile) { TryCloseCurrentOutput(); // first close any open file try { currentOut = saveCurrentOut = new StreamWriter(outFile); Console.SetOut(currentOut); return true; } catch { throw; } } public static bool SetCurrentOutput(StringWriter outStream) { TryCloseCurrentOutput(); // first close any open file try { currentOut = saveCurrentOut = outStream; Console.SetOut(currentOut); return true; } catch { throw; } } public static void RevertToCurrentOutput() { currentOut = saveCurrentOut; Console.SetOut(currentOut); } public static void TryCloseCurrentOutput() { if (currentOut != StdOut) try { currentOut.Close(); } catch { } SetStandardOutput(); } } public struct Utils { private static readonly string logFileName = "PL" + DateTime.Now.ToString("yyyy-MM-dd") + ".log"; private static StreamWriter logFile; private static bool showMode = true; public static string AtomFromVarChar(string s) { return MakeAtom(s.Replace("'", "''")); } public static string RepeatString(string pat, int n) { return (new String('*', n)).Replace("*", pat); // any char will do } public static string Dequote(string s, char c) { int len = s.Length; string cs = c.ToString(); if (len < 2) return s; else if (s[0] == c) return s.Substring(1, len - 2).Replace(cs + cs, cs); else return s; } public static string FileNameFromTerm(Term t, string defExt) { return (t.Value == null) ? null : ExtendedFileName(Dequoted(t.Functor), defExt); } public static string FileNameFromSymbol(string s, string defExt) { return (s == null || s == "") ? null : ExtendedFileName(Dequoted(s), defExt); } public static string Dequoted(string s) { if (s == null || s == "") return s; return (s[0] == '"' || s[0] == '\'') ? Dequote(s, s[0]) : s; } public static string EnsureQuoted(string s) { string result = MakeAtom(s); if (s[0] == '\'') return s; else return '\'' + s + '\''; } public static string ExtendedFileName(string s, string defExt) { try { string fileName = Dequoted(s); if (!Path.HasExtension(fileName)) fileName = Path.ChangeExtension(fileName, defExt); //if (!Path.HasExtension (fileName)) fileName = Path.ChangeExtension (fileName, Globals.DefaultExtension); fileName = Path.GetFullPath(fileName); string dirName = Path.GetDirectoryName(fileName); // if (dirName == "") // { // if (Globals.ConsultDirName != "") // fileName = Globals.ConsultDirName + @"\" + fileName; // use ConsultDirName if it was set // } // else // Globals.ConsultDirName = dirName; return fileName; } catch { return null; } } public static string UnquoteIfUnnecessary(string s) { if (s[0] == '\'') return MakeAtom(s.Substring(1, s.Length - 2)); else return s; } public static string MakeAtom_ic(string a, bool atomic, out FType fType) // don't quote numbers if atomic { fType = FType.atom; if (a == null) PrologIO.Error("MakeAtom_ic -- got null-argument"); if (a == "") return ""; if (Char.IsLower(a[0])) { foreach (char c in a.ToCharArray()) if (!(c == '_' || Char.IsLetterOrDigit(c))) return '\'' + a + '\''; } else if (Char.IsDigit(a[0])) { { bool isNumber = true; bool hasDot = false; foreach (char c in a.ToCharArray()) { if (c == '.') { if (hasDot) { isNumber = false; break; } else hasDot = true; } else if (!Char.IsDigit(c)) { isNumber = false; break; } } if (isNumber) fType = FType.number; return (isNumber && atomic) ? a : '\'' + a + '\''; } } else { foreach (char d in a.ToCharArray()) if (!(Globals.SpecialAtomChars.IndexOf(d) >= 0)) return '\'' + a + '\''; } return a; } public static string MakeAtom_ic(string a, bool atomic) { FType fType; return MakeAtom_ic(a, atomic, out fType); } public static string MakeAtomic(string a) { return MakeAtom_ic(a, true); } public static bool HasAtomShape(string s) { return (s == MakeAtom(s)); } public static string MakeAtom(string a) { return MakeAtom_ic(a, false); } public static Match[] FindRegexMatches(string source, string matchPattern, bool findAllUnique) { Match[] result = null; Regex re = new Regex(matchPattern); //, RegexOptions.Multiline); MatchCollection mc = re.Matches(source); if (findAllUnique) { SortedList uniqueMatches = new SortedList(); for (int i = 0; i < mc.Count; i++) if (!uniqueMatches.ContainsKey(mc[i].Value)) uniqueMatches.Add(mc[i].Value, mc[i]); result = new Match[uniqueMatches.Count]; uniqueMatches.Values.CopyTo(result, 0); } else { result = new Match[mc.Count]; mc.CopyTo(result, 0); } return (result); } public static string WrapWithMargin(string s, string margin, int lenMax) // Break up a string into pieces that are at most lenMax characters long, by // inserting spaces that are at most lenMax positions apart from each other. // If possible, spaces are inserted after 'separator characters'; otherwise // they are simply inserted at each lenMax position. Prefix a margin to the 2nd+ string. { const string separators = @" +-/*^!@():,.;=[]{}<>\"; StringBuilder sb = new StringBuilder(); bool first = true; int p = 0; int rem = s.Length - p; while (rem > lenMax) { // get the position < lenMax of the last separator character int i = s.Substring(p, lenMax).LastIndexOfAny(separators.ToCharArray(), lenMax - 1); int segLen; if (i == -1) segLen = lenMax; else segLen = i + 1; if (first) first = false; else sb.Append(margin); sb.Append(s.Substring(p, segLen)); sb.Append(Environment.NewLine); p += segLen; rem -= segLen; } if (first) first = false; else sb.Append(margin); if (rem != 0) { sb.Append(s.Substring(p)); sb.Append(Environment.NewLine); } return sb.ToString(); } public static void Assert(bool b, string s) { if (!b) throw new Exception(s); } public static string ForceSpaces(string s, int lenMax) // Break up a string into pieces that are at most lenMax characters long, by // inserting spaces that are at most lenMax positions apart from each other. // If possible, spaces are inserted after 'separator characters'; otherwise // they are simply inserted at each lenMax position. { const string separators = " -/:,.;"; if (lenMax < 2) PrologIO.Error("Second argument of wrap must be > 1"); return ForceSpaces(s, lenMax - 1, separators, 0); // 0 is current pos in separators } private static string ForceSpaces(string s, int lenMax, string separators, int i) { int len = s.Length; StringBuilder sb = new StringBuilder(); string blank = Environment.NewLine; // special cases if (len <= lenMax) return s; // nothing to do if (i == separators.Length) // done with all separators -- now simply insert spaces { int r = len; // rest while (r > 0) { sb.Append(s.Substring(len - r, (r > lenMax) ? lenMax : r)); sb.Append(blank); r -= lenMax; } return sb.ToString().Trim(); } // end of special cases string[] words = s.Split(new Char[] { separators[i] }); // split, using the current separator for (int k = 0; k < words.Length; k++) { string t = ForceSpaces(words[k], lenMax, separators, i + 1); // apply the next separator to each word // do not re-place the separator after the last word sb.Append(t + (k == words.Length - 1 ? "" : (separators[i] + blank))); // recursively handle all seps } return sb.ToString(); } // Return the ISO week number for a date. Week 1 of a year is the // first week of the year in which there are more than three days, i.e. // the week in which the first Thursday of the year lies. public static int WeekNo(DateTime date) { // special case: if the date is in a week that starts on December 29, // 30 or 31 (i.e. date day in [sun..wed]), then return 1 if (date.Month == 12 && date.Day >= 29 && date.DayOfWeek <= DayOfWeek.Wednesday) return 1; DateTime jan1 = new DateTime(date.Year, 1, 1); // January 1st DayOfWeek jan1Day = jan1.DayOfWeek; // jan1 is in week 1 if jan1Day is in [sun..wed], since only in that case // there are > 3 days in the week. Calculate the start date of week 1. DateTime startWk1 = (jan1Day <= DayOfWeek.Wednesday) ? jan1.Subtract(new TimeSpan((int)jan1Day, 0, 0, 0)) : jan1.Subtract(new TimeSpan((int)jan1Day - 7, 0, 0, 0)); // Calculate the number of days between the given date and the start // date of week 1 and (integer) divide that by 7. This is the weekno-1. return 1 + (date - startWk1).Days / 7; } #if mswindows // Utils.SendNetBios (Environment.MachineName, Environment.UserName, "hoi"); [DllImport("netapi32.dll")] private static extern short NetMessageBufferSend(IntPtr server, IntPtr recipient, IntPtr reserved, IntPtr message, int size); public static void SendNetBios(string server, string recipient, string text) { int err; IntPtr srv = IntPtr.Zero, rcp = IntPtr.Zero, txt = IntPtr.Zero, res = IntPtr.Zero; try { srv = Marshal.StringToBSTR(server); rcp = Marshal.StringToBSTR(recipient); txt = Marshal.StringToBSTR(text = string.Format("{0}/{1}: {2}", server, recipient, text)); err = NetMessageBufferSend(srv, rcp, res, txt, (text.Length + 1) * 2); } catch (Exception /*e*/) { ; } finally { if (srv != IntPtr.Zero) Marshal.FreeBSTR(srv); if (rcp != IntPtr.Zero) Marshal.FreeBSTR(rcp); if (txt != IntPtr.Zero) Marshal.FreeBSTR(txt); } } // Console private class Constants { // Standard input, output, and error internal const int STD_INPUT_HANDLE = -10; internal const int STD_OUTPUT_HANDLE = -11; internal const int STD_ERROR_HANDLE = -12; // Returned by GetStdHandle when an error occurs internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); } struct COORD { internal short X; internal short Y; public COORD(bool b) // constructor just to get rid of compiler warnings { X = 0; Y = 0; } } struct SMALL_RECT { internal short Left; internal short Top; internal short Right; internal short Bottom; public SMALL_RECT(bool b) // constructor just to get rid of compiler warnings { Left = 0; Top = 0; Right = 0; Bottom = 0; } } struct CONSOLE_SCREEN_BUFFER_INFO { internal COORD dwSize; internal COORD dwCursorPosition; internal ushort wAttributes; internal SMALL_RECT srWindow; internal COORD dwMaximumWindowSize; } [DllImport("kernel32.dll", SetLastError = true)] static extern bool GetConsoleScreenBufferInfo( IntPtr hConsoleOutput, out CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo ); [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr GetStdHandle( int whichHandle ); [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr GetConsoleWindow(); static IntPtr GetHandle(int WhichHandle) { IntPtr h = GetStdHandle(WhichHandle); if (h == Constants.INVALID_HANDLE_VALUE) { switch (WhichHandle) { case Constants.STD_INPUT_HANDLE: throw new Exception("Can't get standard input handle"); //break; case Constants.STD_OUTPUT_HANDLE: throw new Exception("Can't get standard output handle"); //break; case Constants.STD_ERROR_HANDLE: throw new Exception("Can't get standard error handle"); //break; default: throw new Exception("Apparently invalid parameter to GetHandle"); } } return h; } public static short NumCols { get { IntPtr h = GetHandle(Constants.STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO csbi = new CONSOLE_SCREEN_BUFFER_INFO(); if (!GetConsoleScreenBufferInfo(h, out csbi)) return 0; return csbi.dwSize.X; } // set // { // IntPtr h = GetHandle (Constants.STD_OUTPUT_HANDLE); // CONSOLE_SCREEN_BUFFER_INFO csbi = new CONSOLE_SCREEN_BUFFER_INFO(); // // if (!GetConsoleScreenBufferInfo (h, out csbi)) return; // // COORD c = new COORD (); // c.X = value; // c.Y = csbi.dwSize.Y; // SetConsoleScreenBufferSize (h,c); // // return; // } } #endif // Log file public static void SetShow(bool mode) { showMode = mode; } public static void OpenLog() { logFile = new StreamWriter(logFileName); } public static void WriteLogLine(bool abort, string s, params object[] pa) { if (abort) { try { logFile.WriteLine(s, pa); throw new Exception(String.Format(s, pa)); } finally { CloseLog(); } } else { Console.WriteLine(s, pa); logFile.WriteLine(s, pa); } } public static void WriteLogLine(string s, params object[] pa) { WriteLogLine(false, s, pa); } public static void WriteLine(string s, params object[] pa) { WriteLogLine(false, s, pa); } public static void WriteLine(string s) { WriteLogLine(false, s); } public static void Show(string s, params object[] pa) { if (showMode) WriteLogLine(false, s, pa); } public static void Show(string s) { if (showMode) WriteLogLine(false, s); } public static void CloseLog() { logFile.Flush(); logFile.Close(); } } }
--- /dev/null 2016-03-04 11:00:00.000000000 -0500 +++ src/System.Private.Uri/src/SR.cs 2016-03-04 10:59:55.337428000 -0500 @@ -0,0 +1,509 @@ +using System; +using System.Resources; + +namespace FxResources.System.Private.Uri +{ + internal class SR + { + } +} + +namespace System +{ + internal static class SR + { + private static ResourceManager s_resourceManager; + + private const string s_resourcesName = "FxResources.System.Private.Uri.SR"; + + internal static string Argument_InvalidUriSubcomponent + { + get + { + return SR.GetResourceString("Argument_InvalidUriSubcomponent", null); + } + } + + internal static string Argument_ExtraNotValid + { + get + { + return SR.GetResourceString("Argument_ExtraNotValid", null); + } + } + + internal static string Argument_InvalidNormalizationForm + { + get + { + return SR.GetResourceString("Argument_InvalidNormalizationForm", null); + } + } + + internal static string Arg_OutOfMemoryException + { + get + { + return SR.GetResourceString("Arg_OutOfMemoryException", null); + } + } + + internal static string Argument_AddingDuplicate + { + get + { + return SR.GetResourceString("Argument_AddingDuplicate", null); + } + } + + internal static string Argument_IdnBadLabelSize + { + get + { + return SR.GetResourceString("Argument_IdnBadLabelSize", null); + } + } + + internal static string Argument_IdnBadPunycode + { + get + { + return SR.GetResourceString("Argument_IdnBadPunycode", null); + } + } + + internal static string Argument_IdnIllegalName + { + get + { + return SR.GetResourceString("Argument_IdnIllegalName", null); + } + } + + internal static string Argument_InvalidCharSequence + { + get + { + return SR.GetResourceString("Argument_InvalidCharSequence", null); + } + } + + internal static string Argument_InvalidCharSequenceNoIndex + { + get + { + return SR.GetResourceString("Argument_InvalidCharSequenceNoIndex", null); + } + } + + internal static string ArgumentOutOfRange_FileLengthTooBig + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_FileLengthTooBig", null); + } + } + + internal static string ArgumentOutOfRange_Index + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_Index", null); + } + } + + internal static string ArgumentOutOfRange_IndexCountBuffer + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_IndexCountBuffer", null); + } + } + + internal static string ArgumentOutOfRange_NeedNonNegNum + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_NeedNonNegNum", null); + } + } + + internal static string AssertionFailed + { + get + { + return SR.GetResourceString("AssertionFailed", null); + } + } + + internal static string Debug_Fail + { + get + { + return SR.GetResourceString("Debug_Fail", null); + } + } + + internal static string DebugAssertBanner + { + get + { + return SR.GetResourceString("DebugAssertBanner", null); + } + } + + internal static string DebugAssertLongMessage + { + get + { + return SR.GetResourceString("DebugAssertLongMessage", null); + } + } + + internal static string DebugAssertShortMessage + { + get + { + return SR.GetResourceString("DebugAssertShortMessage", null); + } + } + + internal static string IO_FileExists_Name + { + get + { + return SR.GetResourceString("IO_FileExists_Name", null); + } + } + + internal static string IO_FileNotFound + { + get + { + return SR.GetResourceString("IO_FileNotFound", null); + } + } + + internal static string IO_FileNotFound_FileName + { + get + { + return SR.GetResourceString("IO_FileNotFound_FileName", null); + } + } + + internal static string IO_PathNotFound_NoPathName + { + get + { + return SR.GetResourceString("IO_PathNotFound_NoPathName", null); + } + } + + internal static string IO_PathNotFound_Path + { + get + { + return SR.GetResourceString("IO_PathNotFound_Path", null); + } + } + + internal static string IO_PathTooLong + { + get + { + return SR.GetResourceString("IO_PathTooLong", null); + } + } + + internal static string IO_SharingViolation_File + { + get + { + return SR.GetResourceString("IO_SharingViolation_File", null); + } + } + + internal static string IO_SharingViolation_NoFileName + { + get + { + return SR.GetResourceString("IO_SharingViolation_NoFileName", null); + } + } + + internal static string net_uri_AlreadyRegistered + { + get + { + return SR.GetResourceString("net_uri_AlreadyRegistered", null); + } + } + + internal static string net_uri_BadAuthority + { + get + { + return SR.GetResourceString("net_uri_BadAuthority", null); + } + } + + internal static string net_uri_BadAuthorityTerminator + { + get + { + return SR.GetResourceString("net_uri_BadAuthorityTerminator", null); + } + } + + internal static string net_uri_BadFormat + { + get + { + return SR.GetResourceString("net_uri_BadFormat", null); + } + } + + internal static string net_uri_BadHostName + { + get + { + return SR.GetResourceString("net_uri_BadHostName", null); + } + } + + internal static string net_uri_BadPort + { + get + { + return SR.GetResourceString("net_uri_BadPort", null); + } + } + + internal static string net_uri_BadScheme + { + get + { + return SR.GetResourceString("net_uri_BadScheme", null); + } + } + + internal static string net_uri_BadString + { + get + { + return SR.GetResourceString("net_uri_BadString", null); + } + } + + internal static string net_uri_BadUnicodeHostForIdn + { + get + { + return SR.GetResourceString("net_uri_BadUnicodeHostForIdn", null); + } + } + + internal static string net_uri_BadUserPassword + { + get + { + return SR.GetResourceString("net_uri_BadUserPassword", null); + } + } + + internal static string net_uri_CannotCreateRelative + { + get + { + return SR.GetResourceString("net_uri_CannotCreateRelative", null); + } + } + + internal static string net_uri_EmptyUri + { + get + { + return SR.GetResourceString("net_uri_EmptyUri", null); + } + } + + internal static string net_uri_InvalidUriKind + { + get + { + return SR.GetResourceString("net_uri_InvalidUriKind", null); + } + } + + internal static string net_uri_MustRootedPath + { + get + { + return SR.GetResourceString("net_uri_MustRootedPath", null); + } + } + + internal static string net_uri_NeedFreshParser + { + get + { + return SR.GetResourceString("net_uri_NeedFreshParser", null); + } + } + + internal static string net_uri_NotAbsolute + { + get + { + return SR.GetResourceString("net_uri_NotAbsolute", null); + } + } + + internal static string net_uri_NotJustSerialization + { + get + { + return SR.GetResourceString("net_uri_NotJustSerialization", null); + } + } + + internal static string net_uri_PortOutOfRange + { + get + { + return SR.GetResourceString("net_uri_PortOutOfRange", null); + } + } + + internal static string net_uri_SchemeLimit + { + get + { + return SR.GetResourceString("net_uri_SchemeLimit", null); + } + } + + internal static string net_uri_SizeLimit + { + get + { + return SR.GetResourceString("net_uri_SizeLimit", null); + } + } + + internal static string net_uri_UserDrivenParsing + { + get + { + return SR.GetResourceString("net_uri_UserDrivenParsing", null); + } + } + + private static ResourceManager ResourceManager + { + get + { + if (SR.s_resourceManager == null) + { + SR.s_resourceManager = new ResourceManager(SR.ResourceType); + } + return SR.s_resourceManager; + } + } + + internal static Type ResourceType + { + get + { + return typeof(FxResources.System.Private.Uri.SR); + } + } + + internal static string UnauthorizedAccess_IODenied_NoPathName + { + get + { + return SR.GetResourceString("UnauthorizedAccess_IODenied_NoPathName", null); + } + } + + internal static string UnauthorizedAccess_IODenied_Path + { + get + { + return SR.GetResourceString("UnauthorizedAccess_IODenied_Path", null); + } + } + + internal static string UnknownError_Num + { + get + { + return SR.GetResourceString("UnknownError_Num", null); + } + } + + internal static string Format(string resourceFormat, params object[] args) + { + if (args == null) + { + return resourceFormat; + } + if (!SR.UsingResourceKeys()) + { + return string.Format(resourceFormat, args); + } + return string.Concat(resourceFormat, string.Join(", ", args)); + } + + internal static string Format(string resourceFormat, object p1) + { + if (!SR.UsingResourceKeys()) + { + return string.Format(resourceFormat, p1); + } + return string.Join(", ", new object[] { resourceFormat, p1 }); + } + + internal static string Format(string resourceFormat, object p1, object p2) + { + if (!SR.UsingResourceKeys()) + { + return string.Format(resourceFormat, p1, p2); + } + return string.Join(", ", new object[] { resourceFormat, p1, p2 }); + } + + internal static string Format(string resourceFormat, object p1, object p2, object p3) + { + if (!SR.UsingResourceKeys()) + { + return string.Format(resourceFormat, p1, p2, p3); + } + return string.Join(", ", new object[] { resourceFormat, p1, p2, p3 }); + } + + internal static string GetResourceString(string resourceKey, string defaultString) + { + string str = null; + try + { + str = SR.ResourceManager.GetString(resourceKey); + } + catch (MissingManifestResourceException missingManifestResourceException) + { + } + if (defaultString != null && resourceKey.Equals(str)) + { + return defaultString; + } + return str; + } + + private static bool UsingResourceKeys() + { + return false; + } + } +}
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Data; using System.Diagnostics; #pragma warning disable 0618 // ignore obsolete warning about XmlDataDocument namespace System.Xml { internal sealed class DataPointer : IXmlDataVirtualNode { private XmlDataDocument _doc; private XmlNode _node; private DataColumn _column; private bool _fOnValue; private bool _bNeedFoliate = false; private bool _isInUse; internal DataPointer(XmlDataDocument doc, XmlNode node) { _doc = doc; _node = node; _column = null; _fOnValue = false; _bNeedFoliate = false; _isInUse = true; AssertValid(); } internal DataPointer(DataPointer pointer) { _doc = pointer._doc; _node = pointer._node; _column = pointer._column; _fOnValue = pointer._fOnValue; _bNeedFoliate = false; _isInUse = true; AssertValid(); } internal void AddPointer() => _doc.AddPointer(this); // Returns the row element of the region that the pointer points into private XmlBoundElement GetRowElement() { XmlBoundElement rowElem; if (_column != null) { rowElem = _node as XmlBoundElement; Debug.Assert(rowElem != null); Debug.Assert(rowElem.Row != null); return rowElem; } _doc.Mapper.GetRegion(_node, out rowElem); return rowElem; } private DataRow Row { get { XmlBoundElement rowElem = GetRowElement(); if (rowElem == null) { return null; } Debug.Assert(rowElem.Row != null); return rowElem.Row; } } private static bool IsFoliated(XmlNode node) => node != null && node is XmlBoundElement ? ((XmlBoundElement)node).IsFoliated : true; internal void MoveTo(DataPointer pointer) { AssertValid(); // You should not move outside of this document Debug.Assert(_node == _doc || _node.OwnerDocument == _doc); _doc = pointer._doc; _node = pointer._node; _column = pointer._column; _fOnValue = pointer._fOnValue; AssertValid(); } private void MoveTo(XmlNode node) { // You should not move outside of this document Debug.Assert(node == _doc || node.OwnerDocument == _doc); _node = node; _column = null; _fOnValue = false; AssertValid(); } private void MoveTo(XmlNode node, DataColumn column, bool fOnValue) { // You should not move outside of this document Debug.Assert(node == _doc || node.OwnerDocument == _doc); _node = node; _column = column; _fOnValue = fOnValue; AssertValid(); } private DataColumn NextColumn(DataRow row, DataColumn col, bool fAttribute, bool fNulls) { if (row.RowState == DataRowState.Deleted) { return null; } DataTable table = row.Table; DataColumnCollection columns = table.Columns; int iColumn = (col != null) ? col.Ordinal + 1 : 0; int cColumns = columns.Count; DataRowVersion rowVersion = (row.RowState == DataRowState.Detached) ? DataRowVersion.Proposed : DataRowVersion.Current; for (; iColumn < cColumns; iColumn++) { DataColumn c = columns[iColumn]; if (!_doc.IsNotMapped(c) && (c.ColumnMapping == MappingType.Attribute) == fAttribute && (fNulls || !Convert.IsDBNull(row[c, rowVersion]))) { return c; } } return null; } private DataColumn NthColumn(DataRow row, bool fAttribute, int iColumn, bool fNulls) { DataColumn c = null; while ((c = NextColumn(row, c, fAttribute, fNulls)) != null) { if (iColumn == 0) { return c; } iColumn = checked((iColumn - 1)); } return null; } private int ColumnCount(DataRow row, bool fAttribute, bool fNulls) { DataColumn c = null; int count = 0; while ((c = NextColumn(row, c, fAttribute, fNulls)) != null) { count++; } return count; } internal bool MoveToFirstChild() { RealFoliate(); AssertValid(); if (_node == null) { return false; } if (_column != null) { if (_fOnValue) { return false; } _fOnValue = true; return true; } else if (!IsFoliated(_node)) { // find virtual column elements first DataColumn c = NextColumn(Row, null, false, false); if (c != null) { MoveTo(_node, c, _doc.IsTextOnly(c)); return true; } } // look for anything XmlNode n = _doc.SafeFirstChild(_node); if (n != null) { MoveTo(n); return true; } return false; } internal bool MoveToNextSibling() { RealFoliate(); AssertValid(); if (_node != null) { if (_column != null) { if (_fOnValue && !_doc.IsTextOnly(_column)) { return false; } DataColumn c = NextColumn(Row, _column, false, false); if (c != null) { MoveTo(_node, c, false); return true; } XmlNode n = _doc.SafeFirstChild(_node); if (n != null) { MoveTo(n); return true; } } else { XmlNode n = _doc.SafeNextSibling(_node); if (n != null) { MoveTo(n); return true; } } } return false; } internal bool MoveToParent() { RealFoliate(); AssertValid(); if (_node != null) { if (_column != null) { if (_fOnValue && !_doc.IsTextOnly(_column)) { MoveTo(_node, _column, false); return true; } if (_column.ColumnMapping != MappingType.Attribute) { MoveTo(_node, null, false); return true; } } else { XmlNode n = _node.ParentNode; if (n != null) { MoveTo(n); return true; } } } return false; } internal bool MoveToOwnerElement() { RealFoliate(); AssertValid(); if (_node != null) { if (_column != null) { if (_fOnValue || _doc.IsTextOnly(_column) || _column.ColumnMapping != MappingType.Attribute) { return false; } MoveTo(_node, null, false); return true; } else if (_node.NodeType == XmlNodeType.Attribute) { XmlNode n = ((XmlAttribute)_node).OwnerElement; if (n != null) { MoveTo(n, null, false); return true; } } } return false; } internal int AttributeCount { get { RealFoliate(); AssertValid(); if (_node != null) { if (_column == null && _node.NodeType == XmlNodeType.Element) { if (!IsFoliated(_node)) { return ColumnCount(Row, true, false); } else { return _node.Attributes.Count; } } } return 0; } } internal bool MoveToAttribute(int i) { RealFoliate(); AssertValid(); if (i < 0) { return false; } if (_node != null) { if ((_column == null || _column.ColumnMapping == MappingType.Attribute) && _node.NodeType == XmlNodeType.Element) { if (!IsFoliated(_node)) { DataColumn c = NthColumn(Row, true, i, false); if (c != null) { MoveTo(_node, c, false); return true; } } else { XmlNode n = _node.Attributes.Item(i); if (n != null) { MoveTo(n, null, false); return true; } } } } return false; } internal XmlNodeType NodeType { get { RealFoliate(); AssertValid(); if (_node == null) { return XmlNodeType.None; } else if (_column == null) { return _node.NodeType; } else if (_fOnValue) { return XmlNodeType.Text; } else if (_column.ColumnMapping == MappingType.Attribute) { return XmlNodeType.Attribute; } else { return XmlNodeType.Element; } } } internal string LocalName { get { RealFoliate(); AssertValid(); if (_node == null) { return string.Empty; } else if (_column == null) { string name = _node.LocalName; Debug.Assert(name != null); if (IsLocalNameEmpty(_node.NodeType)) { return string.Empty; } return name; } else if (_fOnValue) { return string.Empty; } else { return _doc.NameTable.Add(_column.EncodedColumnName); } } } internal string NamespaceURI { get { RealFoliate(); AssertValid(); if (_node == null) { return string.Empty; } else if (_column == null) { return _node.NamespaceURI; } else if (_fOnValue) { return string.Empty; } else { return _doc.NameTable.Add(_column.Namespace); } } } internal string Name { get { RealFoliate(); AssertValid(); if (_node == null) { return string.Empty; } else if (_column == null) { string name = _node.Name; //Again it could be String.Empty at null position Debug.Assert(name != null); if (IsLocalNameEmpty(_node.NodeType)) { return string.Empty; } return name; } else { string prefix = Prefix; string lname = LocalName; if (prefix != null && prefix.Length > 0) { if (lname != null && lname.Length > 0) { return _doc.NameTable.Add(prefix + ":" + lname); } else { return prefix; } } else { return lname; } } } } private bool IsLocalNameEmpty(XmlNodeType nt) { switch (nt) { case XmlNodeType.None: case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.Comment: case XmlNodeType.Document: case XmlNodeType.DocumentFragment: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.EndElement: case XmlNodeType.EndEntity: return true; case XmlNodeType.Element: case XmlNodeType.Attribute: case XmlNodeType.EntityReference: case XmlNodeType.Entity: case XmlNodeType.ProcessingInstruction: case XmlNodeType.DocumentType: case XmlNodeType.Notation: case XmlNodeType.XmlDeclaration: return false; default: return true; } } internal string Prefix { get { RealFoliate(); AssertValid(); if (_node == null) { return string.Empty; } else if (_column == null) { return _node.Prefix; } else { return string.Empty; } } } internal string Value { get { RealFoliate(); AssertValid(); if (_node == null) { return null; } else if (_column == null) { return _node.Value; } else if (_column.ColumnMapping == MappingType.Attribute || _fOnValue) { DataRow row = Row; DataRowVersion rowVersion = (row.RowState == DataRowState.Detached) ? DataRowVersion.Proposed : DataRowVersion.Current; object value = row[_column, rowVersion]; if (!Convert.IsDBNull(value)) { return _column.ConvertObjectToXml(value); } return null; } else { // column element has no value return null; } } } bool IXmlDataVirtualNode.IsOnNode(XmlNode nodeToCheck) { RealFoliate(); return nodeToCheck == _node; } bool IXmlDataVirtualNode.IsOnColumn(DataColumn col) { RealFoliate(); return col == _column; } internal XmlNode GetNode() => _node; internal bool IsEmptyElement { get { RealFoliate(); AssertValid(); if (_node != null && _column == null) { if (_node.NodeType == XmlNodeType.Element) { return ((XmlElement)_node).IsEmpty; } } return false; } } internal bool IsDefault { get { RealFoliate(); AssertValid(); if (_node != null && _column == null && _node.NodeType == XmlNodeType.Attribute) { return !((XmlAttribute)_node).Specified; } return false; } } void IXmlDataVirtualNode.OnFoliated(XmlNode foliatedNode) { // update the pointer if the element node has been foliated if (_node == foliatedNode) { // if already on this node, nothing to do! if (_column == null) { return; } _bNeedFoliate = true; } } internal void RealFoliate() { if (!_bNeedFoliate) { return; } XmlNode n = null; if (_doc.IsTextOnly(_column)) { n = _node.FirstChild; } else { if (_column.ColumnMapping == MappingType.Attribute) { n = _node.Attributes.GetNamedItem(_column.EncodedColumnName, _column.Namespace); } else { for (n = _node.FirstChild; n != null; n = n.NextSibling) { if (n.LocalName == _column.EncodedColumnName && n.NamespaceURI == _column.Namespace) break; } } if (n != null && _fOnValue) { n = n.FirstChild; } } if (n == null) { throw new InvalidOperationException(SR.DataDom_Foliation); } // Cannot use MoveTo( n ); b/c the initial state for MoveTo is invalid (region is foliated but this is not) _node = n; _column = null; _fOnValue = false; AssertValid(); _bNeedFoliate = false; } //for the 6 properties below, only when the this.column == null that the nodetype could be XmlDeclaration node internal string PublicId { get { XmlNodeType nt = NodeType; switch (nt) { case XmlNodeType.DocumentType: { Debug.Assert(_column == null); return ((XmlDocumentType)(_node)).PublicId; } case XmlNodeType.Entity: { Debug.Assert(_column == null); return ((XmlEntity)(_node)).PublicId; } case XmlNodeType.Notation: { Debug.Assert(_column == null); return ((XmlNotation)(_node)).PublicId; } } return null; } } internal string SystemId { get { XmlNodeType nt = NodeType; switch (nt) { case XmlNodeType.DocumentType: { Debug.Assert(_column == null); return ((XmlDocumentType)(_node)).SystemId; } case XmlNodeType.Entity: { Debug.Assert(_column == null); return ((XmlEntity)(_node)).SystemId; } case XmlNodeType.Notation: { Debug.Assert(_column == null); return ((XmlNotation)(_node)).SystemId; } } return null; } } internal string InternalSubset { get { if (NodeType == XmlNodeType.DocumentType) { Debug.Assert(_column == null); return ((XmlDocumentType)(_node)).InternalSubset; } return null; } } internal XmlDeclaration Declaration { get { XmlNode child = _doc.SafeFirstChild(_doc); if (child != null && child.NodeType == XmlNodeType.XmlDeclaration) return (XmlDeclaration)child; return null; } } internal string Encoding { get { if (NodeType == XmlNodeType.XmlDeclaration) { Debug.Assert(_column == null); return ((XmlDeclaration)(_node)).Encoding; } else if (NodeType == XmlNodeType.Document) { XmlDeclaration dec = Declaration; if (dec != null) { return dec.Encoding; } } return null; } } internal string Standalone { get { if (NodeType == XmlNodeType.XmlDeclaration) { Debug.Assert(_column == null); return ((XmlDeclaration)(_node)).Standalone; } else if (NodeType == XmlNodeType.Document) { XmlDeclaration dec = Declaration; if (dec != null) { return dec.Standalone; } } return null; } } internal string Version { get { if (NodeType == XmlNodeType.XmlDeclaration) { Debug.Assert(_column == null); return ((XmlDeclaration)(_node)).Version; } else if (NodeType == XmlNodeType.Document) { XmlDeclaration dec = Declaration; if (dec != null) return dec.Version; } return null; } } [Conditional("DEBUG")] private void AssertValid() { // This pointer must be int the document list if (_column != null) { // We must be on a de-foliated region XmlBoundElement rowElem = _node as XmlBoundElement; Debug.Assert(rowElem != null); DataRow row = rowElem.Row; Debug.Assert(row != null); ElementState state = rowElem.ElementState; Debug.Assert(state == ElementState.Defoliated, "Region is accessed using column, but it's state is FOLIATED"); // We cannot be on a column for which the value is DBNull DataRowVersion rowVersion = (row.RowState == DataRowState.Detached) ? DataRowVersion.Proposed : DataRowVersion.Current; Debug.Assert(!Convert.IsDBNull(row[_column, rowVersion])); // If we are on the Text column, we should always have fOnValue == true Debug.Assert((_column.ColumnMapping == MappingType.SimpleContent) ? (_fOnValue == true) : true); } } bool IXmlDataVirtualNode.IsInUse() => _isInUse; internal void SetNoLongerUse() { _node = null; _column = null; _fOnValue = false; _bNeedFoliate = false; _isInUse = false; } } }
namespace android.app { [global::MonoJavaBridge.JavaClass()] public partial class SearchManager : java.lang.Object, android.content.DialogInterface_OnDismissListener, android.content.DialogInterface_OnCancelListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected SearchManager(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaInterface(typeof(global::android.app.SearchManager.OnCancelListener_))] public partial interface OnCancelListener : global::MonoJavaBridge.IJavaObject { void onCancel(); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.app.SearchManager.OnCancelListener))] internal sealed partial class OnCancelListener_ : java.lang.Object, OnCancelListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal OnCancelListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; void android.app.SearchManager.OnCancelListener.onCancel() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.SearchManager.OnCancelListener_.staticClass, "onCancel", "()V", ref global::android.app.SearchManager.OnCancelListener_._m0); } static OnCancelListener_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.app.SearchManager.OnCancelListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/SearchManager$OnCancelListener")); } } public delegate void OnCancelListenerDelegate(); internal partial class OnCancelListenerDelegateWrapper : java.lang.Object, OnCancelListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected OnCancelListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public OnCancelListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.app.SearchManager.OnCancelListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero) global::android.app.SearchManager.OnCancelListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.app.SearchManager.OnCancelListenerDelegateWrapper.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.SearchManager.OnCancelListenerDelegateWrapper.staticClass, global::android.app.SearchManager.OnCancelListenerDelegateWrapper._m0); Init(@__env, handle); } static OnCancelListenerDelegateWrapper() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.app.SearchManager.OnCancelListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/SearchManager_OnCancelListenerDelegateWrapper")); } } internal partial class OnCancelListenerDelegateWrapper { private OnCancelListenerDelegate myDelegate; public void onCancel() { myDelegate(); } public static implicit operator OnCancelListenerDelegateWrapper(OnCancelListenerDelegate d) { global::android.app.SearchManager.OnCancelListenerDelegateWrapper ret = new global::android.app.SearchManager.OnCancelListenerDelegateWrapper(); ret.myDelegate = d; global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret); return ret; } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.app.SearchManager.OnDismissListener_))] public partial interface OnDismissListener : global::MonoJavaBridge.IJavaObject { void onDismiss(); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.app.SearchManager.OnDismissListener))] internal sealed partial class OnDismissListener_ : java.lang.Object, OnDismissListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal OnDismissListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; void android.app.SearchManager.OnDismissListener.onDismiss() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.SearchManager.OnDismissListener_.staticClass, "onDismiss", "()V", ref global::android.app.SearchManager.OnDismissListener_._m0); } static OnDismissListener_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.app.SearchManager.OnDismissListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/SearchManager$OnDismissListener")); } } public delegate void OnDismissListenerDelegate(); internal partial class OnDismissListenerDelegateWrapper : java.lang.Object, OnDismissListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected OnDismissListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public OnDismissListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.app.SearchManager.OnDismissListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero) global::android.app.SearchManager.OnDismissListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.app.SearchManager.OnDismissListenerDelegateWrapper.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.SearchManager.OnDismissListenerDelegateWrapper.staticClass, global::android.app.SearchManager.OnDismissListenerDelegateWrapper._m0); Init(@__env, handle); } static OnDismissListenerDelegateWrapper() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.app.SearchManager.OnDismissListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/SearchManager_OnDismissListenerDelegateWrapper")); } } internal partial class OnDismissListenerDelegateWrapper { private OnDismissListenerDelegate myDelegate; public void onDismiss() { myDelegate(); } public static implicit operator OnDismissListenerDelegateWrapper(OnDismissListenerDelegate d) { global::android.app.SearchManager.OnDismissListenerDelegateWrapper ret = new global::android.app.SearchManager.OnDismissListenerDelegateWrapper(); ret.myDelegate = d; global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret); return ret; } } private static global::MonoJavaBridge.MethodId _m0; public virtual void startSearch(java.lang.String arg0, bool arg1, android.content.ComponentName arg2, android.os.Bundle arg3, bool arg4) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.SearchManager.staticClass, "startSearch", "(Ljava/lang/String;ZLandroid/content/ComponentName;Landroid/os/Bundle;Z)V", ref global::android.app.SearchManager._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } private static global::MonoJavaBridge.MethodId _m1; public virtual void triggerSearch(java.lang.String arg0, android.content.ComponentName arg1, android.os.Bundle arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.SearchManager.staticClass, "triggerSearch", "(Ljava/lang/String;Landroid/content/ComponentName;Landroid/os/Bundle;)V", ref global::android.app.SearchManager._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m2; public virtual void setOnCancelListener(android.app.SearchManager.OnCancelListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.SearchManager.staticClass, "setOnCancelListener", "(Landroid/app/SearchManager$OnCancelListener;)V", ref global::android.app.SearchManager._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setOnCancelListener(global::android.app.SearchManager.OnCancelListenerDelegate arg0) { setOnCancelListener((global::android.app.SearchManager.OnCancelListenerDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m3; public virtual void setOnDismissListener(android.app.SearchManager.OnDismissListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.SearchManager.staticClass, "setOnDismissListener", "(Landroid/app/SearchManager$OnDismissListener;)V", ref global::android.app.SearchManager._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setOnDismissListener(global::android.app.SearchManager.OnDismissListenerDelegate arg0) { setOnDismissListener((global::android.app.SearchManager.OnDismissListenerDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m4; public virtual void onCancel(android.content.DialogInterface arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.SearchManager.staticClass, "onCancel", "(Landroid/content/DialogInterface;)V", ref global::android.app.SearchManager._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m5; public virtual void onDismiss(android.content.DialogInterface arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.SearchManager.staticClass, "onDismiss", "(Landroid/content/DialogInterface;)V", ref global::android.app.SearchManager._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m6; public virtual void stopSearch() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.app.SearchManager.staticClass, "stopSearch", "()V", ref global::android.app.SearchManager._m6); } private static global::MonoJavaBridge.MethodId _m7; public virtual global::android.app.SearchableInfo getSearchableInfo(android.content.ComponentName arg0) { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.app.SearchableInfo>(this, global::android.app.SearchManager.staticClass, "getSearchableInfo", "(Landroid/content/ComponentName;)Landroid/app/SearchableInfo;", ref global::android.app.SearchManager._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.app.SearchableInfo; } public new global::java.util.List SearchablesInGlobalSearch { get { return getSearchablesInGlobalSearch(); } } private static global::MonoJavaBridge.MethodId _m8; public virtual global::java.util.List getSearchablesInGlobalSearch() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::android.app.SearchManager.staticClass, "getSearchablesInGlobalSearch", "()Ljava/util/List;", ref global::android.app.SearchManager._m8) as java.util.List; } public static char MENU_KEY { get { return 's'; } } public static int MENU_KEYCODE { get { return 47; } } public static global::java.lang.String QUERY { get { return "query"; } } public static global::java.lang.String USER_QUERY { get { return "user_query"; } } public static global::java.lang.String APP_DATA { get { return "app_data"; } } public static global::java.lang.String ACTION_KEY { get { return "action_key"; } } public static global::java.lang.String EXTRA_DATA_KEY { get { return "intent_extra_data_key"; } } public static global::java.lang.String EXTRA_SELECT_QUERY { get { return "select_query"; } } public static global::java.lang.String CURSOR_EXTRA_KEY_IN_PROGRESS { get { return "in_progress"; } } public static global::java.lang.String ACTION_MSG { get { return "action_msg"; } } public static global::java.lang.String SUGGEST_URI_PATH_QUERY { get { return "search_suggest_query"; } } public static global::java.lang.String SUGGEST_MIME_TYPE { get { return "vnd.android.cursor.dir/vnd.android.search.suggest"; } } public static global::java.lang.String SUGGEST_URI_PATH_SHORTCUT { get { return "search_suggest_shortcut"; } } public static global::java.lang.String SHORTCUT_MIME_TYPE { get { return "vnd.android.cursor.item/vnd.android.search.suggest"; } } public static global::java.lang.String SUGGEST_COLUMN_FORMAT { get { return "suggest_format"; } } public static global::java.lang.String SUGGEST_COLUMN_TEXT_1 { get { return "suggest_text_1"; } } public static global::java.lang.String SUGGEST_COLUMN_TEXT_2 { get { return "suggest_text_2"; } } public static global::java.lang.String SUGGEST_COLUMN_TEXT_2_URL { get { return "suggest_text_2_url"; } } public static global::java.lang.String SUGGEST_COLUMN_ICON_1 { get { return "suggest_icon_1"; } } public static global::java.lang.String SUGGEST_COLUMN_ICON_2 { get { return "suggest_icon_2"; } } public static global::java.lang.String SUGGEST_COLUMN_INTENT_ACTION { get { return "suggest_intent_action"; } } public static global::java.lang.String SUGGEST_COLUMN_INTENT_DATA { get { return "suggest_intent_data"; } } public static global::java.lang.String SUGGEST_COLUMN_INTENT_EXTRA_DATA { get { return "suggest_intent_extra_data"; } } public static global::java.lang.String SUGGEST_COLUMN_INTENT_DATA_ID { get { return "suggest_intent_data_id"; } } public static global::java.lang.String SUGGEST_COLUMN_QUERY { get { return "suggest_intent_query"; } } public static global::java.lang.String SUGGEST_COLUMN_SHORTCUT_ID { get { return "suggest_shortcut_id"; } } public static global::java.lang.String SUGGEST_COLUMN_SPINNER_WHILE_REFRESHING { get { return "suggest_spinner_while_refreshing"; } } public static global::java.lang.String SUGGEST_NEVER_MAKE_SHORTCUT { get { return "_-1"; } } public static global::java.lang.String SUGGEST_PARAMETER_LIMIT { get { return "limit"; } } public static global::java.lang.String INTENT_ACTION_GLOBAL_SEARCH { get { return "android.search.action.GLOBAL_SEARCH"; } } public static global::java.lang.String INTENT_ACTION_SEARCH_SETTINGS { get { return "android.search.action.SEARCH_SETTINGS"; } } public static global::java.lang.String INTENT_ACTION_WEB_SEARCH_SETTINGS { get { return "android.search.action.WEB_SEARCH_SETTINGS"; } } public static global::java.lang.String INTENT_ACTION_SEARCHABLES_CHANGED { get { return "android.search.action.SEARCHABLES_CHANGED"; } } public static global::java.lang.String INTENT_ACTION_SEARCH_SETTINGS_CHANGED { get { return "android.search.action.SETTINGS_CHANGED"; } } static SearchManager() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.app.SearchManager.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/SearchManager")); } } }
// Copyright (c) 2014 Robert Rouhani <[email protected]> and other contributors (see CONTRIBUTORS file). // Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE using System.ComponentModel; using System.Drawing.Design; using System.Windows.Forms; using System.Windows.Forms.Design; using System; namespace SharpNav { /// <summary> /// The following two classes are made for the GUI application purpose /// </summary> class NavMeshGenerationSettingsForm : Form { private PropertyGrid p; private Button okButton; public NavMeshGenerationSettingsForm() { p = new PropertyGrid(); Controls.Add(p); p.Dock = DockStyle.Fill; okButton = new Button(); okButton.Text = "OK"; okButton.Dock = DockStyle.Bottom; okButton.DialogResult = DialogResult.OK; Controls.Add(okButton); } public NavMeshGenerationSettings NavSetting { get { return p.SelectedObject as NavMeshGenerationSettings; } set { p.SelectedObject = value; } } } class NavMeshGenerationSettingsEditor : UITypeEditor { public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(ITypeDescriptorContext context, System.IServiceProvider provider, object value) { IWindowsFormsEditorService svc = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService; NavMeshGenerationSettings config = value as NavMeshGenerationSettings; using (NavMeshGenerationSettingsForm form = new NavMeshGenerationSettingsForm()) { form.NavSetting = config; if (svc.ShowDialog(form) == DialogResult.OK) { config = form.NavSetting; // update object } } return value; // can also replace the wrapper object here } } /// <summary> /// Contains all the settings necessary to convert a mesh to a navmesh. /// </summary> [Editor(typeof(NavMeshGenerationSettingsEditor), typeof(UITypeEditor))] [TypeConverter(typeof(ExpandableObjectConverter))] public class NavMeshGenerationSettings { /// <summary> /// Prevents a default instance of the <see cref="NavMeshGenerationSettings"/> class from being created. /// Use <see cref="Default"/> instead. /// </summary> public NavMeshGenerationSettings() { //TODO now that this is public set reasonable defaults. } /// <summary> /// Gets the "default" generation settings for a model where 1 unit represents 1 meter. /// </summary> public static NavMeshGenerationSettings Default { get { //TODO rename this property to something more descriptive. var settings = new NavMeshGenerationSettings(); settings.CellSize = 0.3f; settings.CellHeight = 0.2f; settings.MaxClimb = 0.9f; settings.AgentHeight = 2.0f; settings.AgentRadius = 0.6f; settings.MinRegionSize = 8; settings.MergedRegionSize = 20; settings.MaxEdgeLength = 12; settings.MaxEdgeError = 1.8f; settings.VertsPerPoly = 6; settings.SampleDistance = 6; settings.MaxSampleError = 1; settings.BuildBoundingVolumeTree = true; return settings; } } /// <summary> /// Gets or sets the size of a cell in the X and Z axes in world units. /// </summary> public float CellSize { get; set; } /// <summary> /// Gets or sets the height of a cell in world units. /// </summary> public float CellHeight { get; set; } /// <summary> /// Gets or sets the maximum climb height. /// </summary> public float MaxClimb { get; set; } /// <summary> /// Gets or sets the height of the agents traversing the <see cref="NavMesh"/>. /// </summary> public float AgentHeight { get; set; } /// <summary> /// Gets or sets the radius of the agents traversing the <see cref="NavMesh"/>. /// </summary> public float AgentRadius { get; set; } /// <summary> /// Gets or sets the minimum number of spans that can form a region. Any less than this, and they will be /// merged with another region. /// </summary> public int MinRegionSize { get; set; } /// <summary> /// Gets or sets the size of the merged regions /// </summary> public int MergedRegionSize { get; set; } /// <summary> /// Gets or sets the maximum edge length allowed /// </summary> public int MaxEdgeLength { get; set; } /// <summary> /// Gets or sets the maximum error allowed /// </summary> public float MaxEdgeError { get; set; } /// <summary> /// Gets or sets the flags that determine how the <see cref="ContourSet"/> is generated. /// </summary> public ContourBuildFlags ContourFlags { get; set; } /// <summary> /// Gets or sets the number of vertices a polygon can have. /// </summary> public int VertsPerPoly { get; set; } /// <summary> /// Gets or sets the sampling distance for the PolyMeshDetail /// </summary> public int SampleDistance { get; set; } /// <summary> /// Gets or sets the maximium error allowed in sampling for the PolyMeshDetail /// </summary> public int MaxSampleError { get; set; } /// <summary> /// Gets or sets a value indicating whether a bounding volume tree is generated for the mesh. /// </summary> public bool BuildBoundingVolumeTree { get; set; } /// <summary> /// Gets the height of the agents traversing the <see cref="NavMesh"/> in voxel (cell) units. /// </summary> public int VoxelAgentHeight { get { return (int)(AgentHeight / CellHeight); } } /// <summary> /// Gets the maximum clim height in voxel (cell) units. /// </summary> public int VoxelMaxClimb { get { return (int)(MaxClimb / CellHeight); } } /// <summary> /// Gets the radius of the agents traversing the <see cref="NavMesh"/> in voxel (cell) units. /// </summary> public int VoxelAgentRadius { get { return (int)(AgentRadius / CellHeight); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Data.Common; using System.Diagnostics; using System.Runtime.InteropServices; using System.Globalization; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace System.Data.SqlTypes { /// <summary> /// Represents the date and time data ranging in value /// from January 1, 1753 to December 31, 9999 to an accuracy of 3.33 milliseconds /// to be stored in or retrieved from a database. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] [XmlSchemaProvider("GetXsdType")] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct SqlDateTime : INullable, IComparable, IXmlSerializable { private bool m_fNotNull; // false if null. Do not rename (binary serialization) private int m_day; // Day from 1900/1/1, could be negative. Range: Jan 1 1753 - Dec 31 9999. Do not rename (binary serialization) private int m_time; // Time in the day in term of ticks. Do not rename (binary serialization) // Constants // Number of (100ns) ticks per time unit private const double s_SQLTicksPerMillisecond = 0.3; public static readonly int SQLTicksPerSecond = 300; public static readonly int SQLTicksPerMinute = SQLTicksPerSecond * 60; public static readonly int SQLTicksPerHour = SQLTicksPerMinute * 60; private static readonly int s_SQLTicksPerDay = SQLTicksPerHour * 24; private const long s_ticksPerSecond = TimeSpan.TicksPerMillisecond * 1000; private static readonly DateTime s_SQLBaseDate = new DateTime(1900, 1, 1); private static readonly long s_SQLBaseDateTicks = s_SQLBaseDate.Ticks; private const int s_minYear = 1753; // Jan 1 1753 private const int s_maxYear = 9999; // Dec 31 9999 private const int s_minDay = -53690; // Jan 1 1753 private const int s_maxDay = 2958463; // Dec 31 9999 is this many days from Jan 1 1900 private const int s_minTime = 0; // 00:00:0:000PM private static readonly int s_maxTime = s_SQLTicksPerDay - 1; // = 25919999, 11:59:59:997PM private const int s_dayBase = 693595; // Jan 1 1900 is this many days from Jan 1 0001 private static readonly int[] s_daysToMonth365 = new int[] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}; private static readonly int[] s_daysToMonth366 = new int[] { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366}; private static readonly DateTime s_minDateTime = new DateTime(1753, 1, 1); private static readonly DateTime s_maxDateTime = DateTime.MaxValue; private static readonly TimeSpan s_minTimeSpan = s_minDateTime.Subtract(s_SQLBaseDate); private static readonly TimeSpan s_maxTimeSpan = s_maxDateTime.Subtract(s_SQLBaseDate); private const string s_ISO8601_DateTimeFormat = "yyyy-MM-ddTHH:mm:ss.fff"; // These formats are valid styles in SQL Server (style 9, 12, 13, 14) // but couldn't be recognized by the default parse. Needs to call // ParseExact in addition to recognize them. private static readonly string[] s_dateTimeFormats = { "MMM d yyyy hh:mm:ss:ffftt", "MMM d yyyy hh:mm:ss:fff", "d MMM yyyy hh:mm:ss:ffftt", "d MMM yyyy hh:mm:ss:fff", "hh:mm:ss:ffftt", "hh:mm:ss:fff", "yyMMdd", "yyyyMMdd" }; private const DateTimeStyles x_DateTimeStyle = DateTimeStyles.AllowWhiteSpaces; // construct a Null private SqlDateTime(bool fNull) { m_fNotNull = false; m_day = 0; m_time = 0; } public SqlDateTime(DateTime value) { this = FromDateTime(value); } public SqlDateTime(int year, int month, int day) : this(year, month, day, 0, 0, 0, 0.0) { } public SqlDateTime(int year, int month, int day, int hour, int minute, int second) : this(year, month, day, hour, minute, second, 0.0) { } public SqlDateTime(int year, int month, int day, int hour, int minute, int second, double millisecond) { if (year >= s_minYear && year <= s_maxYear && month >= 1 && month <= 12) { int[] days = IsLeapYear(year) ? s_daysToMonth366 : s_daysToMonth365; if (day >= 1 && day <= days[month] - days[month - 1]) { int y = year - 1; int dayticks = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1; dayticks -= s_dayBase; if (dayticks >= s_minDay && dayticks <= s_maxDay && hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60 && millisecond >= 0 && millisecond < 1000.0) { double ticksForMilisecond = millisecond * s_SQLTicksPerMillisecond + 0.5; int timeticks = hour * SQLTicksPerHour + minute * SQLTicksPerMinute + second * SQLTicksPerSecond + (int)ticksForMilisecond; if (timeticks > s_maxTime) { // Only rounding up could cause time to become greater than MaxTime. Debug.Assert(timeticks == s_maxTime + 1); // Make time to be zero, and increment day. timeticks = 0; dayticks++; } // Success. Call ctor here which will again check dayticks and timeticks are within range. // All other cases will throw exception below. this = new SqlDateTime(dayticks, timeticks); return; } } } throw new SqlTypeException(SQLResource.InvalidDateTimeMessage); } // constructor that take DBTIMESTAMP data members // Note: bilisecond is same as 'fraction' in DBTIMESTAMP public SqlDateTime(int year, int month, int day, int hour, int minute, int second, int bilisecond) : this(year, month, day, hour, minute, second, bilisecond / 1000.0) { } public SqlDateTime(int dayTicks, int timeTicks) { if (dayTicks < s_minDay || dayTicks > s_maxDay || timeTicks < s_minTime || timeTicks > s_maxTime) { m_fNotNull = false; throw new OverflowException(SQLResource.DateTimeOverflowMessage); } m_day = dayTicks; m_time = timeTicks; m_fNotNull = true; } internal SqlDateTime(double dblVal) { if ((dblVal < s_minDay) || (dblVal >= s_maxDay + 1)) throw new OverflowException(SQLResource.DateTimeOverflowMessage); int day = (int)dblVal; int time = (int)((dblVal - day) * s_SQLTicksPerDay); // Check if we need to borrow a day from the day portion. if (time < 0) { day--; time += s_SQLTicksPerDay; } else if (time >= s_SQLTicksPerDay) { // Deal with case where time portion = 24 hrs. // // ISSUE: Is this code reachable? For this code to be reached there // must be a value for dblVal such that: // dblVal - (long)dblVal = 1.0 // This seems odd, but there was a bug that resulted because // there was a negative value for dblVal such that dblVal + 1.0 = 1.0 // day++; time -= s_SQLTicksPerDay; } this = new SqlDateTime(day, time); } // INullable public bool IsNull { get { return !m_fNotNull; } } private static TimeSpan ToTimeSpan(SqlDateTime value) { long millisecond = (long)(value.m_time / s_SQLTicksPerMillisecond + 0.5); return new TimeSpan(value.m_day * TimeSpan.TicksPerDay + millisecond * TimeSpan.TicksPerMillisecond); } private static DateTime ToDateTime(SqlDateTime value) { return s_SQLBaseDate.Add(ToTimeSpan(value)); } // Used by SqlBuffer in SqlClient. internal static DateTime ToDateTime(int daypart, int timepart) { if (daypart < s_minDay || daypart > s_maxDay || timepart < s_minTime || timepart > s_maxTime) { throw new OverflowException(SQLResource.DateTimeOverflowMessage); } long dayticks = daypart * TimeSpan.TicksPerDay; long timeticks = ((long)(timepart / s_SQLTicksPerMillisecond + 0.5)) * TimeSpan.TicksPerMillisecond; DateTime result = new DateTime(s_SQLBaseDateTicks + dayticks + timeticks); return result; } // Convert from TimeSpan, rounded to one three-hundredth second, due to loss of precision private static SqlDateTime FromTimeSpan(TimeSpan value) { if (value < s_minTimeSpan || value > s_maxTimeSpan) throw new SqlTypeException(SQLResource.DateTimeOverflowMessage); int day = value.Days; long ticks = value.Ticks - day * TimeSpan.TicksPerDay; if (ticks < 0L) { day--; ticks += TimeSpan.TicksPerDay; } int time = (int)((double)ticks / TimeSpan.TicksPerMillisecond * s_SQLTicksPerMillisecond + 0.5); if (time > s_maxTime) { // Only rounding up could cause time to become greater than MaxTime. Debug.Assert(time == s_maxTime + 1); // Make time to be zero, and increment day. time = 0; day++; } return new SqlDateTime(day, time); } private static SqlDateTime FromDateTime(DateTime value) { // SqlDateTime has smaller precision and range than DateTime. // Usually we round the DateTime value to the nearest SqlDateTime value. // but for DateTime.MaxValue, if we round it up, it will overflow. // Although the overflow would be the correct behavior, we simply // returned SqlDateTime.MaxValue in v1. In order not to break existing // code, we'll keep this logic. // if (value == DateTime.MaxValue) return SqlDateTime.MaxValue; return FromTimeSpan(value.Subtract(s_SQLBaseDate)); } /* internal static SqlDateTime FromDouble(double dblVal) { return new SqlDateTime(dblVal); } internal static double ToDouble(SqlDateTime x) { AssertValidSqlDateTime(x); return(double)x.m_day + ((double)x.m_time / (double)SQLTicksPerDay); } internal static int ToInt(SqlDateTime x) { AssertValidSqlDateTime(x); return x.m_time >= MaxTime / 2 ? x.m_day + 1 : x.m_day; } */ // do we still want to define a property of DateTime? If the user uses it often, it is expensive // property: Value public DateTime Value { get { if (m_fNotNull) return ToDateTime(this); else throw new SqlNullValueException(); } } // Day ticks -- returns number of days since 1/1/1900 public int DayTicks { get { if (m_fNotNull) return m_day; else throw new SqlNullValueException(); } } // Time ticks -- return daily time in unit of 1/300 second public int TimeTicks { get { if (m_fNotNull) return m_time; else throw new SqlNullValueException(); } } // Implicit conversion from DateTime to SqlDateTime public static implicit operator SqlDateTime(DateTime value) { return new SqlDateTime(value); } // Explicit conversion from SqlDateTime to int. Returns 0 if x is Null. public static explicit operator DateTime(SqlDateTime x) { return ToDateTime(x); } // Return string representation of SqlDateTime public override string ToString() { if (IsNull) return SQLResource.NullString; DateTime dateTime = ToDateTime(this); return dateTime.ToString((IFormatProvider)null); } public static SqlDateTime Parse(string s) { DateTime dt; if (s == SQLResource.NullString) return SqlDateTime.Null; try { dt = DateTime.Parse(s, CultureInfo.InvariantCulture); } catch (FormatException) { DateTimeFormatInfo dtfi = (DateTimeFormatInfo)(CultureInfo.CurrentCulture.GetFormat(typeof(DateTimeFormatInfo))); dt = DateTime.ParseExact(s, s_dateTimeFormats, dtfi, x_DateTimeStyle); } return new SqlDateTime(dt); } // Binary operators // Arithmetic operators // Alternative method: SqlDateTime.Add public static SqlDateTime operator +(SqlDateTime x, TimeSpan t) { return x.IsNull ? Null : FromDateTime(ToDateTime(x) + t); } // Alternative method: SqlDateTime.Subtract public static SqlDateTime operator -(SqlDateTime x, TimeSpan t) { return x.IsNull ? Null : FromDateTime(ToDateTime(x) - t); } //-------------------------------------------------- // Alternative methods for overloaded operators //-------------------------------------------------- // Alternative method for operator + public static SqlDateTime Add(SqlDateTime x, TimeSpan t) { return x + t; } // Alternative method for operator - public static SqlDateTime Subtract(SqlDateTime x, TimeSpan t) { return x - t; } /* // Implicit conversions // Implicit conversion from SqlBoolean to SqlDateTime public static implicit operator SqlDateTime(SqlBoolean x) { return x.IsNull ? Null : new SqlDateTime(x.Value, 0); } // Implicit conversion from SqlInt32 to SqlDateTime public static implicit operator SqlDateTime(SqlInt32 x) { return x.IsNull ? Null : new SqlDateTime(x.Value, 0); } // Implicit conversion from SqlMoney to SqlDateTime public static implicit operator SqlDateTime(SqlMoney x) { return x.IsNull ? Null : SqlDateTime.FromDouble(x.ToDouble()); } // Explicit conversions // Explicit conversion from SqlDateTime to SqlInt32 public static explicit operator SqlInt32(SqlDateTime x) { if (x.IsNull) return SqlInt32.Null; return new SqlInt32(SqlDateTime.ToInt(x)); } // Explicit conversion from SqlDateTime to SqlBoolean public static explicit operator SqlBoolean(SqlDateTime x) { if (x.IsNull) return SqlBoolean.Null; return new SqlBoolean(x.m_day != 0 || x.m_time != 0, false); } // Explicit conversion from SqlDateTime to SqlMoney public static explicit operator SqlMoney(SqlDateTime x) { return x.IsNull ? SqlMoney.Null : new SqlMoney(SqlDateTime.ToDouble(x)); } // Implicit conversion from SqlDouble to SqlDateTime public static implicit operator SqlDateTime(SqlDouble x) { return x.IsNull ? Null : new SqlDateTime(x.Value); } // Explicit conversion from SqlDateTime to SqlDouble public static explicit operator SqlDouble(SqlDateTime x) { return x.IsNull ? SqlDouble.Null : new SqlDouble(SqlDateTime.ToDouble(x)); } // Implicit conversion from SqlDecimal to SqlDateTime public static implicit operator SqlDateTime(SqlDecimal x) { return x.IsNull ? SqlDateTime.Null : new SqlDateTime(SqlDecimal.ToDouble(x)); } // Explicit conversion from SqlDateTime to SqlDecimal public static explicit operator SqlDecimal(SqlDateTime x) { return x.IsNull ? SqlDecimal.Null : new SqlDecimal(SqlDateTime.ToDouble(x)); } */ // Explicit conversion from SqlString to SqlDateTime // Throws FormatException or OverflowException if necessary. public static explicit operator SqlDateTime(SqlString x) { return x.IsNull ? SqlDateTime.Null : SqlDateTime.Parse(x.Value); } // Builtin functions // utility functions /* private static void AssertValidSqlDateTime(SqlDateTime x) { Debug.Assert(!x.IsNull, "!x.IsNull", "Datetime: Null"); Debug.Assert(x.m_day >= MinDay && x.m_day <= MaxDay, "day >= MinDay && day <= MaxDay", "DateTime: Day out of range"); Debug.Assert(x.m_time >= MinTime && x.m_time <= MaxTime, "time >= MinTime && time <= MaxTime", "DateTime: Time out of range"); } */ // Checks whether a given year is a leap year. This method returns true if // "year" is a leap year, or false if not. // // @param year The year to check. // @return true if "year" is a leap year, false otherwise. // private static bool IsLeapYear(int year) { return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); } // Overloading comparison operators public static SqlBoolean operator ==(SqlDateTime x, SqlDateTime y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_day == y.m_day && x.m_time == y.m_time); } public static SqlBoolean operator !=(SqlDateTime x, SqlDateTime y) { return !(x == y); } public static SqlBoolean operator <(SqlDateTime x, SqlDateTime y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_day < y.m_day || (x.m_day == y.m_day && x.m_time < y.m_time)); } public static SqlBoolean operator >(SqlDateTime x, SqlDateTime y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_day > y.m_day || (x.m_day == y.m_day && x.m_time > y.m_time)); } public static SqlBoolean operator <=(SqlDateTime x, SqlDateTime y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_day < y.m_day || (x.m_day == y.m_day && x.m_time <= y.m_time)); } public static SqlBoolean operator >=(SqlDateTime x, SqlDateTime y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_day > y.m_day || (x.m_day == y.m_day && x.m_time >= y.m_time)); } //-------------------------------------------------- // Alternative methods for overloaded operators //-------------------------------------------------- // Alternative method for operator == public static SqlBoolean Equals(SqlDateTime x, SqlDateTime y) { return (x == y); } // Alternative method for operator != public static SqlBoolean NotEquals(SqlDateTime x, SqlDateTime y) { return (x != y); } // Alternative method for operator < public static SqlBoolean LessThan(SqlDateTime x, SqlDateTime y) { return (x < y); } // Alternative method for operator > public static SqlBoolean GreaterThan(SqlDateTime x, SqlDateTime y) { return (x > y); } // Alternative method for operator <= public static SqlBoolean LessThanOrEqual(SqlDateTime x, SqlDateTime y) { return (x <= y); } // Alternative method for operator >= public static SqlBoolean GreaterThanOrEqual(SqlDateTime x, SqlDateTime y) { return (x >= y); } // Alternative method for conversions. public SqlString ToSqlString() { return (SqlString)this; } // IComparable // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this < object, zero if this = object, // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. public int CompareTo(object value) { if (value is SqlDateTime) { SqlDateTime i = (SqlDateTime)value; return CompareTo(i); } throw ADP.WrongType(value.GetType(), typeof(SqlDateTime)); } public int CompareTo(SqlDateTime value) { // If both Null, consider them equal. // Otherwise, Null is less than anything. if (IsNull) return value.IsNull ? 0 : -1; else if (value.IsNull) return 1; if (this < value) return -1; if (this > value) return 1; return 0; } // Compares this instance with a specified object public override bool Equals(object value) { if (!(value is SqlDateTime)) { return false; } SqlDateTime i = (SqlDateTime)value; if (i.IsNull || IsNull) return (i.IsNull && IsNull); else return (this == i).Value; } // For hashing purpose public override int GetHashCode() { return IsNull ? 0 : Value.GetHashCode(); } XmlSchema IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. reader.ReadElementString(); m_fNotNull = false; } else { DateTime dt = XmlConvert.ToDateTime(reader.ReadElementString(), XmlDateTimeSerializationMode.RoundtripKind); // We do not support any kind of timezone information that is // possibly included in the CLR DateTime, since SQL Server // does not support TZ info. If any was specified, error out. // if (dt.Kind != System.DateTimeKind.Unspecified) { throw new SqlTypeException(SQLResource.TimeZoneSpecifiedMessage); } SqlDateTime st = FromDateTime(dt); m_day = st.DayTicks; m_time = st.TimeTicks; m_fNotNull = true; } } void IXmlSerializable.WriteXml(XmlWriter writer) { if (IsNull) { writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true"); } else { writer.WriteString(XmlConvert.ToString(Value, s_ISO8601_DateTimeFormat)); } } public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet) { return new XmlQualifiedName("dateTime", XmlSchema.Namespace); } public static readonly SqlDateTime MinValue = new SqlDateTime(s_minDay, 0); public static readonly SqlDateTime MaxValue = new SqlDateTime(s_maxDay, s_maxTime); public static readonly SqlDateTime Null = new SqlDateTime(true); } // SqlDateTime } // namespace System.Data.SqlTypes
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEngine; using System; namespace HoloToolkit.Unity.InputModule { /// <summary> /// Component that allows dragging an object with your hand on HoloLens. /// Dragging is done by calculating the angular delta and z-delta between the current and previous hand positions, /// and then repositioning the object based on that. /// </summary> public class HandDraggable : MonoBehaviour, IFocusable, IInputHandler, ISourceStateHandler { /// <summary> /// Event triggered when dragging starts. /// </summary> public event Action StartedDragging; /// <summary> /// Event triggered when dragging stops. /// </summary> public event Action StoppedDragging; [Tooltip("Transform that will be dragged. Defaults to the object of the component.")] public Transform HostTransform; [Tooltip("Scale by which hand movement in z is multiplied to move the dragged object.")] public float DistanceScale = 2f; public enum RotationModeEnum { Default, LockObjectRotation, OrientTowardUser, OrientTowardUserAndKeepUpright } public RotationModeEnum RotationMode = RotationModeEnum.Default; [Tooltip("Controls the speed at which the object will interpolate toward the desired position")] [Range(0.01f, 1.0f)] public float PositionLerpSpeed = 0.2f; [Tooltip("Controls the speed at which the object will interpolate toward the desired rotation")] [Range(0.01f, 1.0f)] public float RotationLerpSpeed = 0.2f; public bool IsDraggingEnabled = true; private bool isDragging; private bool isGazed; private Vector3 objRefForward; private Vector3 objRefUp; private float objRefDistance; private Quaternion gazeAngularOffset; private float handRefDistance; private Vector3 objRefGrabPoint; private Vector3 draggingPosition; private Quaternion draggingRotation; private IInputSource currentInputSource; private uint currentInputSourceId; private Rigidbody hostRigidbody; private void Start() { if (HostTransform == null) { HostTransform = transform; } hostRigidbody = HostTransform.GetComponent<Rigidbody>(); } private void OnDestroy() { if (isDragging) { StopDragging(); } if (isGazed) { OnFocusExit(); } } private void Update() { if (IsDraggingEnabled && isDragging) { UpdateDragging(); } } /// <summary> /// Starts dragging the object. /// </summary> public void StartDragging(Vector3 initialDraggingPosition) { if (!IsDraggingEnabled) { return; } if (isDragging) { return; } // TODO: robertes: Fix push/pop and single-handler model so that multiple HandDraggable components // can be active at once. // Add self as a modal input handler, to get all inputs during the manipulation InputManager.Instance.PushModalInputHandler(gameObject); isDragging = true; Transform cameraTransform = CameraCache.Main.transform; Vector3 inputPosition = Vector3.zero; #if UNITY_2017_2_OR_NEWER InteractionSourceInfo sourceKind; currentInputSource.TryGetSourceKind(currentInputSourceId, out sourceKind); switch (sourceKind) { case InteractionSourceInfo.Hand: currentInputSource.TryGetGripPosition(currentInputSourceId, out inputPosition); break; case InteractionSourceInfo.Controller: currentInputSource.TryGetPointerPosition(currentInputSourceId, out inputPosition); break; } #else currentInputSource.TryGetPointerPosition(currentInputSourceId, out inputPosition); #endif Vector3 pivotPosition = GetHandPivotPosition(cameraTransform); handRefDistance = Vector3.Magnitude(inputPosition - pivotPosition); objRefDistance = Vector3.Magnitude(initialDraggingPosition - pivotPosition); Vector3 objForward = HostTransform.forward; Vector3 objUp = HostTransform.up; // Store where the object was grabbed from objRefGrabPoint = cameraTransform.transform.InverseTransformDirection(HostTransform.position - initialDraggingPosition); Vector3 objDirection = Vector3.Normalize(initialDraggingPosition - pivotPosition); Vector3 handDirection = Vector3.Normalize(inputPosition - pivotPosition); objForward = cameraTransform.InverseTransformDirection(objForward); // in camera space objUp = cameraTransform.InverseTransformDirection(objUp); // in camera space objDirection = cameraTransform.InverseTransformDirection(objDirection); // in camera space handDirection = cameraTransform.InverseTransformDirection(handDirection); // in camera space objRefForward = objForward; objRefUp = objUp; // Store the initial offset between the hand and the object, so that we can consider it when dragging gazeAngularOffset = Quaternion.FromToRotation(handDirection, objDirection); draggingPosition = initialDraggingPosition; StartedDragging.RaiseEvent(); } /// <summary> /// Gets the pivot position for the hand, which is approximated to the base of the neck. /// </summary> /// <returns>Pivot position for the hand.</returns> private Vector3 GetHandPivotPosition(Transform cameraTransform) { return cameraTransform.position + new Vector3(0, -0.2f, 0) - cameraTransform.forward * 0.2f; // a bit lower and behind } /// <summary> /// Enables or disables dragging. /// </summary> /// <param name="isEnabled">Indicates whether dragging should be enabled or disabled.</param> public void SetDragging(bool isEnabled) { if (IsDraggingEnabled == isEnabled) { return; } IsDraggingEnabled = isEnabled; if (isDragging) { StopDragging(); } } /// <summary> /// Update the position of the object being dragged. /// </summary> private void UpdateDragging() { Transform cameraTransform = CameraCache.Main.transform; Vector3 inputPosition = Vector3.zero; #if UNITY_2017_2_OR_NEWER InteractionSourceInfo sourceKind; currentInputSource.TryGetSourceKind(currentInputSourceId, out sourceKind); switch (sourceKind) { case InteractionSourceInfo.Hand: currentInputSource.TryGetGripPosition(currentInputSourceId, out inputPosition); break; case InteractionSourceInfo.Controller: currentInputSource.TryGetPointerPosition(currentInputSourceId, out inputPosition); break; } #else currentInputSource.TryGetPointerPosition(currentInputSourceId, out inputPosition); #endif Vector3 pivotPosition = GetHandPivotPosition(cameraTransform); Vector3 newHandDirection = Vector3.Normalize(inputPosition - pivotPosition); newHandDirection = cameraTransform.InverseTransformDirection(newHandDirection); // in camera space Vector3 targetDirection = Vector3.Normalize(gazeAngularOffset * newHandDirection); targetDirection = cameraTransform.TransformDirection(targetDirection); // back to world space float currentHandDistance = Vector3.Magnitude(inputPosition - pivotPosition); float distanceRatio = currentHandDistance / handRefDistance; float distanceOffset = distanceRatio > 0 ? (distanceRatio - 1f) * DistanceScale : 0; float targetDistance = objRefDistance + distanceOffset; draggingPosition = pivotPosition + (targetDirection * targetDistance); if (RotationMode == RotationModeEnum.OrientTowardUser || RotationMode == RotationModeEnum.OrientTowardUserAndKeepUpright) { draggingRotation = Quaternion.LookRotation(HostTransform.position - pivotPosition); } else if (RotationMode == RotationModeEnum.LockObjectRotation) { draggingRotation = HostTransform.rotation; } else // RotationModeEnum.Default { Vector3 objForward = cameraTransform.TransformDirection(objRefForward); // in world space Vector3 objUp = cameraTransform.TransformDirection(objRefUp); // in world space draggingRotation = Quaternion.LookRotation(objForward, objUp); } Vector3 newPosition = Vector3.Lerp(HostTransform.position, draggingPosition + cameraTransform.TransformDirection(objRefGrabPoint), PositionLerpSpeed); // Apply Final Position if (hostRigidbody == null) { HostTransform.position = newPosition; } else { hostRigidbody.MovePosition(newPosition); } // Apply Final Rotation Quaternion newRotation = Quaternion.Lerp(HostTransform.rotation, draggingRotation, RotationLerpSpeed); if (hostRigidbody == null) { HostTransform.rotation = newRotation; } else { hostRigidbody.MoveRotation(newRotation); } if (RotationMode == RotationModeEnum.OrientTowardUserAndKeepUpright) { Quaternion upRotation = Quaternion.FromToRotation(HostTransform.up, Vector3.up); HostTransform.rotation = upRotation * HostTransform.rotation; } } /// <summary> /// Stops dragging the object. /// </summary> public void StopDragging() { if (!isDragging) { return; } // Remove self as a modal input handler InputManager.Instance.PopModalInputHandler(); isDragging = false; currentInputSource = null; currentInputSourceId = 0; StoppedDragging.RaiseEvent(); } public void OnFocusEnter() { if (!IsDraggingEnabled) { return; } if (isGazed) { return; } isGazed = true; } public void OnFocusExit() { if (!IsDraggingEnabled) { return; } if (!isGazed) { return; } isGazed = false; } public void OnInputUp(InputEventData eventData) { if (currentInputSource != null && eventData.SourceId == currentInputSourceId) { eventData.Use(); // Mark the event as used, so it doesn't fall through to other handlers. StopDragging(); } } public void OnInputDown(InputEventData eventData) { if (isDragging) { // We're already handling drag input, so we can't start a new drag operation. return; } #if UNITY_2017_2_OR_NEWER InteractionSourceInfo sourceKind; eventData.InputSource.TryGetSourceKind(eventData.SourceId, out sourceKind); if (sourceKind != InteractionSourceInfo.Hand) { if (!eventData.InputSource.SupportsInputInfo(eventData.SourceId, SupportedInputInfo.Position)) { // The input source must provide positional data for this script to be usable return; } } #else if (!eventData.InputSource.SupportsInputInfo(eventData.SourceId, SupportedInputInfo.Position)) { // The input source must provide positional data for this script to be usable return; } #endif eventData.Use(); // Mark the event as used, so it doesn't fall through to other handlers. currentInputSource = eventData.InputSource; currentInputSourceId = eventData.SourceId; FocusDetails? details = FocusManager.Instance.TryGetFocusDetails(eventData); Vector3 initialDraggingPosition = (details == null) ? HostTransform.position : details.Value.Point; StartDragging(initialDraggingPosition); } public void OnSourceDetected(SourceStateEventData eventData) { // Nothing to do } public void OnSourceLost(SourceStateEventData eventData) { if (currentInputSource != null && eventData.SourceId == currentInputSourceId) { StopDragging(); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Xml; using System.Xml.Serialization; using System.Diagnostics; using AgenaTrader.API; using AgenaTrader.Custom; using AgenaTrader.Plugins; using AgenaTrader.Helper; /// <summary> /// Version: 1.2.0 /// ------------------------------------------------------------------------- /// Simon Pucher 2016 /// ------------------------------------------------------------------------- /// The indicator was taken from: http://metick.com/forotraderninja/viewtopic.php?t=976 /// Code was generated by AgenaTrader conversion tool and modified by Simon Pucher. /// ------------------------------------------------------------------------- /// ****** Important ****** /// To compile this script without any error you also need access to the utility indicator to use these global source code elements. /// You will find this indicator on GitHub: https://raw.githubusercontent.com/simonpucher/AgenaTrader/master/Utilities/GlobalUtilities_Utility.cs /// ------------------------------------------------------------------------- /// Namespace holds all indicators and is required. Do not change it. /// </summary> namespace AgenaTrader.UserCode { /// <summary> /// The anaMACDBBLines (Moving Average Convergence/Divergence) is a trend following momentum indicator that shows the relationship between two moving averages of prices. /// Optimized execution by predefining instances of external indicators (Zondor August 10 2010) /// </summary> [Description("The TDI (Moving Average Convergence/Divergence) is a trend following momentum indicator that shows the relationship between two moving averages of prices.")] public class TDI_Indicator : UserIndicator { //input private int _rsiPeriod = 13; private int _pricePeriod = 2; private int _signalPeriod = 7; private int _bandPeriod = 34; private double _stdDevNumber = 1.62; private Color _main = Color.Lime; private Color _signal = Color.Red; private Color _bbAverage = Color.Gold; private Color _bbUpper = Color.CornflowerBlue; private Color _bbLower = Color.CornflowerBlue; private Color _midPositive = Color.Olive; private Color _midNegative = Color.RosyBrown; private int _plot0Width = Const.DefaultLineWidth; private DashStyle _dash0Style = Const.DefaultIndicatorDashStyle; private int _plot1Width = Const.DefaultLineWidth; private DashStyle _dash1Style = Const.DefaultIndicatorDashStyle; private int _plot2Width = Const.DefaultLineWidth; private DashStyle _dash2Style = Const.DefaultIndicatorDashStyle; private int _plot3Width = Const.DefaultLineWidth_small; private DashStyle _dash3Style = Const.DefaultIndicatorDashStyle; //output //internal private DataSeries _RSI_List; /// <summary> /// This method is used to configure the indicator and is called once before any bar data is loaded. /// </summary> protected override void OnInit() { Add(new OutputDescriptor(new Pen(this.Main, this.Plot0Width), OutputSerieDrawStyle.Line, "LinePrice")); Add(new OutputDescriptor(new Pen(this.Signal, this.Plot1Width), OutputSerieDrawStyle.Line, "Signalline")); Add(new OutputDescriptor(new Pen(this.BBAverage, this.Plot2Width), OutputSerieDrawStyle.Line, "Average")); Add(new OutputDescriptor(new Pen(this.BBUpper, this.Plot3Width), OutputSerieDrawStyle.Line, "Upper")); Add(new OutputDescriptor(new Pen(this.BBUpper, this.Plot3Width), OutputSerieDrawStyle.Line, "Lower")); Add(new OutputDescriptor(new Pen(Color.Gray, this.Plot3Width), OutputSerieDrawStyle.Line, "MidLine")); CalculateOnClosedBar = true; IsOverlay = false; } /// <summary> /// Calculates the indicator value(s) at the current index. /// </summary> protected override void OnStart() { this._RSI_List = new DataSeries(this); } protected override void OnCalculate() { double RSI_value = RSI(this.RSIPeriod, 1)[0]; this._RSI_List.Set(RSI_value); double PRICE_value = SMA(this._RSI_List, this.PricePeriod)[0]; LinePrice.Set(PRICE_value); double SIGNAL_value = SMA(this._RSI_List, this.SignalPeriod)[0]; SignalLine.Set(SIGNAL_value); double AVG_value = SMA(this._RSI_List, this.BandPeriod)[0]; Average.Set(AVG_value); MidLine.Set(50); double stdDevValue = StdDev(this._RSI_List, this.BandPeriod)[0]; Upper.Set(AVG_value + this.StdDevNumber * stdDevValue); Lower.Set(AVG_value - this.StdDevNumber * stdDevValue); PlotColors[0][0] = this.Main; PlotColors[1][0] = this.Signal; PlotColors[2][0] = this.BBAverage; PlotColors[3][0] = this.BBUpper; PlotColors[4][0] = this.BBLower; if (AVG_value > 50) PlotColors[5][0] = this.MidPositive; else PlotColors[5][0] = this.MidNegative; OutputDescriptors[0].PenStyle = this.Dash0Style; OutputDescriptors[0].Pen.Width = this.Plot0Width; OutputDescriptors[1].PenStyle = this.Dash1Style; OutputDescriptors[1].Pen.Width = this.Plot1Width; OutputDescriptors[2].PenStyle = this.Dash2Style; OutputDescriptors[2].Pen.Width = this.Plot2Width; OutputDescriptors[3].PenStyle = this.Dash3Style; OutputDescriptors[3].Pen.Width = this.Plot3Width; OutputDescriptors[4].PenStyle = this.Dash3Style; OutputDescriptors[4].Pen.Width = this.Plot3Width; OutputDescriptors[5].PenStyle = this.Dash3Style; OutputDescriptors[5].Pen.Width = this.Plot3Width; } public override string ToString() { return "TDI"; } public override string DisplayName { get { return "TDI"; } } #region Properties #region InSeries [XmlIgnore()] [Description("Select Color")] [InputParameter] [DisplayName("Pricline")] public Color Main { get { return _main; } set { _main = value; } } [Browsable(false)] public string MainSerialize { get { return SerializableColor.ToString(_main); } set { _main = SerializableColor.FromString(value); } } [XmlIgnore()] [Description("Select Color")] [InputParameter] [DisplayName("Signalline")] public Color Signal { get { return _signal; } set { _signal = value; } } [Browsable(false)] public string SignalSerialize { get { return SerializableColor.ToString(_signal); } set { _signal = SerializableColor.FromString(value); } } [XmlIgnore()] [Description("Select Color")] [InputParameter] [DisplayName("Bollinger Average")] public Color BBAverage { get { return _bbAverage; } set { _bbAverage = value; } } [Browsable(false)] public string BBAverageSerialize { get { return SerializableColor.ToString(_bbAverage); } set { _bbAverage = SerializableColor.FromString(value); } } [XmlIgnore()] [Description("Select Color")] [InputParameter] [DisplayName("Bollinger Upper Band")] public Color BBUpper { get { return _bbUpper; } set { _bbUpper = value; } } [Browsable(false)] public string BBUpperSerialize { get { return SerializableColor.ToString(_bbUpper); } set { _bbUpper = SerializableColor.FromString(value); } } [XmlIgnore()] [Description("Select Color")] [InputParameter] [DisplayName("Bollinger Lower Band")] public Color BBLower { get { return _bbLower; } set { _bbLower = value; } } [Browsable(false)] public string BBLowerSerialize { get { return SerializableColor.ToString(_bbLower); } set { _bbLower = SerializableColor.FromString(value); } } [XmlIgnore()] [Description("Select Color")] [InputParameter] [DisplayName("Midline Positive")] public Color MidPositive { get { return _midPositive; } set { _midPositive = value; } } [Browsable(false)] public string MidPositiveSerialize { get { return SerializableColor.ToString(_midPositive); } set { _midPositive = SerializableColor.FromString(value); } } [XmlIgnore()] [Description("Select Color")] [InputParameter] [DisplayName("Midline Negative")] public Color MidNegative { get { return _midNegative; } set { _midNegative = value; } } [Browsable(false)] public string MidNegativeSerialize { get { return SerializableColor.ToString(_midNegative); } set { _midNegative = SerializableColor.FromString(value); } } [Description("Period for RSI")] [InputParameter] [DisplayName("Period for RSI")] public int RSIPeriod { get { return _rsiPeriod; } set { _rsiPeriod = Math.Max(1, value); } } [Description("Period for LinePrice")] [InputParameter] [DisplayName("Period for LinePrice")] public int PricePeriod { get { return _pricePeriod; } set { _pricePeriod = Math.Max(1, value); } } /// <summary> /// </summary> [Description("Period for Signalline")] [InputParameter] [DisplayName("Period for Signalline")] public int SignalPeriod { get { return _signalPeriod; } set { _signalPeriod = Math.Max(1, value); } } /// <summary> /// </summary> [Description("Band Period for Bollinger Band")] [InputParameter] [DisplayName("Period for VolaBands")] public int BandPeriod { get { return _bandPeriod; } set { _bandPeriod = Math.Max(1, value); } } /// <summary> /// </summary> [Description("Number of standard deviations")] [InputParameter] [DisplayName("# of Std. Dev.")] public double StdDevNumber { get { return _stdDevNumber; } set { _stdDevNumber = Math.Max(0, value); } } /// <summary> /// </summary> [Description("Width for LinePrice.")] [InputParameter] [DisplayName("Line Width LinePrice")] public int Plot0Width { get { return _plot0Width; } set { _plot0Width = Math.Max(1, value); } } /// <summary> /// </summary> [Description("DashStyle for LinePrice.")] [InputParameter] [DisplayName("Dash Style LinePrice")] public DashStyle Dash0Style { get { return _dash0Style; } set { _dash0Style = value; } } /// <summary> /// </summary> [Description("Width for Signalline.")] [InputParameter] [DisplayName("Line Width Signal")] public int Plot1Width { get { return _plot1Width; } set { _plot1Width = Math.Max(1, value); } } /// <summary> /// </summary> [Description("DashStyle for Signalline.")] [InputParameter] [DisplayName("Dash Style Signal")] public DashStyle Dash1Style { get { return _dash1Style; } set { _dash1Style = value; } } /// <summary> /// </summary> [Description("Width for Midband.")] [InputParameter] [DisplayName("Line Width Midband")] public int Plot2Width { get { return _plot2Width; } set { _plot2Width = Math.Max(1, value); } } /// <summary> /// </summary> [Description("DashStyle for Bollinger Bands.")] [InputParameter] [DisplayName("Dash Style BBands")] public DashStyle Dash2Style { get { return _dash2Style; } set { _dash2Style = value; } } /// <summary> /// </summary> [Description("Width for Bollinger Bands.")] [InputParameter] [DisplayName("Line Width BBAnds")] public int Plot3Width { get { return _plot3Width; } set { _plot3Width = Math.Max(1, value); } } /// <summary> /// </summary> [Description("DashStyle for Trigger Average Line.")] [InputParameter] [DisplayName("Dash Style Average")] public DashStyle Dash3Style { get { return _dash3Style; } set { _dash3Style = value; } } #endregion #region Output [Browsable(false)] [XmlIgnore()] public DataSeries LinePrice { get { return Outputs[0]; } } [Browsable(false)] [XmlIgnore()] public DataSeries SignalLine { get { return Outputs[1]; } } [Browsable(false)] [XmlIgnore()] public DataSeries Average { get { return Outputs[2]; } } [Browsable(false)] [XmlIgnore()] public DataSeries Upper { get { return Outputs[3]; } } [Browsable(false)] [XmlIgnore()] public DataSeries Lower { get { return Outputs[4]; } } [Browsable(false)] [XmlIgnore()] public DataSeries MidLine { get { return Outputs[5]; } } #endregion #endregion } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Compute.V1.Snippets { using Google.Api.Gax; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using lro = Google.LongRunning; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedHealthChecksClientSnippets { /// <summary>Snippet for AggregatedList</summary> public void AggregatedListRequestObject() { // Snippet: AggregatedList(AggregatedListHealthChecksRequest, CallSettings) // Create client HealthChecksClient healthChecksClient = HealthChecksClient.Create(); // Initialize request argument(s) AggregatedListHealthChecksRequest request = new AggregatedListHealthChecksRequest { OrderBy = "", Project = "", Filter = "", IncludeAllScopes = false, ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<HealthChecksAggregatedList, KeyValuePair<string, HealthChecksScopedList>> response = healthChecksClient.AggregatedList(request); // Iterate over all response items, lazily performing RPCs as required foreach (KeyValuePair<string, HealthChecksScopedList> item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (HealthChecksAggregatedList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, HealthChecksScopedList> item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, HealthChecksScopedList>> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, HealthChecksScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for AggregatedListAsync</summary> public async Task AggregatedListRequestObjectAsync() { // Snippet: AggregatedListAsync(AggregatedListHealthChecksRequest, CallSettings) // Create client HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync(); // Initialize request argument(s) AggregatedListHealthChecksRequest request = new AggregatedListHealthChecksRequest { OrderBy = "", Project = "", Filter = "", IncludeAllScopes = false, ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<HealthChecksAggregatedList, KeyValuePair<string, HealthChecksScopedList>> response = healthChecksClient.AggregatedListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((KeyValuePair<string, HealthChecksScopedList> item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((HealthChecksAggregatedList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, HealthChecksScopedList> item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, HealthChecksScopedList>> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, HealthChecksScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for AggregatedList</summary> public void AggregatedList() { // Snippet: AggregatedList(string, string, int?, CallSettings) // Create client HealthChecksClient healthChecksClient = HealthChecksClient.Create(); // Initialize request argument(s) string project = ""; // Make the request PagedEnumerable<HealthChecksAggregatedList, KeyValuePair<string, HealthChecksScopedList>> response = healthChecksClient.AggregatedList(project); // Iterate over all response items, lazily performing RPCs as required foreach (KeyValuePair<string, HealthChecksScopedList> item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (HealthChecksAggregatedList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, HealthChecksScopedList> item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, HealthChecksScopedList>> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, HealthChecksScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for AggregatedListAsync</summary> public async Task AggregatedListAsync() { // Snippet: AggregatedListAsync(string, string, int?, CallSettings) // Create client HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync(); // Initialize request argument(s) string project = ""; // Make the request PagedAsyncEnumerable<HealthChecksAggregatedList, KeyValuePair<string, HealthChecksScopedList>> response = healthChecksClient.AggregatedListAsync(project); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((KeyValuePair<string, HealthChecksScopedList> item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((HealthChecksAggregatedList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, HealthChecksScopedList> item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, HealthChecksScopedList>> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, HealthChecksScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for Delete</summary> public void DeleteRequestObject() { // Snippet: Delete(DeleteHealthCheckRequest, CallSettings) // Create client HealthChecksClient healthChecksClient = HealthChecksClient.Create(); // Initialize request argument(s) DeleteHealthCheckRequest request = new DeleteHealthCheckRequest { RequestId = "", Project = "", HealthCheck = "", }; // Make the request lro::Operation<Operation, Operation> response = healthChecksClient.Delete(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = healthChecksClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteRequestObjectAsync() { // Snippet: DeleteAsync(DeleteHealthCheckRequest, CallSettings) // Additional: DeleteAsync(DeleteHealthCheckRequest, CancellationToken) // Create client HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync(); // Initialize request argument(s) DeleteHealthCheckRequest request = new DeleteHealthCheckRequest { RequestId = "", Project = "", HealthCheck = "", }; // Make the request lro::Operation<Operation, Operation> response = await healthChecksClient.DeleteAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await healthChecksClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Delete</summary> public void Delete() { // Snippet: Delete(string, string, CallSettings) // Create client HealthChecksClient healthChecksClient = HealthChecksClient.Create(); // Initialize request argument(s) string project = ""; string healthCheck = ""; // Make the request lro::Operation<Operation, Operation> response = healthChecksClient.Delete(project, healthCheck); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = healthChecksClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteAsync() { // Snippet: DeleteAsync(string, string, CallSettings) // Additional: DeleteAsync(string, string, CancellationToken) // Create client HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync(); // Initialize request argument(s) string project = ""; string healthCheck = ""; // Make the request lro::Operation<Operation, Operation> response = await healthChecksClient.DeleteAsync(project, healthCheck); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await healthChecksClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Get</summary> public void GetRequestObject() { // Snippet: Get(GetHealthCheckRequest, CallSettings) // Create client HealthChecksClient healthChecksClient = HealthChecksClient.Create(); // Initialize request argument(s) GetHealthCheckRequest request = new GetHealthCheckRequest { Project = "", HealthCheck = "", }; // Make the request HealthCheck response = healthChecksClient.Get(request); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetRequestObjectAsync() { // Snippet: GetAsync(GetHealthCheckRequest, CallSettings) // Additional: GetAsync(GetHealthCheckRequest, CancellationToken) // Create client HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync(); // Initialize request argument(s) GetHealthCheckRequest request = new GetHealthCheckRequest { Project = "", HealthCheck = "", }; // Make the request HealthCheck response = await healthChecksClient.GetAsync(request); // End snippet } /// <summary>Snippet for Get</summary> public void Get() { // Snippet: Get(string, string, CallSettings) // Create client HealthChecksClient healthChecksClient = HealthChecksClient.Create(); // Initialize request argument(s) string project = ""; string healthCheck = ""; // Make the request HealthCheck response = healthChecksClient.Get(project, healthCheck); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetAsync() { // Snippet: GetAsync(string, string, CallSettings) // Additional: GetAsync(string, string, CancellationToken) // Create client HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync(); // Initialize request argument(s) string project = ""; string healthCheck = ""; // Make the request HealthCheck response = await healthChecksClient.GetAsync(project, healthCheck); // End snippet } /// <summary>Snippet for Insert</summary> public void InsertRequestObject() { // Snippet: Insert(InsertHealthCheckRequest, CallSettings) // Create client HealthChecksClient healthChecksClient = HealthChecksClient.Create(); // Initialize request argument(s) InsertHealthCheckRequest request = new InsertHealthCheckRequest { RequestId = "", HealthCheckResource = new HealthCheck(), Project = "", }; // Make the request lro::Operation<Operation, Operation> response = healthChecksClient.Insert(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = healthChecksClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertRequestObjectAsync() { // Snippet: InsertAsync(InsertHealthCheckRequest, CallSettings) // Additional: InsertAsync(InsertHealthCheckRequest, CancellationToken) // Create client HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync(); // Initialize request argument(s) InsertHealthCheckRequest request = new InsertHealthCheckRequest { RequestId = "", HealthCheckResource = new HealthCheck(), Project = "", }; // Make the request lro::Operation<Operation, Operation> response = await healthChecksClient.InsertAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await healthChecksClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Insert</summary> public void Insert() { // Snippet: Insert(string, HealthCheck, CallSettings) // Create client HealthChecksClient healthChecksClient = HealthChecksClient.Create(); // Initialize request argument(s) string project = ""; HealthCheck healthCheckResource = new HealthCheck(); // Make the request lro::Operation<Operation, Operation> response = healthChecksClient.Insert(project, healthCheckResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = healthChecksClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertAsync() { // Snippet: InsertAsync(string, HealthCheck, CallSettings) // Additional: InsertAsync(string, HealthCheck, CancellationToken) // Create client HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync(); // Initialize request argument(s) string project = ""; HealthCheck healthCheckResource = new HealthCheck(); // Make the request lro::Operation<Operation, Operation> response = await healthChecksClient.InsertAsync(project, healthCheckResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await healthChecksClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for List</summary> public void ListRequestObject() { // Snippet: List(ListHealthChecksRequest, CallSettings) // Create client HealthChecksClient healthChecksClient = HealthChecksClient.Create(); // Initialize request argument(s) ListHealthChecksRequest request = new ListHealthChecksRequest { OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<HealthCheckList, HealthCheck> response = healthChecksClient.List(request); // Iterate over all response items, lazily performing RPCs as required foreach (HealthCheck item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (HealthCheckList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (HealthCheck item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<HealthCheck> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (HealthCheck item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListRequestObjectAsync() { // Snippet: ListAsync(ListHealthChecksRequest, CallSettings) // Create client HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync(); // Initialize request argument(s) ListHealthChecksRequest request = new ListHealthChecksRequest { OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<HealthCheckList, HealthCheck> response = healthChecksClient.ListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((HealthCheck item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((HealthCheckList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (HealthCheck item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<HealthCheck> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (HealthCheck item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for List</summary> public void List() { // Snippet: List(string, string, int?, CallSettings) // Create client HealthChecksClient healthChecksClient = HealthChecksClient.Create(); // Initialize request argument(s) string project = ""; // Make the request PagedEnumerable<HealthCheckList, HealthCheck> response = healthChecksClient.List(project); // Iterate over all response items, lazily performing RPCs as required foreach (HealthCheck item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (HealthCheckList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (HealthCheck item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<HealthCheck> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (HealthCheck item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListAsync() { // Snippet: ListAsync(string, string, int?, CallSettings) // Create client HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync(); // Initialize request argument(s) string project = ""; // Make the request PagedAsyncEnumerable<HealthCheckList, HealthCheck> response = healthChecksClient.ListAsync(project); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((HealthCheck item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((HealthCheckList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (HealthCheck item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<HealthCheck> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (HealthCheck item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for Patch</summary> public void PatchRequestObject() { // Snippet: Patch(PatchHealthCheckRequest, CallSettings) // Create client HealthChecksClient healthChecksClient = HealthChecksClient.Create(); // Initialize request argument(s) PatchHealthCheckRequest request = new PatchHealthCheckRequest { RequestId = "", HealthCheckResource = new HealthCheck(), Project = "", HealthCheck = "", }; // Make the request lro::Operation<Operation, Operation> response = healthChecksClient.Patch(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = healthChecksClient.PollOncePatch(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for PatchAsync</summary> public async Task PatchRequestObjectAsync() { // Snippet: PatchAsync(PatchHealthCheckRequest, CallSettings) // Additional: PatchAsync(PatchHealthCheckRequest, CancellationToken) // Create client HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync(); // Initialize request argument(s) PatchHealthCheckRequest request = new PatchHealthCheckRequest { RequestId = "", HealthCheckResource = new HealthCheck(), Project = "", HealthCheck = "", }; // Make the request lro::Operation<Operation, Operation> response = await healthChecksClient.PatchAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await healthChecksClient.PollOncePatchAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Patch</summary> public void Patch() { // Snippet: Patch(string, string, HealthCheck, CallSettings) // Create client HealthChecksClient healthChecksClient = HealthChecksClient.Create(); // Initialize request argument(s) string project = ""; string healthCheck = ""; HealthCheck healthCheckResource = new HealthCheck(); // Make the request lro::Operation<Operation, Operation> response = healthChecksClient.Patch(project, healthCheck, healthCheckResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = healthChecksClient.PollOncePatch(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for PatchAsync</summary> public async Task PatchAsync() { // Snippet: PatchAsync(string, string, HealthCheck, CallSettings) // Additional: PatchAsync(string, string, HealthCheck, CancellationToken) // Create client HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync(); // Initialize request argument(s) string project = ""; string healthCheck = ""; HealthCheck healthCheckResource = new HealthCheck(); // Make the request lro::Operation<Operation, Operation> response = await healthChecksClient.PatchAsync(project, healthCheck, healthCheckResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await healthChecksClient.PollOncePatchAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Update</summary> public void UpdateRequestObject() { // Snippet: Update(UpdateHealthCheckRequest, CallSettings) // Create client HealthChecksClient healthChecksClient = HealthChecksClient.Create(); // Initialize request argument(s) UpdateHealthCheckRequest request = new UpdateHealthCheckRequest { RequestId = "", HealthCheckResource = new HealthCheck(), Project = "", HealthCheck = "", }; // Make the request lro::Operation<Operation, Operation> response = healthChecksClient.Update(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = healthChecksClient.PollOnceUpdate(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateAsync</summary> public async Task UpdateRequestObjectAsync() { // Snippet: UpdateAsync(UpdateHealthCheckRequest, CallSettings) // Additional: UpdateAsync(UpdateHealthCheckRequest, CancellationToken) // Create client HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync(); // Initialize request argument(s) UpdateHealthCheckRequest request = new UpdateHealthCheckRequest { RequestId = "", HealthCheckResource = new HealthCheck(), Project = "", HealthCheck = "", }; // Make the request lro::Operation<Operation, Operation> response = await healthChecksClient.UpdateAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await healthChecksClient.PollOnceUpdateAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Update</summary> public void Update() { // Snippet: Update(string, string, HealthCheck, CallSettings) // Create client HealthChecksClient healthChecksClient = HealthChecksClient.Create(); // Initialize request argument(s) string project = ""; string healthCheck = ""; HealthCheck healthCheckResource = new HealthCheck(); // Make the request lro::Operation<Operation, Operation> response = healthChecksClient.Update(project, healthCheck, healthCheckResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = healthChecksClient.PollOnceUpdate(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateAsync</summary> public async Task UpdateAsync() { // Snippet: UpdateAsync(string, string, HealthCheck, CallSettings) // Additional: UpdateAsync(string, string, HealthCheck, CancellationToken) // Create client HealthChecksClient healthChecksClient = await HealthChecksClient.CreateAsync(); // Initialize request argument(s) string project = ""; string healthCheck = ""; HealthCheck healthCheckResource = new HealthCheck(); // Make the request lro::Operation<Operation, Operation> response = await healthChecksClient.UpdateAsync(project, healthCheck, healthCheckResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await healthChecksClient.PollOnceUpdateAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V10.Services { /// <summary>Settings for <see cref="FeedServiceClient"/> instances.</summary> public sealed partial class FeedServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="FeedServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="FeedServiceSettings"/>.</returns> public static FeedServiceSettings GetDefault() => new FeedServiceSettings(); /// <summary>Constructs a new <see cref="FeedServiceSettings"/> object with default settings.</summary> public FeedServiceSettings() { } private FeedServiceSettings(FeedServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); MutateFeedsSettings = existing.MutateFeedsSettings; OnCopy(existing); } partial void OnCopy(FeedServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>FeedServiceClient.MutateFeeds</c> and <c>FeedServiceClient.MutateFeedsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateFeedsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="FeedServiceSettings"/> object.</returns> public FeedServiceSettings Clone() => new FeedServiceSettings(this); } /// <summary> /// Builder class for <see cref="FeedServiceClient"/> to provide simple configuration of credentials, endpoint etc. /// </summary> internal sealed partial class FeedServiceClientBuilder : gaxgrpc::ClientBuilderBase<FeedServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public FeedServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public FeedServiceClientBuilder() { UseJwtAccessWithScopes = FeedServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref FeedServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<FeedServiceClient> task); /// <summary>Builds the resulting client.</summary> public override FeedServiceClient Build() { FeedServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<FeedServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<FeedServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private FeedServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return FeedServiceClient.Create(callInvoker, Settings); } private async stt::Task<FeedServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return FeedServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => FeedServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => FeedServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => FeedServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>FeedService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage feeds. /// </remarks> public abstract partial class FeedServiceClient { /// <summary> /// The default endpoint for the FeedService service, which is a host of "googleads.googleapis.com" and a port /// of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default FeedService scopes.</summary> /// <remarks> /// The default FeedService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="FeedServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="FeedServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="FeedServiceClient"/>.</returns> public static stt::Task<FeedServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new FeedServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="FeedServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="FeedServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="FeedServiceClient"/>.</returns> public static FeedServiceClient Create() => new FeedServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="FeedServiceClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="FeedServiceSettings"/>.</param> /// <returns>The created <see cref="FeedServiceClient"/>.</returns> internal static FeedServiceClient Create(grpccore::CallInvoker callInvoker, FeedServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } FeedService.FeedServiceClient grpcClient = new FeedService.FeedServiceClient(callInvoker); return new FeedServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC FeedService client</summary> public virtual FeedService.FeedServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateFeedsResponse MutateFeeds(MutateFeedsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateFeedsResponse> MutateFeedsAsync(MutateFeedsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateFeedsResponse> MutateFeedsAsync(MutateFeedsRequest request, st::CancellationToken cancellationToken) => MutateFeedsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose feeds are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual feeds. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateFeedsResponse MutateFeeds(string customerId, scg::IEnumerable<FeedOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateFeeds(new MutateFeedsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose feeds are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual feeds. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateFeedsResponse> MutateFeedsAsync(string customerId, scg::IEnumerable<FeedOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateFeedsAsync(new MutateFeedsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose feeds are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual feeds. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateFeedsResponse> MutateFeedsAsync(string customerId, scg::IEnumerable<FeedOperation> operations, st::CancellationToken cancellationToken) => MutateFeedsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>FeedService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage feeds. /// </remarks> public sealed partial class FeedServiceClientImpl : FeedServiceClient { private readonly gaxgrpc::ApiCall<MutateFeedsRequest, MutateFeedsResponse> _callMutateFeeds; /// <summary> /// Constructs a client wrapper for the FeedService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="FeedServiceSettings"/> used within this client.</param> public FeedServiceClientImpl(FeedService.FeedServiceClient grpcClient, FeedServiceSettings settings) { GrpcClient = grpcClient; FeedServiceSettings effectiveSettings = settings ?? FeedServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callMutateFeeds = clientHelper.BuildApiCall<MutateFeedsRequest, MutateFeedsResponse>(grpcClient.MutateFeedsAsync, grpcClient.MutateFeeds, effectiveSettings.MutateFeedsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateFeeds); Modify_MutateFeedsApiCall(ref _callMutateFeeds); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_MutateFeedsApiCall(ref gaxgrpc::ApiCall<MutateFeedsRequest, MutateFeedsResponse> call); partial void OnConstruction(FeedService.FeedServiceClient grpcClient, FeedServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC FeedService client</summary> public override FeedService.FeedServiceClient GrpcClient { get; } partial void Modify_MutateFeedsRequest(ref MutateFeedsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Creates, updates, or removes feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateFeedsResponse MutateFeeds(MutateFeedsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateFeedsRequest(ref request, ref callSettings); return _callMutateFeeds.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateFeedsResponse> MutateFeedsAsync(MutateFeedsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateFeedsRequest(ref request, ref callSettings); return _callMutateFeeds.Async(request, callSettings); } } }
using System; using System.Collections.Generic; namespace ClosedXML.Excel { public enum XLPageOrientation { Default, Portrait, Landscape } public enum XLPaperSize { LetterPaper = 1, LetterSmallPaper = 2, TabloidPaper = 3, LedgerPaper = 4, LegalPaper = 5, StatementPaper = 6, ExecutivePaper = 7, A3Paper = 8, A4Paper = 9, A4SmallPaper = 10, A5Paper = 11, B4Paper = 12, B5Paper = 13, FolioPaper = 14, QuartoPaper = 15, StandardPaper = 16, StandardPaper1 = 17, NotePaper = 18, No9Envelope = 19, No10Envelope = 20, No11Envelope = 21, No12Envelope = 22, No14Envelope = 23, CPaper = 24, DPaper = 25, EPaper = 26, DlEnvelope = 27, C5Envelope = 28, C3Envelope = 29, C4Envelope = 30, C6Envelope = 31, C65Envelope = 32, B4Envelope = 33, B5Envelope = 34, B6Envelope = 35, ItalyEnvelope = 36, MonarchEnvelope = 37, No634Envelope = 38, UsStandardFanfold = 39, GermanStandardFanfold = 40, GermanLegalFanfold = 41, IsoB4 = 42, JapaneseDoublePostcard = 43, StandardPaper2 = 44, StandardPaper3 = 45, StandardPaper4 = 46, InviteEnvelope = 47, LetterExtraPaper = 50, LegalExtraPaper = 51, TabloidExtraPaper = 52, A4ExtraPaper = 53, LetterTransversePaper = 54, A4TransversePaper = 55, LetterExtraTransversePaper = 56, SuperaSuperaA4Paper = 57, SuperbSuperbA3Paper = 58, LetterPlusPaper = 59, A4PlusPaper = 60, A5TransversePaper = 61, JisB5TransversePaper = 62, A3ExtraPaper = 63, A5ExtraPaper = 64, IsoB5ExtraPaper = 65, A2Paper = 66, A3TransversePaper = 67, A3ExtraTransversePaper = 68 } public enum XLPageOrderValues { DownThenOver, OverThenDown } public enum XLShowCommentsValues { None, AtEnd, AsDisplayed } public enum XLPrintErrorValues { Blank, Dash, Displayed, NA } public interface IXLPageSetup { /// <summary> /// Gets an object to manage the print areas of the worksheet. /// </summary> IXLPrintAreas PrintAreas { get; } /// <summary> /// Gets the first row that will repeat on the top of the printed pages. /// <para>Use SetRowsToRepeatAtTop() to set the rows that will be repeated on the top of the printed pages.</para> /// </summary> Int32 FirstRowToRepeatAtTop { get; } /// <summary> /// Gets the last row that will repeat on the top of the printed pages. /// <para>Use SetRowsToRepeatAtTop() to set the rows that will be repeated on the top of the printed pages.</para> /// </summary> Int32 LastRowToRepeatAtTop { get; } /// <summary> /// Sets the rows to repeat on the top of the printed pages. /// </summary> /// <param name="range">The range of rows to repeat on the top of the printed pages.</param> void SetRowsToRepeatAtTop(String range); /// <summary> /// Sets the rows to repeat on the top of the printed pages. /// </summary> /// <param name="firstRowToRepeatAtTop">The first row to repeat at top.</param> /// <param name="lastRowToRepeatAtTop">The last row to repeat at top.</param> void SetRowsToRepeatAtTop(Int32 firstRowToRepeatAtTop, Int32 lastRowToRepeatAtTop); /// <summary>Gets the first column to repeat on the left of the printed pages.</summary> /// <value>The first column to repeat on the left of the printed pages.</value> Int32 FirstColumnToRepeatAtLeft { get; } /// <summary>Gets the last column to repeat on the left of the printed pages.</summary> /// <value>The last column to repeat on the left of the printed pages.</value> Int32 LastColumnToRepeatAtLeft { get; } /// <summary> /// Sets the rows to repeat on the left of the printed pages. /// </summary> /// <param name="firstColumnToRepeatAtLeft">The first column to repeat at left.</param> /// <param name="lastColumnToRepeatAtLeft">The last column to repeat at left.</param> void SetColumnsToRepeatAtLeft(Int32 firstColumnToRepeatAtLeft, Int32 lastColumnToRepeatAtLeft); /// <summary> /// Sets the rows to repeat on the left of the printed pages. /// </summary> /// <param name="range">The range of rows to repeat on the left of the printed pages.</param> void SetColumnsToRepeatAtLeft(String range); /// <summary>Gets or sets the page orientation for printing.</summary> /// <value>The page orientation.</value> XLPageOrientation PageOrientation { get; set; } /// <summary> /// Gets or sets the number of pages wide (horizontal) the worksheet will be printed on. /// <para>If you don't specify the PagesTall, Excel will adjust that value</para> /// <para>based on the contents of the worksheet and the PagesWide number.</para> /// <para>Setting this value will override the Scale value.</para> /// </summary> Int32 PagesWide { get; set; } /// <summary> /// Gets or sets the number of pages tall (vertical) the worksheet will be printed on. /// <para>If you don't specify the PagesWide, Excel will adjust that value</para> /// <para>based on the contents of the worksheet and the PagesTall number.</para> /// <para>Setting this value will override the Scale value.</para> /// </summary> Int32 PagesTall { get; set; } /// <summary> /// Gets or sets the scale at which the worksheet will be printed. /// <para>The worksheet will be printed on as many pages as necessary to print at the given scale.</para> /// <para>Setting this value will override the PagesWide and PagesTall values.</para> /// </summary> Int32 Scale { get; set; } /// <summary> /// Gets or sets the horizontal dpi for printing the worksheet. /// </summary> Int32 HorizontalDpi { get; set; } /// <summary> /// Gets or sets the vertical dpi for printing the worksheet. /// </summary> Int32 VerticalDpi { get; set; } /// <summary> /// Gets or sets the page number that will begin the printout. /// <para>For example, the first page of your printout could be numbered page 5.</para> /// </summary> UInt32? FirstPageNumber { get; set; } /// <summary> /// Gets or sets a value indicating whether the worksheet will be centered on the page horizontally. /// </summary> /// <value> /// <c>true</c> if the worksheet will be centered on the page horizontally; otherwise, <c>false</c>. /// </value> Boolean CenterHorizontally { get; set; } /// <summary> /// Gets or sets a value indicating whether the worksheet will be centered on the page vertically. /// </summary> /// <value> /// <c>true</c> if the worksheet will be centered on the page vartically; otherwise, <c>false</c>. /// </value> Boolean CenterVertically { get; set; } /// <summary> /// Sets the scale at which the worksheet will be printed. This is equivalent to setting the Scale property. /// <para>The worksheet will be printed on as many pages as necessary to print at the given scale.</para> /// <para>Setting this value will override the PagesWide and PagesTall values.</para> /// </summary> /// <param name="percentageOfNormalSize">The scale at which the worksheet will be printed.</param> void AdjustTo(Int32 percentageOfNormalSize); /// <summary> /// Gets or sets the number of pages the worksheet will be printed on. /// <para>This is equivalent to setting both PagesWide and PagesTall properties.</para> /// <para>Setting this value will override the Scale value.</para> /// </summary> /// <param name="pagesWide">The pages wide.</param> /// <param name="pagesTall">The pages tall.</param> void FitToPages(Int32 pagesWide, Int32 pagesTall); /// <summary> /// Gets or sets the size of the paper to print the worksheet. /// </summary> XLPaperSize PaperSize { get; set; } /// <summary> /// Gets an object to work with the page margins. /// </summary> IXLMargins Margins { get; } /// <summary> /// Gets an object to work with the page headers. /// </summary> IXLHeaderFooter Header { get; } /// <summary> /// Gets an object to work with the page footers. /// </summary> IXLHeaderFooter Footer { get; } /// <summary> /// Gets or sets a value indicating whether Excel will automatically adjust the font size to the scale of the worksheet. /// </summary> /// <value> /// <c>true</c> if Excel will automatically adjust the font size to the scale of the worksheet; otherwise, <c>false</c>. /// </value> Boolean ScaleHFWithDocument { get; set; } /// <summary> /// Gets or sets a value indicating whether the header and footer margins are aligned with the left and right margins of the worksheet. /// </summary> /// <value> /// <c>true</c> if the header and footer margins are aligned with the left and right margins of the worksheet; otherwise, <c>false</c>. /// </value> Boolean AlignHFWithMargins { get; set; } /// <summary> /// Gets or sets a value indicating whether the gridlines will be printed. /// </summary> /// <value> /// <c>true</c> if the gridlines will be printed; otherwise, <c>false</c>. /// </value> Boolean ShowGridlines { get; set; } /// <summary> /// Gets or sets a value indicating whether to show row numbers and column letters/numbers. /// </summary> /// <value> /// <c>true</c> to show row numbers and column letters/numbers; otherwise, <c>false</c>. /// </value> Boolean ShowRowAndColumnHeadings { get; set; } /// <summary> /// Gets or sets a value indicating whether the worksheet will be printed in black and white. /// </summary> /// <value> /// <c>true</c> if the worksheet will be printed in black and white; otherwise, <c>false</c>. /// </value> Boolean BlackAndWhite { get; set; } /// <summary> /// Gets or sets a value indicating whether the worksheet will be printed in draft quality. /// </summary> /// <value> /// <c>true</c> if the worksheet will be printed in draft quality; otherwise, <c>false</c>. /// </value> Boolean DraftQuality { get; set; } /// <summary> /// Gets or sets the page order for printing. /// </summary> XLPageOrderValues PageOrder { get; set; } /// <summary> /// Gets or sets how the comments will be printed. /// </summary> XLShowCommentsValues ShowComments { get; set; } /// <summary> /// Gets a list with the row breaks (for printing). /// </summary> List<Int32> RowBreaks { get; } /// <summary> /// Gets a list with the column breaks (for printing). /// </summary> List<Int32> ColumnBreaks { get; } /// <summary> /// Adds a horizontal page break after the given row. /// </summary> /// <param name="row">The row to insert the break.</param> void AddHorizontalPageBreak(Int32 row); /// <summary> /// Adds a vertical page break after the given column. /// </summary> /// <param name="column">The column to insert the break.</param> void AddVerticalPageBreak(Int32 column); /// <summary> /// Gets or sets how error values will be printed. /// </summary> XLPrintErrorValues PrintErrorValue { get; set; } IXLPageSetup SetPageOrientation(XLPageOrientation value); IXLPageSetup SetPagesWide(Int32 value); IXLPageSetup SetPagesTall(Int32 value); IXLPageSetup SetScale(Int32 value); IXLPageSetup SetHorizontalDpi(Int32 value); IXLPageSetup SetVerticalDpi(Int32 value); IXLPageSetup SetFirstPageNumber(UInt32? value); IXLPageSetup SetCenterHorizontally(); IXLPageSetup SetCenterHorizontally(Boolean value); IXLPageSetup SetCenterVertically(); IXLPageSetup SetCenterVertically(Boolean value); IXLPageSetup SetPaperSize(XLPaperSize value); IXLPageSetup SetScaleHFWithDocument(); IXLPageSetup SetScaleHFWithDocument(Boolean value); IXLPageSetup SetAlignHFWithMargins(); IXLPageSetup SetAlignHFWithMargins(Boolean value); IXLPageSetup SetShowGridlines(); IXLPageSetup SetShowGridlines(Boolean value); IXLPageSetup SetShowRowAndColumnHeadings(); IXLPageSetup SetShowRowAndColumnHeadings(Boolean value); IXLPageSetup SetBlackAndWhite(); IXLPageSetup SetBlackAndWhite(Boolean value); IXLPageSetup SetDraftQuality(); IXLPageSetup SetDraftQuality(Boolean value); IXLPageSetup SetPageOrder(XLPageOrderValues value); IXLPageSetup SetShowComments(XLShowCommentsValues value); IXLPageSetup SetPrintErrorValue(XLPrintErrorValues value); Boolean DifferentFirstPageOnHF { get; set; } IXLPageSetup SetDifferentFirstPageOnHF(); IXLPageSetup SetDifferentFirstPageOnHF(Boolean value); Boolean DifferentOddEvenPagesOnHF { get; set; } IXLPageSetup SetDifferentOddEvenPagesOnHF(); IXLPageSetup SetDifferentOddEvenPagesOnHF(Boolean value); } }
// // Copyright (c) 2004-2018 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using NLog.Common; using NLog.Config; using NLog.Internal.NetworkSenders; using NLog.Targets; using Xunit; public class NetworkTargetTests : NLogTestBase { [Fact] public void HappyPathDefaultsTest() { HappyPathTest(false, LineEndingMode.CRLF, "msg1", "msg2", "msg3"); } [Fact] public void HappyPathCRLFTest() { HappyPathTest(true, LineEndingMode.CRLF, "msg1", "msg2", "msg3"); } [Fact] public void HappyPathLFTest() { HappyPathTest(true, LineEndingMode.LF, "msg1", "msg2", "msg3"); } private void HappyPathTest(bool newLine, LineEndingMode lineEnding, params string[] messages) { var senderFactory = new MySenderFactory(); var target = new NetworkTarget(); target.Address = "tcp://someaddress/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.NewLine = newLine; target.LineEnding = lineEnding; target.KeepConnection = true; target.Initialize(null); var exceptions = new List<Exception>(); var mre = new ManualResetEvent(false); int remaining = 3; AsyncContinuation asyncContinuation = ex => { lock (exceptions) { exceptions.Add(ex); if (--remaining == 0) { mre.Set(); } } }; target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger", "msg1").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger", "msg2").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger", "msg3").WithContinuation(asyncContinuation)); mre.WaitOne(); foreach (var ex in exceptions) { if (ex != null) { Assert.True(false, ex.ToString()); } } Assert.Single(senderFactory.Senders); var sender = senderFactory.Senders[0]; target.Close(); // Get the length of all the messages and their line endings var eol = newLine ? lineEnding.NewLineCharacters : string.Empty; var eolLength = eol.Length; var length = messages.Sum(m => m.Length) + (eolLength * messages.Length); Assert.Equal(length, sender.MemoryStream.Length); Assert.Equal(string.Join(eol, messages) + eol, target.Encoding.GetString(sender.MemoryStream.GetBuffer(), 0, (int)sender.MemoryStream.Length)); // we invoke the sender for each message, each time sending 4 bytes var actual = senderFactory.Log.ToString(); Assert.True(actual.IndexOf("1: connect tcp://someaddress/") != -1); foreach (var message in messages) { Assert.True(actual.IndexOf($"1: send 0 {message.Length + eolLength}") != -1); } Assert.True(actual.IndexOf("1: close") != -1); } [Fact] public void NetworkTargetDefaultsTest() { var target = new NetworkTarget(); Assert.True(target.KeepConnection); Assert.False(target.NewLine); Assert.Equal("\r\n", target.LineEnding.NewLineCharacters); Assert.Equal(65000, target.MaxMessageSize); Assert.Equal(5, target.ConnectionCacheSize); Assert.Equal(0, target.MaxConnections); Assert.Equal(0, target.MaxQueueSize); Assert.Equal(Encoding.UTF8, target.Encoding); } [Fact] public void NetworkTargetMultipleConnectionsTest() { var senderFactory = new MySenderFactory(); var target = new NetworkTarget(); target.Address = "tcp://${logger}.company.lan/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.KeepConnection = true; target.Initialize(null); var exceptions = new List<Exception>(); var mre = new ManualResetEvent(false); int remaining = 3; AsyncContinuation asyncContinuation = ex => { lock (exceptions) { exceptions.Add(ex); if (--remaining == 0) { mre.Set(); } } }; target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg1").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "msg2").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger3", "msg3").WithContinuation(asyncContinuation)); mre.WaitOne(); foreach (var ex in exceptions) { if (ex != null) { Assert.True(false, ex.ToString()); } } mre.Reset(); AsyncContinuation flushContinuation = ex => { mre.Set(); }; target.Flush(flushContinuation); mre.WaitOne(); target.Close(); var actual = senderFactory.Log.ToString(); Assert.True(actual.IndexOf("1: connect tcp://logger1.company.lan/") != -1); Assert.True(actual.IndexOf("1: send 0 4") != -1); Assert.True(actual.IndexOf("2: connect tcp://logger2.company.lan/") != -1); Assert.True(actual.IndexOf("2: send 0 4") != -1); Assert.True(actual.IndexOf("3: connect tcp://logger3.company.lan/") != -1); Assert.True(actual.IndexOf("3: send 0 4") != -1); Assert.True(actual.IndexOf("1: flush") != -1); Assert.True(actual.IndexOf("2: flush") != -1); Assert.True(actual.IndexOf("3: flush") != -1); Assert.True(actual.IndexOf("1: close") != -1); Assert.True(actual.IndexOf("2: close") != -1); Assert.True(actual.IndexOf("3: close") != -1); } [Fact] public void NothingToFlushTest() { var senderFactory = new MySenderFactory(); var target = new NetworkTarget(); target.Address = "tcp://${logger}.company.lan/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.KeepConnection = true; target.Initialize(null); var mre = new ManualResetEvent(false); AsyncContinuation flushContinuation = ex => { mre.Set(); }; target.Flush(flushContinuation); mre.WaitOne(); target.Close(); string expectedLog = @""; Assert.Equal(expectedLog, senderFactory.Log.ToString()); } [Fact] public void NetworkTargetMultipleConnectionsWithCacheOverflowTest() { var senderFactory = new MySenderFactory(); var target = new NetworkTarget(); target.Address = "tcp://${logger}.company.lan/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.KeepConnection = true; target.ConnectionCacheSize = 2; target.Initialize(null); var exceptions = new List<Exception>(); var mre = new ManualResetEvent(false); int remaining = 6; AsyncContinuation asyncContinuation = ex => { lock (exceptions) { exceptions.Add(ex); if (--remaining == 0) { mre.Set(); } } }; // logger1 should be kept alive because it's being referenced frequently target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg1").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "msg2").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg3").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger3", "msg1").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg2").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "msg3").WithContinuation(asyncContinuation)); mre.WaitOne(); foreach (var ex in exceptions) { if (ex != null) { Assert.True(false, ex.ToString()); } } target.Close(); string result = senderFactory.Log.ToString(); Assert.True(result.IndexOf("1: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("1: send 0 4") != -1); Assert.True(result.IndexOf("2: connect tcp://logger2.company.lan/") != -1); Assert.True(result.IndexOf("2: send 0 4") != -1); Assert.True(result.IndexOf("1: send 0 4") != -1); Assert.True(result.IndexOf("2: close") != -1); Assert.True(result.IndexOf("3: connect tcp://logger3.company.lan/") != -1); Assert.True(result.IndexOf("3: send 0 4") != -1); Assert.True(result.IndexOf("1: send 0 4") != -1); Assert.True(result.IndexOf("3: close") != -1); Assert.True(result.IndexOf("4: connect tcp://logger2.company.lan/") != -1); Assert.True(result.IndexOf("4: send 0 4") != -1); Assert.True(result.IndexOf("1: close") != -1); Assert.True(result.IndexOf("4: close") != -1); } [Fact] public void NetworkTargetMultipleConnectionsWithoutKeepAliveTest() { var senderFactory = new MySenderFactory(); var target = new NetworkTarget(); target.Address = "tcp://${logger}.company.lan/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.KeepConnection = false; target.Initialize(null); var exceptions = new List<Exception>(); var mre = new ManualResetEvent(false); int remaining = 6; AsyncContinuation asyncContinuation = ex => { lock (exceptions) { exceptions.Add(ex); if (--remaining == 0) { mre.Set(); } } }; target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg1").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "msg2").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg3").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger3", "msg1").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "msg2").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "msg3").WithContinuation(asyncContinuation)); mre.WaitOne(); foreach (var ex in exceptions) { if (ex != null) { Assert.True(false, ex.ToString()); } } target.Close(); string result = senderFactory.Log.ToString(); Assert.True(result.IndexOf("1: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("1: send 0 4") != -1); Assert.True(result.IndexOf("1: close") != -1); Assert.True(result.IndexOf("2: connect tcp://logger2.company.lan/") != -1); Assert.True(result.IndexOf("2: send 0 4") != -1); Assert.True(result.IndexOf("2: close") != -1); Assert.True(result.IndexOf("3: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("3: send 0 4") != -1); Assert.True(result.IndexOf("3: close") != -1); Assert.True(result.IndexOf("4: connect tcp://logger3.company.lan/") != -1); Assert.True(result.IndexOf("4: send 0 4") != -1); Assert.True(result.IndexOf("4: close") != -1); Assert.True(result.IndexOf("5: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("5: send 0 4") != -1); Assert.True(result.IndexOf("5: close") != -1); Assert.True(result.IndexOf("6: connect tcp://logger2.company.lan/") != -1); Assert.True(result.IndexOf("6: send 0 4") != -1); Assert.True(result.IndexOf("6: close") != -1); } [Fact] public void NetworkTargetMultipleConnectionsWithMessageSplitTest() { var senderFactory = new MySenderFactory(); var target = new NetworkTarget(); target.Address = "tcp://${logger}.company.lan/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.KeepConnection = true; target.MaxMessageSize = 9; target.OnOverflow = NetworkTargetOverflowAction.Split; target.Initialize(null); var exceptions = new List<Exception>(); var mre = new ManualResetEvent(false); int remaining = 3; AsyncContinuation asyncContinuation = ex => { lock (exceptions) { exceptions.Add(ex); if (--remaining == 0) { mre.Set(); } } }; target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "012345678901234567890123456789").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "012345678901234").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "012345678901234567890123").WithContinuation(asyncContinuation)); mre.WaitOne(); foreach (var ex in exceptions) { if (ex != null) { Assert.True(false, ex.ToString()); } } target.Close(); var result = senderFactory.Log.ToString(); Assert.True(result.IndexOf("1: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("1: send 0 9") != -1); Assert.True(result.IndexOf("1: send 9 9") != -1); Assert.True(result.IndexOf("1: send 18 9") != -1); Assert.True(result.IndexOf("1: send 27 3") != -1); Assert.True(result.IndexOf("1: send 0 9") != -1); Assert.True(result.IndexOf("1: send 9 6") != -1); Assert.True(result.IndexOf("2: connect tcp://logger2.company.lan/") != -1); Assert.True(result.IndexOf("2: send 0 9") != -1); Assert.True(result.IndexOf("2: send 9 9") != -1); Assert.True(result.IndexOf("2: send 18 6") != -1); Assert.True(result.IndexOf("1: close") != -1); Assert.True(result.IndexOf("2: close") != -1); } [Fact] public void NetworkTargetMultipleConnectionsWithMessageDiscardTest() { var senderFactory = new MySenderFactory(); var target = new NetworkTarget(); target.Address = "tcp://${logger}.company.lan/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.KeepConnection = true; target.MaxMessageSize = 10; target.OnOverflow = NetworkTargetOverflowAction.Discard; target.Initialize(null); var exceptions = new List<Exception>(); var mre = new ManualResetEvent(false); int remaining = 3; AsyncContinuation asyncContinuation = ex => { lock (exceptions) { exceptions.Add(ex); if (--remaining == 0) { mre.Set(); } } }; target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "012345678901234").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "01234").WithContinuation(asyncContinuation)); mre.WaitOne(); foreach (var ex in exceptions) { if (ex != null) { Assert.True(false, ex.ToString()); } } target.Close(); string result = senderFactory.Log.ToString(); Assert.True(result.IndexOf("1: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("1: send 0 7") != -1); Assert.True(result.IndexOf("2: connect tcp://logger2.company.lan/") != -1); Assert.True(result.IndexOf("2: send 0 5") != -1); Assert.True(result.IndexOf("1: close") != -1); Assert.True(result.IndexOf("2: close") != -1); } [Fact] public void NetworkTargetMultipleConnectionsWithMessageErrorTest() { var senderFactory = new MySenderFactory(); var target = new NetworkTarget(); target.Address = "tcp://${logger}.company.lan/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.KeepConnection = true; target.MaxMessageSize = 10; target.OnOverflow = NetworkTargetOverflowAction.Error; target.Initialize(null); var exceptions = new List<Exception>(); var mre = new ManualResetEvent(false); int remaining = 3; AsyncContinuation asyncContinuation = ex => { lock (exceptions) { exceptions.Add(ex); if (--remaining == 0) { mre.Set(); } } }; target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "012345678901234").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger2", "01234").WithContinuation(asyncContinuation)); mre.WaitOne(); Assert.Null(exceptions[0]); Assert.NotNull(exceptions[1]); Assert.Equal("Attempted to send a message larger than MaxMessageSize (10). Actual size was: 15. Adjust OnOverflow and MaxMessageSize parameters accordingly.", exceptions[1].Message); Assert.Null(exceptions[2]); target.Close(); string result = senderFactory.Log.ToString(); Assert.True(result.IndexOf("1: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("1: send 0 7") != -1); Assert.True(result.IndexOf("1: close") != -1); Assert.True(result.IndexOf("2: connect tcp://logger2.company.lan/") != -1); Assert.True(result.IndexOf("2: send 0 5") != -1); Assert.True(result.IndexOf("2: close") != -1); } [Fact] public void NetworkTargetSendFailureTests() { var senderFactory = new MySenderFactory() { FailCounter = 3, // first 3 sends will fail }; var target = new NetworkTarget(); target.Address = "tcp://${logger}.company.lan/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.KeepConnection = true; target.OnOverflow = NetworkTargetOverflowAction.Discard; target.Initialize(null); var exceptions = new List<Exception>(); var mre = new ManualResetEvent(false); int remaining = 5; AsyncContinuation asyncContinuation = ex => { lock (exceptions) { exceptions.Add(ex); if (--remaining == 0) { mre.Set(); } } }; target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "01234").WithContinuation(asyncContinuation)); mre.WaitOne(); Assert.NotNull(exceptions[0]); Assert.NotNull(exceptions[1]); Assert.NotNull(exceptions[2]); Assert.Null(exceptions[3]); Assert.Null(exceptions[4]); target.Close(); var result = senderFactory.Log.ToString(); Assert.True(result.IndexOf("1: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("1: send 0 7") != -1); Assert.True(result.IndexOf("1: failed") != -1); Assert.True(result.IndexOf("1: close") != -1); Assert.True(result.IndexOf("2: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("2: send 0 7") != -1); Assert.True(result.IndexOf("2: failed") != -1); Assert.True(result.IndexOf("2: close") != -1); Assert.True(result.IndexOf("3: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("3: send 0 7") != -1); Assert.True(result.IndexOf("3: failed") != -1); Assert.True(result.IndexOf("3: close") != -1); Assert.True(result.IndexOf("4: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("4: send 0 7") != -1); Assert.True(result.IndexOf("4: send 0 5") != -1); Assert.True(result.IndexOf("4: close") != -1); } [Fact] public void NetworkTargetTcpTest() { NetworkTarget target; target = new NetworkTarget() { Address = "tcp://127.0.0.1:3004", Layout = "${message}\n", KeepConnection = true, }; string expectedResult = string.Empty; using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Exception receiveException = null; var resultStream = new MemoryStream(); var receiveFinished = new ManualResetEvent(false); listener.Bind(new IPEndPoint(IPAddress.Loopback, 3004)); listener.Listen(10); listener.BeginAccept( result => { try { byte[] buffer = new byte[4096]; using (Socket connectedSocket = listener.EndAccept(result)) { int got; while ((got = connectedSocket.Receive(buffer, 0, buffer.Length, SocketFlags.None)) > 0) { resultStream.Write(buffer, 0, got); } } } catch (Exception ex) { Console.WriteLine("Receive exception {0}", ex); receiveException = ex; } finally { receiveFinished.Set(); } }, null); target.Initialize(new LoggingConfiguration()); int pendingWrites = 100; var writeCompleted = new ManualResetEvent(false); var exceptions = new List<Exception>(); AsyncContinuation writeFinished = ex => { lock (exceptions) { // Console.WriteLine("{0} Write finished {1}", pendingWrites, ex); exceptions.Add(ex); pendingWrites--; if (pendingWrites == 0) { writeCompleted.Set(); } } }; int toWrite = pendingWrites; for (int i = 0; i < toWrite; ++i) { var ev = new LogEventInfo(LogLevel.Info, "logger1", "messagemessagemessagemessagemessage" + i).WithContinuation(writeFinished); target.WriteAsyncLogEvent(ev); expectedResult += "messagemessagemessagemessagemessage" + i + "\n"; } Assert.True(writeCompleted.WaitOne(10000, false), "Writes did not complete"); target.Close(); Assert.True(receiveFinished.WaitOne(10000, false), "Receive did not complete"); string resultString = Encoding.UTF8.GetString(resultStream.GetBuffer(), 0, (int)resultStream.Length); Assert.Null(receiveException); Assert.Equal(expectedResult, resultString); } } [Fact] public void NetworkTargetUdpTest() { var target = new NetworkTarget() { Address = "udp://127.0.0.1:3002", Layout = "${message}\n", KeepConnection = true, }; string expectedResult = string.Empty; using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { Exception receiveException = null; var receivedMessages = new List<string>(); var receiveFinished = new ManualResetEvent(false); byte[] receiveBuffer = new byte[4096]; listener.Bind(new IPEndPoint(IPAddress.Loopback, 3002)); EndPoint remoteEndPoint = null; AsyncCallback receivedDatagram = null; receivedDatagram = result => { try { int got = listener.EndReceiveFrom(result, ref remoteEndPoint); string message = Encoding.UTF8.GetString(receiveBuffer, 0, got); lock (receivedMessages) { receivedMessages.Add(message); if (receivedMessages.Count == 100) { receiveFinished.Set(); } } remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); listener.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, receivedDatagram, null); } catch (Exception ex) { receiveException = ex; } }; remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); listener.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, receivedDatagram, null); target.Initialize(new LoggingConfiguration()); int pendingWrites = 100; var writeCompleted = new ManualResetEvent(false); var exceptions = new List<Exception>(); AsyncContinuation writeFinished = ex => { lock (exceptions) { exceptions.Add(ex); pendingWrites--; if (pendingWrites == 0) { writeCompleted.Set(); } } }; int toWrite = pendingWrites; for (int i = 0; i < toWrite; ++i) { var ev = new LogEventInfo(LogLevel.Info, "logger1", "message" + i).WithContinuation(writeFinished); target.WriteAsyncLogEvent(ev); expectedResult += "message" + i + "\n"; } Assert.True(writeCompleted.WaitOne(10000, false)); target.Close(); Assert.True(receiveFinished.WaitOne(10000, false)); Assert.Equal(toWrite, receivedMessages.Count); for (int i = 0; i < toWrite; ++i) { Assert.True(receivedMessages.Contains("message" + i + "\n"), "Message #" + i + " not received."); } Assert.Null(receiveException); } } [Fact] public void NetworkTargetNotConnectedTest() { var target = new NetworkTarget() { Address = "tcp4://127.0.0.1:33415", Layout = "${message}\n", KeepConnection = true, }; target.Initialize(new LoggingConfiguration()); int toWrite = 10; int pendingWrites = toWrite; var writeCompleted = new ManualResetEvent(false); var exceptions = new List<Exception>(); AsyncContinuation writeFinished = ex => { lock (exceptions) { exceptions.Add(ex); pendingWrites--; if (pendingWrites == 0) { writeCompleted.Set(); } } }; for (int i = 0; i < toWrite; ++i) { var ev = new LogEventInfo(LogLevel.Info, "logger1", "message" + i).WithContinuation(writeFinished); target.WriteAsyncLogEvent(ev); } writeCompleted.WaitOne(); // no exception target.Close(); Assert.Equal(toWrite, exceptions.Count); foreach (var ex in exceptions) { Assert.NotNull(ex); } } [Fact] public void NetworkTargetSendFailureWithoutKeepAliveTests() { var senderFactory = new MySenderFactory() { FailCounter = 3, // first 3 sends will fail }; var target = new NetworkTarget(); target.Address = "tcp://${logger}.company.lan/"; target.SenderFactory = senderFactory; target.Layout = "${message}"; target.KeepConnection = false; target.OnOverflow = NetworkTargetOverflowAction.Discard; target.Initialize(null); var exceptions = new List<Exception>(); var mre = new ManualResetEvent(false); int remaining = 5; AsyncContinuation asyncContinuation = ex => { lock (exceptions) { exceptions.Add(ex); if (--remaining == 0) { mre.Set(); } } }; target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "0123456").WithContinuation(asyncContinuation)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "logger1", "01234").WithContinuation(asyncContinuation)); mre.WaitOne(); Assert.NotNull(exceptions[0]); Assert.NotNull(exceptions[1]); Assert.NotNull(exceptions[2]); Assert.Null(exceptions[3]); Assert.Null(exceptions[4]); target.Close(); var result = senderFactory.Log.ToString(); Assert.True(result.IndexOf("1: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("1: send 0 7") != -1); Assert.True(result.IndexOf("1: failed") != -1); Assert.True(result.IndexOf("1: close") != -1); Assert.True(result.IndexOf("2: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("2: send 0 7") != -1); Assert.True(result.IndexOf("2: failed") != -1); Assert.True(result.IndexOf("2: close") != -1); Assert.True(result.IndexOf("3: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("3: send 0 7") != -1); Assert.True(result.IndexOf("3: failed") != -1); Assert.True(result.IndexOf("3: close") != -1); Assert.True(result.IndexOf("4: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("4: send 0 7") != -1); Assert.True(result.IndexOf("4: close") != -1); Assert.True(result.IndexOf("5: connect tcp://logger1.company.lan/") != -1); Assert.True(result.IndexOf("5: send 0 5") != -1); Assert.True(result.IndexOf("5: close") != -1); } internal class MySenderFactory : INetworkSenderFactory { internal List<MyNetworkSender> Senders = new List<MyNetworkSender>(); internal StringWriter Log = new StringWriter(); private int idCounter; public NetworkSender Create(string url, int maximumQueueSize) { var sender = new MyNetworkSender(url, ++idCounter, Log, this); Senders.Add(sender); return sender; } public int FailCounter { get; set; } } internal class MyNetworkSender : NetworkSender { private readonly int id; private readonly TextWriter log; private readonly MySenderFactory senderFactory; internal MemoryStream MemoryStream { get; set; } public MyNetworkSender(string url, int id, TextWriter log, MySenderFactory senderFactory) : base(url) { this.id = id; this.log = log; this.senderFactory = senderFactory; MemoryStream = new MemoryStream(); } protected override void DoInitialize() { base.DoInitialize(); log.WriteLine("{0}: connect {1}", id, Address); } protected override void DoFlush(AsyncContinuation continuation) { log.WriteLine("{0}: flush", id); continuation(null); } protected override void DoClose(AsyncContinuation continuation) { log.WriteLine("{0}: close", id); continuation(null); } protected override void DoSend(byte[] bytes, int offset, int length, AsyncContinuation asyncContinuation) { log.WriteLine("{0}: send {1} {2}", id, offset, length); MemoryStream.Write(bytes, offset, length); if (senderFactory.FailCounter > 0) { log.WriteLine("{0}: failed", id); senderFactory.FailCounter--; asyncContinuation(new IOException("some IO error has occured")); } else { asyncContinuation(null); } } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.TeamFoundation.TestClient.PublishTestResults; using Microsoft.TeamFoundation.TestManagement.WebApi; using Microsoft.VisualStudio.Services.WebApi; using Microsoft.TeamFoundation.Core.WebApi; using System; using System.Linq; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.Services.Agent.Worker.TestResults.Utils; using ITestResultsServer = Microsoft.VisualStudio.Services.Agent.Worker.LegacyTestResults.ITestResultsServer; namespace Microsoft.VisualStudio.Services.Agent.Worker.TestResults { [ServiceLocator(Default = typeof(TestDataPublisher))] public interface ITestDataPublisher : IAgentService { void InitializePublisher(IExecutionContext executionContext, string projectName, VssConnection connection, string testRunner); Task<bool> PublishAsync(TestRunContext runContext, List<string> testResultFiles, PublishOptions publishOptions, CancellationToken cancellationToken = default(CancellationToken)); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA2000:Dispose objects before losing scope", MessageId = "CommandTraceListener")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1001:Types that own disposable fields should be disposable", MessageId = "DisposableFieldsArePassedIn")] public sealed class TestDataPublisher : AgentService, ITestDataPublisher { private IExecutionContext _executionContext; private string _projectName; private ITestRunPublisher _testRunPublisher; private ITestLogStore _testLogStore; private IParser _parser; private VssConnection _connection; private IFeatureFlagService _featureFlagService; private string _testRunner; private bool _calculateTestRunSummary; private TestRunDataPublisherHelper _testRunPublisherHelper; private ITestResultsServer _testResultsServer; public void InitializePublisher(IExecutionContext context, string projectName, VssConnection connection, string testRunner) { Trace.Entering(); _executionContext = context; _projectName = projectName; _connection = connection; _testRunner = testRunner; _testRunPublisher = new TestRunPublisher(connection, new CommandTraceListener(context)); _testLogStore = new TestLogStore(connection, new CommandTraceListener(context)); _testResultsServer = HostContext.GetService<ITestResultsServer>(); _testResultsServer.InitializeServer(connection, _executionContext); var extensionManager = HostContext.GetService<IExtensionManager>(); _featureFlagService = HostContext.GetService<IFeatureFlagService>(); _parser = (extensionManager.GetExtensions<IParser>()).FirstOrDefault(x => _testRunner.Equals(x.Name, StringComparison.OrdinalIgnoreCase)); _testRunPublisherHelper = new TestRunDataPublisherHelper(_executionContext, _testRunPublisher, null, _testResultsServer); Trace.Leaving(); } public async Task<bool> PublishAsync(TestRunContext runContext, List<string> testResultFiles, PublishOptions publishOptions, CancellationToken cancellationToken = default(CancellationToken)) { try { TestDataProvider testDataProvider = ParseTestResultsFile(runContext, testResultFiles); var publishTasks = new List<Task>(); if (testDataProvider != null){ var testRunData = testDataProvider.GetTestRunData(); //publishing run level attachment Task<IList<TestRun>> publishtestRunDataTask = Task.Run(() => _testRunPublisher.PublishTestRunDataAsync(runContext, _projectName, testRunData, publishOptions, cancellationToken)); Task uploadBuildDataAttachmentTask = Task.Run(() => UploadBuildDataAttachment(runContext, testDataProvider.GetBuildData(), cancellationToken)); publishTasks.Add(publishtestRunDataTask); //publishing build level attachment publishTasks.Add(uploadBuildDataAttachmentTask); await Task.WhenAll(publishTasks); IList<TestRun> publishedRuns = publishtestRunDataTask.Result; _calculateTestRunSummary = _featureFlagService.GetFeatureFlagState(TestResultsConstants.CalculateTestRunSummaryFeatureFlag, TestResultsConstants.TFSServiceInstanceGuid); var isTestRunOutcomeFailed = GetTestRunOutcome(_executionContext, testRunData, out TestRunSummary testRunSummary); // Storing testrun summary in environment variable, which will be read by PublishPipelineMetadataTask and publish to evidence store. if(_calculateTestRunSummary) { TestResultUtils.StoreTestRunSummaryInEnvVar(_executionContext, testRunSummary, _testRunner, "PublishTestResults"); } // Check failed results for flaky aware // Fallback to flaky aware if there are any failures. bool isFlakyCheckEnabled = _featureFlagService.GetFeatureFlagState(TestResultsConstants.EnableFlakyCheckInAgentFeatureFlag, TestResultsConstants.TCMServiceInstanceGuid); if (isTestRunOutcomeFailed && isFlakyCheckEnabled) { var runOutcome = _testRunPublisherHelper.CheckRunsForFlaky(publishedRuns, _projectName); if (runOutcome != null && runOutcome.HasValue) { isTestRunOutcomeFailed = runOutcome.Value; } } return isTestRunOutcomeFailed; } return false; } catch (Exception ex) { _executionContext.Warning("Failed to publish test run data: "+ ex.ToString()); } return false; } private TestDataProvider ParseTestResultsFile(TestRunContext runContext, List<string> testResultFiles) { if (_parser == null) { throw new ArgumentException("Unknown test runner"); } return _parser.ParseTestResultFiles(_executionContext, runContext, testResultFiles); } private bool GetTestRunOutcome(IExecutionContext executionContext, IList<TestRunData> testRunDataList, out TestRunSummary testRunSummary) { bool anyFailedTests = false; testRunSummary = new TestRunSummary(); foreach (var testRunData in testRunDataList) { foreach (var testCaseResult in testRunData.TestResults) { testRunSummary.Total += 1; Enum.TryParse(testCaseResult.Outcome, out TestOutcome outcome); switch(outcome) { case TestOutcome.Failed: case TestOutcome.Aborted: testRunSummary.Failed += 1; anyFailedTests = true; break; case TestOutcome.Passed: testRunSummary.Passed += 1; break; case TestOutcome.Inconclusive: testRunSummary.Skipped += 1; break; default: break; } if(!_calculateTestRunSummary && anyFailedTests) { return anyFailedTests; } } } return anyFailedTests; } private async Task UploadRunDataAttachment(TestRunContext runContext, List<TestRunData> testRunData, PublishOptions publishOptions, CancellationToken cancellationToken = default(CancellationToken)) { await _testRunPublisher.PublishTestRunDataAsync(runContext, _projectName, testRunData, publishOptions, cancellationToken); } private async Task UploadBuildDataAttachment(TestRunContext runContext, List<BuildData> buildDataList, CancellationToken cancellationToken = default(CancellationToken)) { _executionContext.Debug("Uploading build level attachements individually"); Guid projectId = await GetProjectId(_projectName); var attachFilesTasks = new List<Task>(); HashSet<BuildAttachment> attachments = new HashSet<BuildAttachment>(new BuildAttachmentComparer()); foreach (var buildData in buildDataList) { attachFilesTasks.AddRange(buildData.BuildAttachments .Select( async attachment => { if (attachments.Contains(attachment)) { _executionContext.Debug($"Skipping upload of {attachment.Filename} as it was already uploaded."); await Task.Yield(); } else { attachments.Add(attachment); await UploadTestBuildLog(projectId, attachment, runContext, cancellationToken); } }) ); } _executionContext.Debug($"Total build level attachments: {attachFilesTasks.Count}."); await Task.WhenAll(attachFilesTasks); } private async Task UploadTestBuildLog(Guid projectId, BuildAttachment buildAttachment, TestRunContext runContext, CancellationToken cancellationToken) { await _testLogStore.UploadTestBuildLogAsync(projectId, runContext.BuildId, buildAttachment.TestLogType, buildAttachment.Filename, buildAttachment.Metadata, null, buildAttachment.AllowDuplicateUploads, buildAttachment.TestLogCompressionType, cancellationToken); } private async Task<Guid> GetProjectId(string projectName) { var _projectClient = _connection.GetClient<ProjectHttpClient>(); TeamProject proj = null; try { proj = await _projectClient.GetProject(projectName); } catch (Exception ex) { _executionContext.Warning("Get project failed" + projectName + " , exception: " + ex); } return proj.Id; } } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace Discord { [DebuggerDisplay(@"{DebuggerDisplay,nq}")] public struct GuildPermissions { /// <summary> Gets a blank <see cref="GuildPermissions"/> that grants no permissions. </summary> public static readonly GuildPermissions None = new GuildPermissions(); /// <summary> Gets a <see cref="GuildPermissions"/> that grants all guild permissions for webhook users. </summary> public static readonly GuildPermissions Webhook = new GuildPermissions(0b00000_0000000_0001101100000_000000); /// <summary> Gets a <see cref="GuildPermissions"/> that grants all guild permissions. </summary> public static readonly GuildPermissions All = new GuildPermissions(0b11111_1111111_1111111111111_111111); /// <summary> Gets a packed value representing all the permissions in this <see cref="GuildPermissions"/>. </summary> public ulong RawValue { get; } /// <summary> If <c>true</c>, a user may create invites. </summary> public bool CreateInstantInvite => Permissions.GetValue(RawValue, GuildPermission.CreateInstantInvite); /// <summary> If <c>true</c>, a user may ban users from the guild. </summary> public bool BanMembers => Permissions.GetValue(RawValue, GuildPermission.BanMembers); /// <summary> If <c>true</c>, a user may kick users from the guild. </summary> public bool KickMembers => Permissions.GetValue(RawValue, GuildPermission.KickMembers); /// <summary> If <c>true</c>, a user is granted all permissions, and cannot have them revoked via channel permissions. </summary> public bool Administrator => Permissions.GetValue(RawValue, GuildPermission.Administrator); /// <summary> If <c>true</c>, a user may create, delete and modify channels. </summary> public bool ManageChannels => Permissions.GetValue(RawValue, GuildPermission.ManageChannels); /// <summary> If <c>true</c>, a user may adjust guild properties. </summary> public bool ManageGuild => Permissions.GetValue(RawValue, GuildPermission.ManageGuild); /// <summary> If <c>true</c>, a user may add reactions. </summary> public bool AddReactions => Permissions.GetValue(RawValue, GuildPermission.AddReactions); /// <summary> If <c>true</c>, a user may view the audit log. </summary> public bool ViewAuditLog => Permissions.GetValue(RawValue, GuildPermission.ViewAuditLog); /// <summary> If <c>true</c>, a user may view the guild insights. </summary> public bool ViewGuildInsights => Permissions.GetValue(RawValue, GuildPermission.ViewGuildInsights); /// <summary> If True, a user may join channels. </summary> [Obsolete("Use ViewChannel instead.")] public bool ReadMessages => ViewChannel; /// <summary> If True, a user may view channels. </summary> public bool ViewChannel => Permissions.GetValue(RawValue, GuildPermission.ViewChannel); /// <summary> If True, a user may send messages. </summary> public bool SendMessages => Permissions.GetValue(RawValue, GuildPermission.SendMessages); /// <summary> If <c>true</c>, a user may send text-to-speech messages. </summary> public bool SendTTSMessages => Permissions.GetValue(RawValue, GuildPermission.SendTTSMessages); /// <summary> If <c>true</c>, a user may delete messages. </summary> public bool ManageMessages => Permissions.GetValue(RawValue, GuildPermission.ManageMessages); /// <summary> If <c>true</c>, Discord will auto-embed links sent by this user. </summary> public bool EmbedLinks => Permissions.GetValue(RawValue, GuildPermission.EmbedLinks); /// <summary> If <c>true</c>, a user may send files. </summary> public bool AttachFiles => Permissions.GetValue(RawValue, GuildPermission.AttachFiles); /// <summary> If <c>true</c>, a user may read previous messages. </summary> public bool ReadMessageHistory => Permissions.GetValue(RawValue, GuildPermission.ReadMessageHistory); /// <summary> If <c>true</c>, a user may mention @everyone. </summary> public bool MentionEveryone => Permissions.GetValue(RawValue, GuildPermission.MentionEveryone); /// <summary> If <c>true</c>, a user may use custom emoji from other guilds. </summary> public bool UseExternalEmojis => Permissions.GetValue(RawValue, GuildPermission.UseExternalEmojis); /// <summary> If <c>true</c>, a user may connect to a voice channel. </summary> public bool Connect => Permissions.GetValue(RawValue, GuildPermission.Connect); /// <summary> If <c>true</c>, a user may speak in a voice channel. </summary> public bool Speak => Permissions.GetValue(RawValue, GuildPermission.Speak); /// <summary> If <c>true</c>, a user may mute users. </summary> public bool MuteMembers => Permissions.GetValue(RawValue, GuildPermission.MuteMembers); /// <summary> If <c>true</c>, a user may deafen users. </summary> public bool DeafenMembers => Permissions.GetValue(RawValue, GuildPermission.DeafenMembers); /// <summary> If <c>true</c>, a user may move other users between voice channels. </summary> public bool MoveMembers => Permissions.GetValue(RawValue, GuildPermission.MoveMembers); /// <summary> If <c>true</c>, a user may use voice-activity-detection rather than push-to-talk. </summary> public bool UseVAD => Permissions.GetValue(RawValue, GuildPermission.UseVAD); /// <summary> If True, a user may use priority speaker in a voice channel. </summary> public bool PrioritySpeaker => Permissions.GetValue(RawValue, GuildPermission.PrioritySpeaker); /// <summary> If True, a user may stream video in a voice channel. </summary> public bool Stream => Permissions.GetValue(RawValue, GuildPermission.Stream); /// <summary> If <c>true</c>, a user may change their own nickname. </summary> public bool ChangeNickname => Permissions.GetValue(RawValue, GuildPermission.ChangeNickname); /// <summary> If <c>true</c>, a user may change the nickname of other users. </summary> public bool ManageNicknames => Permissions.GetValue(RawValue, GuildPermission.ManageNicknames); /// <summary> If <c>true</c>, a user may adjust roles. </summary> public bool ManageRoles => Permissions.GetValue(RawValue, GuildPermission.ManageRoles); /// <summary> If <c>true</c>, a user may edit the webhooks for this guild. </summary> public bool ManageWebhooks => Permissions.GetValue(RawValue, GuildPermission.ManageWebhooks); /// <summary> If <c>true</c>, a user may edit the emojis for this guild. </summary> public bool ManageEmojis => Permissions.GetValue(RawValue, GuildPermission.ManageEmojis); /// <summary> Creates a new <see cref="GuildPermissions"/> with the provided packed value. </summary> public GuildPermissions(ulong rawValue) { RawValue = rawValue; } private GuildPermissions(ulong initialValue, bool? createInstantInvite = null, bool? kickMembers = null, bool? banMembers = null, bool? administrator = null, bool? manageChannels = null, bool? manageGuild = null, bool? addReactions = null, bool? viewAuditLog = null, bool? viewGuildInsights = null, bool? viewChannel = null, bool? sendMessages = null, bool? sendTTSMessages = null, bool? manageMessages = null, bool? embedLinks = null, bool? attachFiles = null, bool? readMessageHistory = null, bool? mentionEveryone = null, bool? useExternalEmojis = null, bool? connect = null, bool? speak = null, bool? muteMembers = null, bool? deafenMembers = null, bool? moveMembers = null, bool? useVoiceActivation = null, bool? prioritySpeaker = null, bool? stream = null, bool? changeNickname = null, bool? manageNicknames = null, bool? manageRoles = null, bool? manageWebhooks = null, bool? manageEmojis = null) { ulong value = initialValue; Permissions.SetValue(ref value, createInstantInvite, GuildPermission.CreateInstantInvite); Permissions.SetValue(ref value, banMembers, GuildPermission.BanMembers); Permissions.SetValue(ref value, kickMembers, GuildPermission.KickMembers); Permissions.SetValue(ref value, administrator, GuildPermission.Administrator); Permissions.SetValue(ref value, manageChannels, GuildPermission.ManageChannels); Permissions.SetValue(ref value, manageGuild, GuildPermission.ManageGuild); Permissions.SetValue(ref value, addReactions, GuildPermission.AddReactions); Permissions.SetValue(ref value, viewAuditLog, GuildPermission.ViewAuditLog); Permissions.SetValue(ref value, viewGuildInsights, GuildPermission.ViewGuildInsights); Permissions.SetValue(ref value, viewChannel, GuildPermission.ViewChannel); Permissions.SetValue(ref value, sendMessages, GuildPermission.SendMessages); Permissions.SetValue(ref value, sendTTSMessages, GuildPermission.SendTTSMessages); Permissions.SetValue(ref value, manageMessages, GuildPermission.ManageMessages); Permissions.SetValue(ref value, embedLinks, GuildPermission.EmbedLinks); Permissions.SetValue(ref value, attachFiles, GuildPermission.AttachFiles); Permissions.SetValue(ref value, readMessageHistory, GuildPermission.ReadMessageHistory); Permissions.SetValue(ref value, mentionEveryone, GuildPermission.MentionEveryone); Permissions.SetValue(ref value, useExternalEmojis, GuildPermission.UseExternalEmojis); Permissions.SetValue(ref value, connect, GuildPermission.Connect); Permissions.SetValue(ref value, speak, GuildPermission.Speak); Permissions.SetValue(ref value, muteMembers, GuildPermission.MuteMembers); Permissions.SetValue(ref value, deafenMembers, GuildPermission.DeafenMembers); Permissions.SetValue(ref value, moveMembers, GuildPermission.MoveMembers); Permissions.SetValue(ref value, useVoiceActivation, GuildPermission.UseVAD); Permissions.SetValue(ref value, prioritySpeaker, GuildPermission.PrioritySpeaker); Permissions.SetValue(ref value, stream, GuildPermission.Stream); Permissions.SetValue(ref value, changeNickname, GuildPermission.ChangeNickname); Permissions.SetValue(ref value, manageNicknames, GuildPermission.ManageNicknames); Permissions.SetValue(ref value, manageRoles, GuildPermission.ManageRoles); Permissions.SetValue(ref value, manageWebhooks, GuildPermission.ManageWebhooks); Permissions.SetValue(ref value, manageEmojis, GuildPermission.ManageEmojis); RawValue = value; } /// <summary> Creates a new <see cref="GuildPermissions"/> structure with the provided permissions. </summary> public GuildPermissions( bool createInstantInvite = false, bool kickMembers = false, bool banMembers = false, bool administrator = false, bool manageChannels = false, bool manageGuild = false, bool addReactions = false, bool viewAuditLog = false, bool viewGuildInsights = false, bool viewChannel = false, bool sendMessages = false, bool sendTTSMessages = false, bool manageMessages = false, bool embedLinks = false, bool attachFiles = false, bool readMessageHistory = false, bool mentionEveryone = false, bool useExternalEmojis = false, bool connect = false, bool speak = false, bool muteMembers = false, bool deafenMembers = false, bool moveMembers = false, bool useVoiceActivation = false, bool prioritySpeaker = false, bool stream = false, bool changeNickname = false, bool manageNicknames = false, bool manageRoles = false, bool manageWebhooks = false, bool manageEmojis = false) : this(0, createInstantInvite: createInstantInvite, manageRoles: manageRoles, kickMembers: kickMembers, banMembers: banMembers, administrator: administrator, manageChannels: manageChannels, manageGuild: manageGuild, addReactions: addReactions, viewAuditLog: viewAuditLog, viewGuildInsights: viewGuildInsights, viewChannel: viewChannel, sendMessages: sendMessages, sendTTSMessages: sendTTSMessages, manageMessages: manageMessages, embedLinks: embedLinks, attachFiles: attachFiles, readMessageHistory: readMessageHistory, mentionEveryone: mentionEveryone, useExternalEmojis: useExternalEmojis, connect: connect, speak: speak, muteMembers: muteMembers, deafenMembers: deafenMembers, moveMembers: moveMembers, useVoiceActivation: useVoiceActivation, prioritySpeaker: prioritySpeaker, stream: stream, changeNickname: changeNickname, manageNicknames: manageNicknames, manageWebhooks: manageWebhooks, manageEmojis: manageEmojis) { } /// <summary> Creates a new <see cref="GuildPermissions"/> from this one, changing the provided non-null permissions. </summary> public GuildPermissions Modify( bool? createInstantInvite = null, bool? kickMembers = null, bool? banMembers = null, bool? administrator = null, bool? manageChannels = null, bool? manageGuild = null, bool? addReactions = null, bool? viewAuditLog = null, bool? viewGuildInsights = null, bool? viewChannel = null, bool? sendMessages = null, bool? sendTTSMessages = null, bool? manageMessages = null, bool? embedLinks = null, bool? attachFiles = null, bool? readMessageHistory = null, bool? mentionEveryone = null, bool? useExternalEmojis = null, bool? connect = null, bool? speak = null, bool? muteMembers = null, bool? deafenMembers = null, bool? moveMembers = null, bool? useVoiceActivation = null, bool? prioritySpeaker = null, bool? stream = null, bool? changeNickname = null, bool? manageNicknames = null, bool? manageRoles = null, bool? manageWebhooks = null, bool? manageEmojis = null) => new GuildPermissions(RawValue, createInstantInvite, kickMembers, banMembers, administrator, manageChannels, manageGuild, addReactions, viewAuditLog, viewGuildInsights, viewChannel, sendMessages, sendTTSMessages, manageMessages, embedLinks, attachFiles, readMessageHistory, mentionEveryone, useExternalEmojis, connect, speak, muteMembers, deafenMembers, moveMembers, useVoiceActivation, prioritySpeaker, stream, changeNickname, manageNicknames, manageRoles, manageWebhooks, manageEmojis); /// <summary> /// Returns a value that indicates if a specific <see cref="GuildPermission"/> is enabled /// in these permissions. /// </summary> /// <param name="permission">The permission value to check for.</param> /// <returns><c>true</c> if the permission is enabled, <c>false</c> otherwise.</returns> public bool Has(GuildPermission permission) => Permissions.GetValue(RawValue, permission); /// <summary> /// Returns a <see cref="List{T}"/> containing all of the <see cref="GuildPermission"/> /// flags that are enabled. /// </summary> /// <returns>A <see cref="List{T}"/> containing <see cref="GuildPermission"/> flags. Empty if none are enabled.</returns> public List<GuildPermission> ToList() { var perms = new List<GuildPermission>(); // bitwise operations on raw value // each of the GuildPermissions increments by 2^i from 0 to MaxBits for (byte i = 0; i < Permissions.MaxBits; i++) { ulong flag = ((ulong)1 << i); if ((RawValue & flag) != 0) perms.Add((GuildPermission)flag); } return perms; } public override string ToString() => RawValue.ToString(); private string DebuggerDisplay => $"{string.Join(", ", ToList())}"; } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using Moq; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.UnitTests; using Avalonia.VisualTree; using Xunit; namespace Avalonia.Controls.UnitTests.Primitives { public class TemplatedControlTests { [Fact] public void Template_Doesnt_Get_Executed_On_Set() { bool executed = false; var template = new FuncControlTemplate(_ => { executed = true; return new Control(); }); var target = new TemplatedControl { Template = template, }; Assert.False(executed); } [Fact] public void Template_Gets_Executed_On_Measure() { bool executed = false; var template = new FuncControlTemplate(_ => { executed = true; return new Control(); }); var target = new TemplatedControl { Template = template, }; target.Measure(new Size(100, 100)); Assert.True(executed); } [Fact] public void ApplyTemplate_Should_Create_Visual_Children() { var target = new TemplatedControl { Template = new FuncControlTemplate(_ => new Decorator { Child = new Panel { Children = new Controls { new TextBlock(), new Border(), } } }), }; target.ApplyTemplate(); var types = target.GetVisualDescendents().Select(x => x.GetType()).ToList(); Assert.Equal( new[] { typeof(Decorator), typeof(Panel), typeof(TextBlock), typeof(Border) }, types); Assert.Empty(target.GetLogicalChildren()); } [Fact] public void Templated_Child_Should_Be_NameScope() { var target = new TemplatedControl { Template = new FuncControlTemplate(_ => new Decorator { Child = new Panel { Children = new Controls { new TextBlock(), new Border(), } } }), }; target.ApplyTemplate(); Assert.NotNull(NameScope.GetNameScope((Control)target.GetVisualChildren().Single())); } [Fact] public void Templated_Children_Should_Have_TemplatedParent_Set() { var target = new TemplatedControl { Template = new FuncControlTemplate(_ => new Decorator { Child = new Panel { Children = new Controls { new TextBlock(), new Border(), } } }), }; target.ApplyTemplate(); var templatedParents = target.GetVisualDescendents() .OfType<IControl>() .Select(x => x.TemplatedParent) .ToList(); Assert.Equal(4, templatedParents.Count); Assert.True(templatedParents.All(x => x == target)); } [Fact] public void Templated_Child_Should_Have_Parent_Set() { var target = new TemplatedControl { Template = new FuncControlTemplate(_ => new Decorator()) }; target.ApplyTemplate(); var child = (Decorator)target.GetVisualChildren().Single(); Assert.Equal(target, child.Parent); Assert.Equal(target, child.GetLogicalParent()); } [Fact] public void Nested_Templated_Control_Should_Not_Have_Template_Applied() { var target = new TemplatedControl { Template = new FuncControlTemplate(_ => new ScrollViewer()) }; target.ApplyTemplate(); var child = (ScrollViewer)target.GetVisualChildren().Single(); Assert.Empty(child.GetVisualChildren()); } [Fact] public void Templated_Children_Should_Be_Styled() { using (UnitTestApplication.Start(TestServices.MockStyler)) { TestTemplatedControl target; var root = new TestRoot { Child = target = new TestTemplatedControl { Template = new FuncControlTemplate(_ => { return new StackPanel { Children = new Controls { new TextBlock { } } }; }), } }; target.ApplyTemplate(); var styler = Mock.Get(UnitTestApplication.Current.Services.Styler); styler.Verify(x => x.ApplyStyles(It.IsAny<TestTemplatedControl>()), Times.Once()); styler.Verify(x => x.ApplyStyles(It.IsAny<StackPanel>()), Times.Once()); styler.Verify(x => x.ApplyStyles(It.IsAny<TextBlock>()), Times.Once()); } } [Fact] public void Nested_Templated_Controls_Have_Correct_TemplatedParent() { var target = new TestTemplatedControl { Template = new FuncControlTemplate(_ => { return new ContentControl { Template = new FuncControlTemplate(parent => { return new Border { Child = new ContentPresenter { [~ContentPresenter.ContentProperty] = parent.GetObservable(ContentControl.ContentProperty).AsBinding(), } }; }), Content = new Decorator { Child = new TextBlock() } }; }), }; target.ApplyTemplate(); var contentControl = target.GetTemplateChildren().OfType<ContentControl>().Single(); contentControl.ApplyTemplate(); var border = contentControl.GetTemplateChildren().OfType<Border>().Single(); var presenter = contentControl.GetTemplateChildren().OfType<ContentPresenter>().Single(); var decorator = (Decorator)presenter.Content; var textBlock = (TextBlock)decorator.Child; Assert.Equal(target, contentControl.TemplatedParent); Assert.Equal(contentControl, border.TemplatedParent); Assert.Equal(contentControl, presenter.TemplatedParent); Assert.Equal(target, decorator.TemplatedParent); Assert.Equal(target, textBlock.TemplatedParent); } [Fact] public void Nested_TemplatedControls_Should_Register_With_Correct_NameScope() { var target = new ContentControl { Template = new FuncControlTemplate<ContentControl>(ScrollingContentControlTemplate), Content = "foo" }; var root = new TestRoot { Child = target }; target.ApplyTemplate(); var border = target.GetVisualChildren().FirstOrDefault(); Assert.IsType<Border>(border); var scrollViewer = border.GetVisualChildren().FirstOrDefault(); Assert.IsType<ScrollViewer>(scrollViewer); ((ScrollViewer)scrollViewer).ApplyTemplate(); var scrollContentPresenter = scrollViewer.GetVisualChildren().FirstOrDefault(); Assert.IsType<ScrollContentPresenter>(scrollContentPresenter); ((ContentPresenter)scrollContentPresenter).UpdateChild(); var contentPresenter = scrollContentPresenter.GetVisualChildren().FirstOrDefault(); Assert.IsType<ContentPresenter>(contentPresenter); var borderNs = NameScope.GetNameScope((Control)border); var scrollContentPresenterNs = NameScope.GetNameScope((Control)scrollContentPresenter); Assert.NotNull(borderNs); Assert.Same(scrollViewer, borderNs.Find("ScrollViewer")); Assert.Same(contentPresenter, borderNs.Find("PART_ContentPresenter")); Assert.Same(scrollContentPresenter, scrollContentPresenterNs.Find("PART_ContentPresenter")); } [Fact] public void ApplyTemplate_Should_Raise_TemplateApplied() { var target = new TestTemplatedControl { Template = new FuncControlTemplate(_ => new Decorator()) }; var raised = false; target.TemplateApplied += (s, e) => { Assert.Equal(TemplatedControl.TemplateAppliedEvent, e.RoutedEvent); Assert.Same(target, e.Source); Assert.NotNull(e.NameScope); raised = true; }; target.ApplyTemplate(); Assert.True(raised); } [Fact] public void Applying_New_Template_Clears_TemplatedParent_Of_Old_Template_Children() { var target = new TestTemplatedControl { Template = new FuncControlTemplate(_ => new Decorator { Child = new Border(), }) }; target.ApplyTemplate(); var decorator = (Decorator)target.GetVisualChildren().Single(); var border = (Border)decorator.Child; Assert.Equal(target, decorator.TemplatedParent); Assert.Equal(target, border.TemplatedParent); target.Template = new FuncControlTemplate(_ => new Canvas()); // Templated children should not be removed here: the control may be re-added // somewhere with the same template, so they could still be of use. Assert.Same(decorator, target.GetVisualChildren().Single()); Assert.Equal(target, decorator.TemplatedParent); Assert.Equal(target, border.TemplatedParent); target.ApplyTemplate(); Assert.Null(decorator.TemplatedParent); Assert.Null(border.TemplatedParent); } [Fact] public void TemplateChild_AttachedToLogicalTree_Should_Be_Raised() { Border templateChild = new Border(); var root = new TestRoot { Child = new TestTemplatedControl { Template = new FuncControlTemplate(_ => new Decorator { Child = templateChild, }) } }; var raised = false; templateChild.AttachedToLogicalTree += (s, e) => raised = true; root.Child.ApplyTemplate(); Assert.True(raised); } [Fact] public void TemplateChild_DetachedFromLogicalTree_Should_Be_Raised() { Border templateChild = new Border(); var root = new TestRoot { Child = new TestTemplatedControl { Template = new FuncControlTemplate(_ => new Decorator { Child = templateChild, }) } }; root.Child.ApplyTemplate(); var raised = false; templateChild.DetachedFromLogicalTree += (s, e) => raised = true; root.Child = null; Assert.True(raised); } [Fact] public void Removing_From_LogicalTree_Should_Not_Remove_Child() { using (UnitTestApplication.Start(TestServices.RealStyler)) { Border templateChild = new Border(); TestTemplatedControl target; var root = new TestRoot { Styles = new Styles { new Style(x => x.OfType<TestTemplatedControl>()) { Setters = new[] { new Setter( TemplatedControl.TemplateProperty, new FuncControlTemplate(_ => new Decorator { Child = new Border(), })) } } }, Child = target = new TestTemplatedControl() }; Assert.NotNull(target.Template); target.ApplyTemplate(); root.Child = null; Assert.Null(target.Template); Assert.IsType<Decorator>(target.GetVisualChildren().Single()); } } [Fact] public void Re_adding_To_Same_LogicalTree_Should_Not_Recreate_Template() { using (UnitTestApplication.Start(TestServices.RealStyler)) { TestTemplatedControl target; var root = new TestRoot { Styles = new Styles { new Style(x => x.OfType<TestTemplatedControl>()) { Setters = new[] { new Setter( TemplatedControl.TemplateProperty, new FuncControlTemplate(_ => new Decorator { Child = new Border(), })) } } }, Child = target = new TestTemplatedControl() }; Assert.NotNull(target.Template); target.ApplyTemplate(); var expected = (Decorator)target.GetVisualChildren().Single(); root.Child = null; root.Child = target; target.ApplyTemplate(); Assert.Same(expected, target.GetVisualChildren().Single()); } } [Fact] public void Re_adding_To_Different_LogicalTree_Should_Recreate_Template() { using (UnitTestApplication.Start(TestServices.RealStyler)) { TestTemplatedControl target; var root = new TestRoot { Styles = new Styles { new Style(x => x.OfType<TestTemplatedControl>()) { Setters = new[] { new Setter( TemplatedControl.TemplateProperty, new FuncControlTemplate(_ => new Decorator { Child = new Border(), })) } } }, Child = target = new TestTemplatedControl() }; var root2 = new TestRoot { Styles = new Styles { new Style(x => x.OfType<TestTemplatedControl>()) { Setters = new[] { new Setter( TemplatedControl.TemplateProperty, new FuncControlTemplate(_ => new Decorator { Child = new Border(), })) } } }, }; Assert.NotNull(target.Template); target.ApplyTemplate(); var expected = (Decorator)target.GetVisualChildren().Single(); root.Child = null; root2.Child = target; target.ApplyTemplate(); var child = target.GetVisualChildren().Single(); Assert.NotNull(target.Template); Assert.NotNull(child); Assert.NotSame(expected, child); } } private static IControl ScrollingContentControlTemplate(ContentControl control) { return new Border { Child = new ScrollViewer { Template = new FuncControlTemplate<ScrollViewer>(ScrollViewerTemplate), Name = "ScrollViewer", Content = new ContentPresenter { Name = "PART_ContentPresenter", [!ContentPresenter.ContentProperty] = control[!ContentControl.ContentProperty], } } }; } private static Control ScrollViewerTemplate(ScrollViewer control) { var result = new ScrollContentPresenter { Name = "PART_ContentPresenter", [~ContentPresenter.ContentProperty] = control[~ContentControl.ContentProperty], }; return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using GitVersion.Common; using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.Model.Configuration; using LibGit2Sharp; namespace GitVersion.Configuration { public class BranchConfigurationCalculator : IBranchConfigurationCalculator { private const string FallbackConfigName = "Fallback"; private readonly ILog log; private readonly IRepositoryMetadataProvider repositoryMetadataProvider; public BranchConfigurationCalculator(ILog log, IRepositoryMetadataProvider repositoryMetadataProvider) { this.log = log ?? throw new ArgumentNullException(nameof(log)); this.repositoryMetadataProvider = repositoryMetadataProvider ?? throw new ArgumentNullException(nameof(repositoryMetadataProvider)); } /// <summary> /// Gets the <see cref="BranchConfig"/> for the current commit. /// </summary> public BranchConfig GetBranchConfiguration(Branch targetBranch, Commit currentCommit, Config configuration, IList<Branch> excludedInheritBranches = null) { var matchingBranches = configuration.GetConfigForBranch(targetBranch.NameWithoutRemote()); if (matchingBranches == null) { log.Info($"No branch configuration found for branch {targetBranch.FriendlyName}, falling back to default configuration"); matchingBranches = new BranchConfig { Name = FallbackConfigName }; configuration.ApplyBranchDefaults(matchingBranches, "", new List<string>()); } if (matchingBranches.Increment == IncrementStrategy.Inherit) { matchingBranches = InheritBranchConfiguration(targetBranch, matchingBranches, currentCommit, configuration, excludedInheritBranches); if (matchingBranches.Name == FallbackConfigName && matchingBranches.Increment == IncrementStrategy.Inherit) { // We tried, and failed to inherit, just fall back to patch matchingBranches.Increment = IncrementStrategy.Patch; } } return matchingBranches; } // TODO I think we need to take a fresh approach to this.. it's getting really complex with heaps of edge cases private BranchConfig InheritBranchConfiguration(Branch targetBranch, BranchConfig branchConfiguration, Commit currentCommit, Config configuration, IList<Branch> excludedInheritBranches) { using (log.IndentLog("Attempting to inherit branch configuration from parent branch")) { var excludedBranches = new[] { targetBranch }; // Check if we are a merge commit. If so likely we are a pull request var parentCount = currentCommit.Parents.Count(); if (parentCount == 2) { excludedBranches = CalculateWhenMultipleParents(currentCommit, ref targetBranch, excludedBranches); } excludedInheritBranches ??= repositoryMetadataProvider.GetExcludedInheritBranches(configuration); // Add new excluded branches. foreach (var excludedBranch in excludedBranches.ExcludingBranches(excludedInheritBranches)) { excludedInheritBranches.Add(excludedBranch); } var branchesToEvaluate = repositoryMetadataProvider.ExcludingBranches(excludedInheritBranches).ToList(); var branchPoint = repositoryMetadataProvider .FindCommitBranchWasBranchedFrom(targetBranch, configuration, excludedInheritBranches.ToArray()); List<Branch> possibleParents; if (branchPoint == BranchCommit.Empty) { possibleParents = repositoryMetadataProvider.GetBranchesContainingCommit(targetBranch.Tip, branchesToEvaluate) // It fails to inherit Increment branch configuration if more than 1 parent; // therefore no point to get more than 2 parents .Take(2) .ToList(); } else { var branches = repositoryMetadataProvider.GetBranchesContainingCommit(branchPoint.Commit, branchesToEvaluate).ToList(); if (branches.Count > 1) { var currentTipBranches = repositoryMetadataProvider.GetBranchesContainingCommit(currentCommit, branchesToEvaluate).ToList(); possibleParents = branches.Except(currentTipBranches).ToList(); } else { possibleParents = branches; } } log.Info("Found possible parent branches: " + string.Join(", ", possibleParents.Select(p => p.FriendlyName))); if (possibleParents.Count == 1) { var branchConfig = GetBranchConfiguration(possibleParents[0], currentCommit, configuration, excludedInheritBranches); // If we have resolved a fallback config we should not return that we have got config if (branchConfig.Name != FallbackConfigName) { return new BranchConfig(branchConfiguration) { Increment = branchConfig.Increment, PreventIncrementOfMergedBranchVersion = branchConfig.PreventIncrementOfMergedBranchVersion, // If we are inheriting from develop then we should behave like develop TracksReleaseBranches = branchConfig.TracksReleaseBranches }; } } // If we fail to inherit it is probably because the branch has been merged and we can't do much. So we will fall back to develop's config // if develop exists and master if not var errorMessage = possibleParents.Count == 0 ? "Failed to inherit Increment branch configuration, no branches found." : "Failed to inherit Increment branch configuration, ended up with: " + string.Join(", ", possibleParents.Select(p => p.FriendlyName)); var chosenBranch = repositoryMetadataProvider.GetChosenBranch(configuration); if (chosenBranch == null) { // TODO We should call the build server to generate this exception, each build server works differently // for fetch issues and we could give better warnings. throw new InvalidOperationException("Could not find a 'develop' or 'master' branch, neither locally nor remotely."); } var branchName = chosenBranch.FriendlyName; log.Warning(errorMessage + System.Environment.NewLine + "Falling back to " + branchName + " branch config"); // To prevent infinite loops, make sure that a new branch was chosen. if (targetBranch.IsSameBranch(chosenBranch)) { var developOrMasterConfig = ChooseMasterOrDevelopIncrementStrategyIfTheChosenBranchIsOneOfThem( chosenBranch, branchConfiguration, configuration); if (developOrMasterConfig != null) { return developOrMasterConfig; } log.Warning("Fallback branch wants to inherit Increment branch configuration from itself. Using patch increment instead."); return new BranchConfig(branchConfiguration) { Increment = IncrementStrategy.Patch }; } var inheritingBranchConfig = GetBranchConfiguration(chosenBranch, currentCommit, configuration, excludedInheritBranches); var configIncrement = inheritingBranchConfig.Increment; if (inheritingBranchConfig.Name == FallbackConfigName && configIncrement == IncrementStrategy.Inherit) { log.Warning("Fallback config inherits by default, dropping to patch increment"); configIncrement = IncrementStrategy.Patch; } return new BranchConfig(branchConfiguration) { Increment = configIncrement, PreventIncrementOfMergedBranchVersion = inheritingBranchConfig.PreventIncrementOfMergedBranchVersion, // If we are inheriting from develop then we should behave like develop TracksReleaseBranches = inheritingBranchConfig.TracksReleaseBranches }; } } private Branch[] CalculateWhenMultipleParents(Commit currentCommit, ref Branch currentBranch, Branch[] excludedBranches) { var parents = currentCommit.Parents.ToArray(); var branches = repositoryMetadataProvider.GetBranchesForCommit(parents[1]); if (branches.Count == 1) { var branch = branches[0]; excludedBranches = new[] { currentBranch, branch }; currentBranch = branch; } else if (branches.Count > 1) { currentBranch = branches.FirstOrDefault(b => b.NameWithoutRemote() == "master") ?? branches.First(); } else { var possibleTargetBranches = repositoryMetadataProvider.GetBranchesForCommit(parents[0]); if (possibleTargetBranches.Count > 1) { currentBranch = possibleTargetBranches.FirstOrDefault(b => b.NameWithoutRemote() == "master") ?? possibleTargetBranches.First(); } else { currentBranch = possibleTargetBranches.FirstOrDefault() ?? currentBranch; } } log.Info("HEAD is merge commit, this is likely a pull request using " + currentBranch.FriendlyName + " as base"); return excludedBranches; } private static BranchConfig ChooseMasterOrDevelopIncrementStrategyIfTheChosenBranchIsOneOfThem(Branch chosenBranch, BranchConfig branchConfiguration, Config config) { BranchConfig masterOrDevelopConfig = null; var developBranchRegex = config.Branches[Config.DevelopBranchKey].Regex; var masterBranchRegex = config.Branches[Config.MasterBranchKey].Regex; if (Regex.IsMatch(chosenBranch.FriendlyName, developBranchRegex, RegexOptions.IgnoreCase)) { // Normally we would not expect this to happen but for safety we add a check if (config.Branches[Config.DevelopBranchKey].Increment != IncrementStrategy.Inherit) { masterOrDevelopConfig = new BranchConfig(branchConfiguration) { Increment = config.Branches[Config.DevelopBranchKey].Increment }; } } else if (Regex.IsMatch(chosenBranch.FriendlyName, masterBranchRegex, RegexOptions.IgnoreCase)) { // Normally we would not expect this to happen but for safety we add a check if (config.Branches[Config.MasterBranchKey].Increment != IncrementStrategy.Inherit) { masterOrDevelopConfig = new BranchConfig(branchConfiguration) { Increment = config.Branches[Config.DevelopBranchKey].Increment }; } } return masterOrDevelopConfig; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.Contracts; using System.Threading.Tasks; namespace System.IO { // This class implements a text reader that reads from a string. // public class StringReader : TextReader { private string _s; private int _pos; private int _length; public StringReader(string s) { if (s == null) { throw new ArgumentNullException(nameof(s)); } _s = s; _length = s == null ? 0 : s.Length; } protected override void Dispose(bool disposing) { _s = null; _pos = 0; _length = 0; base.Dispose(disposing); } // Returns the next available character without actually reading it from // the underlying string. The current position of the StringReader is not // changed by this operation. The returned value is -1 if no further // characters are available. // [Pure] public override int Peek() { if (_s == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed); } if (_pos == _length) { return -1; } return _s[_pos]; } // Reads the next character from the underlying string. The returned value // is -1 if no further characters are available. // public override int Read() { if (_s == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed); } if (_pos == _length) { return -1; } return _s[_pos++]; } // Reads a block of characters. This method will read up to count // characters from this StringReader into the buffer character // array starting at position index. Returns the actual number of // characters read, or zero if the end of the string is reached. // public override int Read(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (_s == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed); } int n = _length - _pos; if (n > 0) { if (n > count) { n = count; } _s.CopyTo(_pos, buffer, index, n); _pos += n; } return n; } public override string ReadToEnd() { if (_s == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed); } string s; if (_pos == 0) { s = _s; } else { s = _s.Substring(_pos, _length - _pos); } _pos = _length; return s; } // Reads a line. A line is defined as a sequence of characters followed by // a carriage return ('\r'), a line feed ('\n'), or a carriage return // immediately followed by a line feed. The resulting string does not // contain the terminating carriage return and/or line feed. The returned // value is null if the end of the underlying string has been reached. // public override string ReadLine() { if (_s == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed); } int i = _pos; while (i < _length) { char ch = _s[i]; if (ch == '\r' || ch == '\n') { string result = _s.Substring(_pos, i - _pos); _pos = i + 1; if (ch == '\r' && _pos < _length && _s[_pos] == '\n') { _pos++; } return result; } i++; } if (i > _pos) { string result = _s.Substring(_pos, i - _pos); _pos = i; return result; } return null; } #region Task based Async APIs public override Task<string> ReadLineAsync() { return Task.FromResult(ReadLine()); } public override Task<string> ReadToEndAsync() { return Task.FromResult(ReadToEnd()); } public override Task<int> ReadBlockAsync(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return Task.FromResult(ReadBlock(buffer, index, count)); } public override Task<int> ReadAsync(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return Task.FromResult(Read(buffer, index, count)); } #endregion } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.IO; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Windows.Media.Imaging; using Autodesk.Revit; using Autodesk.Revit.DB.Events; using Autodesk.Revit.UI; using Autodesk.Revit.ApplicationServices; using Autodesk.Revit.DB; namespace Revit.SDK.Samples.DoorSwing.CS { /// <summary> /// A class inherited IExternalApplication interface. /// This class subscribes to some application level events and /// creates a custom Ribbon panel which contains three buttons. /// </summary [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)] [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)] [Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)] public class ExternalApplication : IExternalApplication { #region "Members" // An object that is passed to the external application which contains the controlled Revit application. UIControlledApplication m_controlApp; #endregion #region IExternalApplication Members /// <summary> /// Implement this method to implement the external application which should be called when /// Revit starts before a file or default template is actually loaded. /// <param name="application">An object that is passed to the external application /// which contains the controlled application.</param> /// <returns>Return the status of the external application. /// A result of Succeeded means that the external application successfully started. /// Cancelled can be used to signify that the user cancelled the external operation at /// some point. /// If false is returned then Revit should inform the user that the external application /// failed to load and the release the internal reference.</returns> public Autodesk.Revit.UI.Result OnStartup(UIControlledApplication application) { m_controlApp = application; #region Subscribe to related events // Doors are updated from the application level events. // That will insure that the doc is correct when it is saved. // Subscribe to related events. application.ControlledApplication.DocumentSaving += new EventHandler<DocumentSavingEventArgs>(DocumentSavingHandler); application.ControlledApplication.DocumentSavingAs += new EventHandler<DocumentSavingAsEventArgs>(DocumentSavingAsHandler); #endregion #region create a custom Ribbon panel which contains three buttons // The location of this command assembly string currentCommandAssemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location; // The directory path of buttons' images string buttonImageDir = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName (Path.GetDirectoryName(currentCommandAssemblyPath)))); // begin to create custom Ribbon panel and command buttons. // create a Ribbon panel. RibbonPanel doorPanel = application.CreateRibbonPanel("Door Swing"); // the first button in the DoorSwing panel, use to invoke the InitializeCommand. PushButton initialCommandBut = doorPanel.AddItem(new PushButtonData("Customize Door Opening", "Customize Door Opening", currentCommandAssemblyPath, typeof(InitializeCommand).FullName)) as PushButton; initialCommandBut.ToolTip = "Customize the expression based on family's geometry and country's standard."; initialCommandBut.LargeImage = new BitmapImage(new Uri(Path.Combine(buttonImageDir, "InitialCommand_Large.bmp"))); initialCommandBut.Image = new BitmapImage(new Uri(Path.Combine(buttonImageDir, "InitialCommand_Small.bmp"))); // the second button in the DoorSwing panel, use to invoke the UpdateParamsCommand. PushButton updateParamBut = doorPanel.AddItem(new PushButtonData("Update Door Properties", "Update Door Properties", currentCommandAssemblyPath, typeof(UpdateParamsCommand).FullName)) as PushButton; updateParamBut.ToolTip = "Update door properties based on geometry."; updateParamBut.LargeImage = new BitmapImage(new Uri(Path.Combine(buttonImageDir, "UpdateParameter_Large.bmp"))); updateParamBut.Image = new BitmapImage(new Uri(Path.Combine(buttonImageDir, "UpdateParameter_Small.bmp"))); // the third button in the DoorSwing panel, use to invoke the UpdateGeometryCommand. PushButton updateGeoBut = doorPanel.AddItem(new PushButtonData("Update Door Geometry", "Update Door Geometry", currentCommandAssemblyPath, typeof(UpdateGeometryCommand).FullName)) as PushButton; updateGeoBut.ToolTip = "Update door geometry based on From/To room property."; updateGeoBut.LargeImage = new BitmapImage(new Uri(Path.Combine(buttonImageDir, "UpdateGeometry_Large.bmp"))); updateGeoBut.Image = new BitmapImage(new Uri(Path.Combine(buttonImageDir, "UpdateGeometry_Small.bmp"))); #endregion return Autodesk.Revit.UI.Result.Succeeded; } /// <summary> /// Implement this method to implement the external application which should be called when /// Revit is about to exit, any documents must have been closed before this method is called. /// </summary> /// <param name="application">An object that is passed to the external application /// which contains the controlled application.</param> /// <returns>Return the status of the external application. /// A result of Succeeded means that the external application successfully shutdown. /// Cancelled can be used to signify that the user cancelled the external operation at some point. /// If false is returned then the Revit user should be warned of the failure of the external /// application to shut down correctly.</returns> public Autodesk.Revit.UI.Result OnShutdown(UIControlledApplication application) { return Autodesk.Revit.UI.Result.Succeeded; } #endregion /// <summary> /// This event is fired whenever a document is saved. /// Update door's information according to door's current geometry. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="args">An DocumentSavingEventArgs that contains the DocumentSaving event data.</param> private void DocumentSavingHandler(Object sender, DocumentSavingEventArgs args) { string message = ""; Transaction tran = null; try { Document doc = args.Document; if (doc.IsModifiable) { if (DoorSwingData.UpdateDoorsInfo(args.Document, false, false, ref message) != Autodesk.Revit.UI.Result.Succeeded) MessageBox.Show(message, "Door Swing"); } else { tran = new Transaction(doc, "Update parameters in Saving event"); tran.Start(); if (DoorSwingData.UpdateDoorsInfo(args.Document, false, false, ref message) != Autodesk.Revit.UI.Result.Succeeded) MessageBox.Show(message, "Door Swing"); tran.Commit(); } } catch (Exception ex) { // if there are something wrong, give error information message. MessageBox.Show(ex.Message, "Door Swing"); if (null != tran) { if (tran.HasStarted() && !tran.HasEnded()) { tran.RollBack(); } } } } /// <summary> /// This event is fired whenever a document is saved as. /// Update door's information according to door's current geometry. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="args">An DocumentSavingAsEventArgs that contains the DocumentSavingAs event data.</param> private void DocumentSavingAsHandler(Object sender, DocumentSavingAsEventArgs args) { string message = ""; Transaction tran = null; try { Document doc = args.Document; if (doc.IsModifiable) { if (DoorSwingData.UpdateDoorsInfo(args.Document, false, false, ref message) != Autodesk.Revit.UI.Result.Succeeded) MessageBox.Show(message, "Door Swing"); } else { tran = new Transaction(doc, "Update parameters in Saving event"); tran.Start(); if (DoorSwingData.UpdateDoorsInfo(args.Document, false, false, ref message) != Autodesk.Revit.UI.Result.Succeeded) MessageBox.Show(message, "Door Swing"); tran.Commit(); } } catch (Exception ex) { // if there are something wrong, give error message. MessageBox.Show(ex.Message, "Door Swing"); if (null != tran) { if (tran.HasStarted() && !tran.HasEnded()) { tran.RollBack(); } } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Umbraco.Core.Events; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.UnitOfWork; namespace Umbraco.Core.Services { /// <summary> /// Represents the File Service, which is an easy access to operations involving <see cref="IFile"/> objects like Scripts, Stylesheets and Templates /// </summary> public class FileService : ScopeRepositoryService, IFileService { private const string PartialViewHeader = "@inherits Umbraco.Web.Mvc.UmbracoTemplatePage"; private const string PartialViewMacroHeader = "@inherits Umbraco.Web.Macros.PartialViewMacroPage"; public FileService( IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory, ILogger logger, IEventMessagesFactory eventMessagesFactory) : base(provider, repositoryFactory, logger, eventMessagesFactory) { } #region Stylesheets /// <summary> /// Gets a list of all <see cref="Stylesheet"/> objects /// </summary> /// <returns>An enumerable list of <see cref="Stylesheet"/> objects</returns> public IEnumerable<Stylesheet> GetStylesheets(params string[] names) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateStylesheetRepository(uow); return repository.GetAll(names); } } /// <summary> /// Gets a <see cref="Stylesheet"/> object by its name /// </summary> /// <param name="name">Name of the stylesheet incl. extension</param> /// <returns>A <see cref="Stylesheet"/> object</returns> public Stylesheet GetStylesheetByName(string name) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateStylesheetRepository(uow); return repository.Get(name); } } /// <summary> /// Saves a <see cref="Stylesheet"/> /// </summary> /// <param name="stylesheet"><see cref="Stylesheet"/> to save</param> /// <param name="userId"></param> public void SaveStylesheet(Stylesheet stylesheet, int userId = 0) { using (var uow = UowProvider.GetUnitOfWork()) { var saveEventArgs = new SaveEventArgs<Stylesheet>(stylesheet); if (uow.Events.DispatchCancelable(SavingStylesheet, this, saveEventArgs)) { uow.Commit(); return; } var repository = RepositoryFactory.CreateStylesheetRepository(uow); repository.AddOrUpdate(stylesheet); saveEventArgs.CanCancel = false; uow.Events.Dispatch(SavedStylesheet, this, saveEventArgs); Audit(uow, AuditType.Save, "Save Stylesheet performed by user", userId, -1); uow.Commit(); } } /// <summary> /// Deletes a stylesheet by its name /// </summary> /// <param name="path">Name incl. extension of the Stylesheet to delete</param> /// <param name="userId"></param> public void DeleteStylesheet(string path, int userId = 0) { using (var uow = UowProvider.GetUnitOfWork()) { var repository = RepositoryFactory.CreateStylesheetRepository(uow); var stylesheet = repository.Get(path); if (stylesheet == null) { uow.Commit(); return; } var deleteEventArgs = new DeleteEventArgs<Stylesheet>(stylesheet); if (uow.Events.DispatchCancelable(DeletingStylesheet, this, deleteEventArgs)) { uow.Commit(); return; } repository.Delete(stylesheet); deleteEventArgs.CanCancel = false; uow.Events.Dispatch(DeletedStylesheet, this, deleteEventArgs); Audit(uow, AuditType.Delete, string.Format("Delete Stylesheet performed by user"), userId, -1); uow.Commit(); } } /// <summary> /// Validates a <see cref="Stylesheet"/> /// </summary> /// <param name="stylesheet"><see cref="Stylesheet"/> to validate</param> /// <returns>True if Stylesheet is valid, otherwise false</returns> public bool ValidateStylesheet(Stylesheet stylesheet) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateStylesheetRepository(uow); return repository.ValidateStylesheet(stylesheet); } } #endregion #region Scripts /// <summary> /// Gets a list of all <see cref="Script"/> objects /// </summary> /// <returns>An enumerable list of <see cref="Script"/> objects</returns> public IEnumerable<Script> GetScripts(params string[] names) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateScriptRepository(uow); return repository.GetAll(names); } } /// <summary> /// Gets a <see cref="Script"/> object by its name /// </summary> /// <param name="name">Name of the script incl. extension</param> /// <returns>A <see cref="Script"/> object</returns> public Script GetScriptByName(string name) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateScriptRepository(uow); return repository.Get(name); } } /// <summary> /// Saves a <see cref="Script"/> /// </summary> /// <param name="script"><see cref="Script"/> to save</param> /// <param name="userId"></param> public void SaveScript(Script script, int userId = 0) { using (var uow = UowProvider.GetUnitOfWork()) { var saveEventArgs = new SaveEventArgs<Script>(script); if (uow.Events.DispatchCancelable(SavingScript, this, saveEventArgs)) { uow.Commit(); return; } var repository = RepositoryFactory.CreateScriptRepository(uow); repository.AddOrUpdate(script); saveEventArgs.CanCancel = false; uow.Events.Dispatch(SavedScript, this, saveEventArgs); Audit(uow, AuditType.Save, "Save Script performed by user", userId, -1); uow.Commit(); } } /// <summary> /// Deletes a script by its name /// </summary> /// <param name="path">Name incl. extension of the Script to delete</param> /// <param name="userId"></param> public void DeleteScript(string path, int userId = 0) { using (var uow = UowProvider.GetUnitOfWork()) { var repository = RepositoryFactory.CreateScriptRepository(uow); var script = repository.Get(path); if (script == null) { uow.Commit(); return; } var deleteEventArgs = new DeleteEventArgs<Script>(script); if (uow.Events.DispatchCancelable(DeletingScript, this, deleteEventArgs)) { uow.Commit(); return; } repository.Delete(script); deleteEventArgs.CanCancel = false; uow.Events.Dispatch(DeletedScript, this, deleteEventArgs); Audit(uow, AuditType.Delete, string.Format("Delete Script performed by user"), userId, -1); uow.Commit(); } } /// <summary> /// Validates a <see cref="Script"/> /// </summary> /// <param name="script"><see cref="Script"/> to validate</param> /// <returns>True if Script is valid, otherwise false</returns> public bool ValidateScript(Script script) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateScriptRepository(uow); return repository.ValidateScript(script); } } public void CreateScriptFolder(string folderPath) { using (var uow = UowProvider.GetUnitOfWork()) { var repository = RepositoryFactory.CreateScriptRepository(uow); ((ScriptRepository)repository).AddFolder(folderPath); uow.Commit(); } } public void DeleteScriptFolder(string folderPath) { using (var uow = UowProvider.GetUnitOfWork()) { var repository = RepositoryFactory.CreateScriptRepository(uow); ((ScriptRepository)repository).DeleteFolder(folderPath); uow.Commit(); } } #endregion #region Templates /// <summary> /// Creates a template for a content type /// </summary> /// <param name="contentTypeAlias"></param> /// <param name="contentTypeName"></param> /// <param name="userId"></param> /// <returns> /// The template created /// </returns> public Attempt<OperationStatus<ITemplate, OperationStatusType>> CreateTemplateForContentType(string contentTypeAlias, string contentTypeName, int userId = 0) { var template = new Template(contentTypeName, //NOTE: We are NOT passing in the content type alias here, we want to use it's name since we don't // want to save template file names as camelCase, the Template ctor will clean the alias as // `alias.ToCleanString(CleanStringType.UnderscoreAlias)` which has been the default. // This fixes: http://issues.umbraco.org/issue/U4-7953 contentTypeName); var evtMsgs = EventMessagesFactory.Get(); //NOTE: This isn't pretty but we need to maintain backwards compatibility so we cannot change // the event args here. The other option is to create a different event with different event // args specifically for this method... which also isn't pretty. So for now, we'll use this // dictionary approach to store 'additional data' in. var additionalData = new Dictionary<string, object> { {"CreateTemplateForContentType", true}, {"ContentTypeAlias", contentTypeAlias}, }; using (var uow = UowProvider.GetUnitOfWork()) { var saveEventArgs = new SaveEventArgs<ITemplate>(template, true, evtMsgs, additionalData); if (uow.Events.DispatchCancelable(SavingTemplate, this, saveEventArgs)) { uow.Commit(); return Attempt.Fail(new OperationStatus<ITemplate, OperationStatusType>(template, OperationStatusType.FailedCancelledByEvent, evtMsgs)); } var repository = RepositoryFactory.CreateTemplateRepository(uow); repository.AddOrUpdate(template); saveEventArgs.CanCancel = false; uow.Events.Dispatch(SavedTemplate, this, saveEventArgs); Audit(uow, AuditType.Save, "Save Template performed by user", userId, template.Id); uow.Commit(); } return Attempt.Succeed(new OperationStatus<ITemplate, OperationStatusType>(template, OperationStatusType.Success, evtMsgs)); } public ITemplate CreateTemplateWithIdentity(string name, string content, ITemplate masterTemplate = null, int userId = 0) { var template = new Template(name, name) { Content = content }; if (masterTemplate != null) { template.SetMasterTemplate(masterTemplate); } SaveTemplate(template, userId); return template; } /// <summary> /// Gets a list of all <see cref="ITemplate"/> objects /// </summary> /// <returns>An enumerable list of <see cref="ITemplate"/> objects</returns> public IEnumerable<ITemplate> GetTemplates(params string[] aliases) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateTemplateRepository(uow); return repository.GetAll(aliases).OrderBy(x => x.Name); } } /// <summary> /// Gets a list of all <see cref="ITemplate"/> objects /// </summary> /// <returns>An enumerable list of <see cref="ITemplate"/> objects</returns> public IEnumerable<ITemplate> GetTemplates(int masterTemplateId) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateTemplateRepository(uow); return repository.GetChildren(masterTemplateId).OrderBy(x => x.Name); } } /// <summary> /// Gets a <see cref="ITemplate"/> object by its alias. /// </summary> /// <param name="alias">The alias of the template.</param> /// <returns>The <see cref="ITemplate"/> object matching the alias, or null.</returns> public ITemplate GetTemplate(string alias) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateTemplateRepository(uow); return repository.Get(alias); } } /// <summary> /// Gets a <see cref="ITemplate"/> object by its identifier. /// </summary> /// <param name="id">The identifer of the template.</param> /// <returns>The <see cref="ITemplate"/> object matching the identifier, or null.</returns> public ITemplate GetTemplate(int id) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateTemplateRepository(uow); return repository.Get(id); } } /// <summary> /// Gets a <see cref="ITemplate"/> object by its guid identifier. /// </summary> /// <param name="id">The guid identifier of the template.</param> /// <returns>The <see cref="ITemplate"/> object matching the identifier, or null.</returns> public ITemplate GetTemplate(Guid id) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateTemplateRepository(uow); var query = Query<ITemplate>.Builder.Where(x => x.Key == id); return repository.GetByQuery(query).SingleOrDefault(); } } public IEnumerable<ITemplate> GetTemplateDescendants(string alias) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateTemplateRepository(uow); return repository.GetDescendants(alias); } } /// <summary> /// Gets the template descendants /// </summary> /// <param name="masterTemplateId"></param> /// <returns></returns> public IEnumerable<ITemplate> GetTemplateDescendants(int masterTemplateId) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateTemplateRepository(uow); return repository.GetDescendants(masterTemplateId); } } /// <summary> /// Gets the template children /// </summary> /// <param name="alias"></param> /// <returns></returns> public IEnumerable<ITemplate> GetTemplateChildren(string alias) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateTemplateRepository(uow); return repository.GetChildren(alias); } } /// <summary> /// Gets the template children /// </summary> /// <param name="masterTemplateId"></param> /// <returns></returns> public IEnumerable<ITemplate> GetTemplateChildren(int masterTemplateId) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateTemplateRepository(uow); return repository.GetChildren(masterTemplateId); } } /// <summary> /// Returns a template as a template node which can be traversed (parent, children) /// </summary> /// <param name="alias"></param> /// <returns></returns> [Obsolete("Use GetDescendants instead")] [EditorBrowsable(EditorBrowsableState.Never)] public TemplateNode GetTemplateNode(string alias) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateTemplateRepository(uow); return repository.GetTemplateNode(alias); } } /// <summary> /// Given a template node in a tree, this will find the template node with the given alias if it is found in the hierarchy, otherwise null /// </summary> /// <param name="anyNode"></param> /// <param name="alias"></param> /// <returns></returns> [Obsolete("Use GetDescendants instead")] [EditorBrowsable(EditorBrowsableState.Never)] public TemplateNode FindTemplateInTree(TemplateNode anyNode, string alias) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateTemplateRepository(uow); return repository.FindTemplateInTree(anyNode, alias); } } /// <summary> /// Saves a <see cref="Template"/> /// </summary> /// <param name="template"><see cref="Template"/> to save</param> /// <param name="userId"></param> public void SaveTemplate(ITemplate template, int userId = 0) { using (var uow = UowProvider.GetUnitOfWork()) { if (uow.Events.DispatchCancelable(SavingTemplate, this, new SaveEventArgs<ITemplate>(template))) { uow.Commit(); return; } var repository = RepositoryFactory.CreateTemplateRepository(uow); repository.AddOrUpdate(template); uow.Events.Dispatch(SavedTemplate, this, new SaveEventArgs<ITemplate>(template, false)); Audit(uow, AuditType.Save, "Save Template performed by user", userId, template.Id); uow.Commit(); } } /// <summary> /// Saves a collection of <see cref="Template"/> objects /// </summary> /// <param name="templates">List of <see cref="Template"/> to save</param> /// <param name="userId">Optional id of the user</param> public void SaveTemplate(IEnumerable<ITemplate> templates, int userId = 0) { using (var uow = UowProvider.GetUnitOfWork()) { if (uow.Events.DispatchCancelable(SavingTemplate, this, new SaveEventArgs<ITemplate>(templates))) { uow.Commit(); return; } var repository = RepositoryFactory.CreateTemplateRepository(uow); foreach (var template in templates) { repository.AddOrUpdate(template); } uow.Events.Dispatch(SavedTemplate, this, new SaveEventArgs<ITemplate>(templates, false)); Audit(uow, AuditType.Save, "Save Template performed by user", userId, -1); uow.Commit(); } } /// <summary> /// This checks what the default rendering engine is set in config but then also ensures that there isn't already /// a template that exists in the opposite rendering engine's template folder, then returns the appropriate /// rendering engine to use. /// </summary> /// <returns></returns> /// <remarks> /// The reason this is required is because for example, if you have a master page file already existing under ~/masterpages/Blah.aspx /// and then you go to create a template in the tree called Blah and the default rendering engine is MVC, it will create a Blah.cshtml /// empty template in ~/Views. This means every page that is using Blah will go to MVC and render an empty page. /// This is mostly related to installing packages since packages install file templates to the file system and then create the /// templates in business logic. Without this, it could cause the wrong rendering engine to be used for a package. /// </remarks> public RenderingEngine DetermineTemplateRenderingEngine(ITemplate template) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateTemplateRepository(uow); return repository.DetermineTemplateRenderingEngine(template); } } /// <summary> /// Deletes a template by its alias /// </summary> /// <param name="alias">Alias of the <see cref="ITemplate"/> to delete</param> /// <param name="userId"></param> public void DeleteTemplate(string alias, int userId = 0) { // v8 - that should be part of the uow / scope var template = GetTemplate(alias); if (template == null) return; using (var uow = UowProvider.GetUnitOfWork()) { var repository = RepositoryFactory.CreateTemplateRepository(uow); var args = new DeleteEventArgs<ITemplate>(template); if (uow.Events.DispatchCancelable(DeletingTemplate, this, args)) { uow.Commit(); return; } repository.Delete(template); args.CanCancel = false; uow.Events.Dispatch(DeletedTemplate, this, args); Audit(uow, AuditType.Delete, "Delete Template performed by user", userId, template.Id); uow.Commit(); } } /// <summary> /// Validates a <see cref="ITemplate"/> /// </summary> /// <param name="template"><see cref="ITemplate"/> to validate</param> /// <returns>True if Script is valid, otherwise false</returns> public bool ValidateTemplate(ITemplate template) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateTemplateRepository(uow); return repository.ValidateTemplate(template); } } public Stream GetTemplateFileContentStream(string filepath) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateTemplateRepository(uow); return repository.GetFileContentStream(filepath); } } public void SetTemplateFileContent(string filepath, Stream content) { using (var uow = UowProvider.GetUnitOfWork()) { var repository = RepositoryFactory.CreateTemplateRepository(uow); repository.SetFileContent(filepath, content); uow.Commit(); } } public long GetTemplateFileSize(string filepath) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateTemplateRepository(uow); return repository.GetFileSize(filepath); } } public Stream GetMacroScriptFileContentStream(string filepath) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateMacroScriptRepository(uow); return repository.GetFileContentStream(filepath); } } public void SetMacroScriptFileContent(string filepath, Stream content) { using (var uow = UowProvider.GetUnitOfWork()) { var repository = RepositoryFactory.CreateMacroScriptRepository(uow); repository.SetFileContent(filepath, content); uow.Commit(); } } public long GetMacroScriptFileSize(string filepath) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateMacroScriptRepository(uow); return repository.GetFileSize(filepath); } } #endregion public Stream GetStylesheetFileContentStream(string filepath) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateStylesheetRepository(uow); return repository.GetFileContentStream(filepath); } } public void SetStylesheetFileContent(string filepath, Stream content) { using (var uow = UowProvider.GetUnitOfWork()) { var repository = RepositoryFactory.CreateStylesheetRepository(uow); repository.SetFileContent(filepath, content); uow.Commit(); } } public long GetStylesheetFileSize(string filepath) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateStylesheetRepository(uow); return repository.GetFileSize(filepath); } } public Stream GetScriptFileContentStream(string filepath) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateScriptRepository(uow); return repository.GetFileContentStream(filepath); } } public void SetScriptFileContent(string filepath, Stream content) { using (var uow = UowProvider.GetUnitOfWork()) { var repository = RepositoryFactory.CreateScriptRepository(uow); repository.SetFileContent(filepath, content); uow.Commit(); } } public long GetScriptFileSize(string filepath) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateScriptRepository(uow); return repository.GetFileSize(filepath); } } public Stream GetUserControlFileContentStream(string filepath) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateUserControlRepository(uow); return repository.GetFileContentStream(filepath); } } public void SetUserControlFileContent(string filepath, Stream content) { using (var uow = UowProvider.GetUnitOfWork()) { var repository = RepositoryFactory.CreateUserControlRepository(uow); repository.SetFileContent(filepath, content); uow.Commit(); } } public long GetUserControlFileSize(string filepath) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateUserControlRepository(uow); return repository.GetFileSize(filepath); } } public Stream GetXsltFileContentStream(string filepath) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateXsltFileRepository(uow); return repository.GetFileContentStream(filepath); } } public void SetXsltFileContent(string filepath, Stream content) { using (var uow = UowProvider.GetUnitOfWork()) { var repository = RepositoryFactory.CreateXsltFileRepository(uow); repository.SetFileContent(filepath, content); uow.Commit(); } } public long GetXsltFileSize(string filepath) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateXsltFileRepository(uow); return repository.GetFileSize(filepath); } } #region Partial Views public IEnumerable<string> GetPartialViewSnippetNames(params string[] filterNames) { var snippetPath = IOHelper.MapPath(string.Format("{0}/PartialViewMacros/Templates/", SystemDirectories.Umbraco)); var files = Directory.GetFiles(snippetPath, "*.cshtml") .Select(Path.GetFileNameWithoutExtension) .Except(filterNames, StringComparer.InvariantCultureIgnoreCase) .ToArray(); //Ensure the ones that are called 'Empty' are at the top var empty = files.Where(x => Path.GetFileName(x).InvariantStartsWith("Empty")) .OrderBy(x => x.Length) .ToArray(); return empty.Union(files.Except(empty)); } public void CreatePartialViewFolder(string folderPath) { using (var uow = UowProvider.GetUnitOfWork()) { var repository = RepositoryFactory.CreatePartialViewRepository(uow); ((PartialViewRepository)repository).AddFolder(folderPath); uow.Commit(); } } public void CreatePartialViewMacroFolder(string folderPath) { using (var uow = UowProvider.GetUnitOfWork()) { var repository = RepositoryFactory.CreatePartialViewMacroRepository(uow); ((PartialViewMacroRepository)repository).AddFolder(folderPath); uow.Commit(); } } public void DeletePartialViewFolder(string folderPath) { using (var uow = UowProvider.GetUnitOfWork()) { var repository = RepositoryFactory.CreatePartialViewRepository(uow); ((PartialViewRepository)repository).DeleteFolder(folderPath); uow.Commit(); } } public void DeletePartialViewMacroFolder(string folderPath) { using (var uow = UowProvider.GetUnitOfWork()) { var repository = RepositoryFactory.CreatePartialViewMacroRepository(uow); ((PartialViewMacroRepository)repository).DeleteFolder(folderPath); uow.Commit(); } } public IPartialView GetPartialView(string path) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreatePartialViewRepository(uow); return repository.Get(path); } } public IPartialView GetPartialViewMacro(string path) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreatePartialViewMacroRepository(uow); return repository.Get(path); } } [Obsolete("MacroScripts are obsolete - this is for backwards compatibility with upgraded sites.")] public IPartialView GetMacroScript(string path) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateMacroScriptRepository(uow); return repository.Get(path); } } [Obsolete("UserControls are obsolete - this is for backwards compatibility with upgraded sites.")] public IUserControl GetUserControl(string path) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateUserControlRepository(uow); return repository.Get(path); } } public IEnumerable<IPartialView> GetPartialViewMacros(params string[] names) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreatePartialViewMacroRepository(uow); return repository.GetAll(names).OrderBy(x => x.Name); } } public IXsltFile GetXsltFile(string path) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateXsltFileRepository(uow); return repository.Get(path); } } public IEnumerable<IXsltFile> GetXsltFiles(params string[] names) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreateXsltFileRepository(uow); return repository.GetAll(names).OrderBy(x => x.Name); } } public Attempt<IPartialView> CreatePartialView(IPartialView partialView, string snippetName = null, int userId = 0) { return CreatePartialViewMacro(partialView, PartialViewType.PartialView, snippetName, userId); } public Attempt<IPartialView> CreatePartialViewMacro(IPartialView partialView, string snippetName = null, int userId = 0) { return CreatePartialViewMacro(partialView, PartialViewType.PartialViewMacro, snippetName, userId); } private Attempt<IPartialView> CreatePartialViewMacro(IPartialView partialView, PartialViewType partialViewType, string snippetName = null, int userId = 0) { var newEventArgs = new NewEventArgs<IPartialView>(partialView, true, partialView.Alias, -1); using (var scope = UowProvider.ScopeProvider.CreateScope()) { scope.Complete(); // always if (scope.Events.DispatchCancelable(CreatingPartialView, this, newEventArgs)) return Attempt<IPartialView>.Fail(); } if (snippetName.IsNullOrWhiteSpace() == false) { partialView.Content = GetPartialViewMacroSnippetContent(snippetName, partialViewType); } using (var uow = UowProvider.GetUnitOfWork()) { var repository = GetPartialViewRepository(partialViewType, uow); repository.AddOrUpdate(partialView); newEventArgs.CanCancel = false; uow.Events.Dispatch(CreatedPartialView, this, newEventArgs); Audit(uow, AuditType.Save, string.Format("Save {0} performed by user", partialViewType), userId, -1); uow.Commit(); } return Attempt<IPartialView>.Succeed(partialView); } public bool DeletePartialView(string path, int userId = 0) { return DeletePartialViewMacro(path, PartialViewType.PartialView, userId); } public bool DeletePartialViewMacro(string path, int userId = 0) { return DeletePartialViewMacro(path, PartialViewType.PartialViewMacro, userId); } private bool DeletePartialViewMacro(string path, PartialViewType partialViewType, int userId = 0) { using (var uow = UowProvider.GetUnitOfWork()) { var repository = GetPartialViewRepository(partialViewType, uow); var partialView = repository.Get(path); if (partialView == null) { uow.Commit(); return false; } var deleteEventArgs = new DeleteEventArgs<IPartialView>(partialView); if (uow.Events.DispatchCancelable(DeletingPartialView, this, deleteEventArgs)) { uow.Commit(); return false; } repository.Delete(partialView); deleteEventArgs.CanCancel = false; uow.Events.Dispatch(DeletedPartialView, this, deleteEventArgs); Audit(uow, AuditType.Delete, string.Format("Delete {0} performed by user", partialViewType), userId, -1); uow.Commit(); } return true; } public Attempt<IPartialView> SavePartialView(IPartialView partialView, int userId = 0) { return SavePartialView(partialView, PartialViewType.PartialView, userId); } public Attempt<IPartialView> SavePartialViewMacro(IPartialView partialView, int userId = 0) { return SavePartialView(partialView, PartialViewType.PartialViewMacro, userId); } private Attempt<IPartialView> SavePartialView(IPartialView partialView, PartialViewType partialViewType, int userId = 0) { using (var uow = UowProvider.GetUnitOfWork()) { var saveEventArgs = new SaveEventArgs<IPartialView>(partialView); if (uow.Events.DispatchCancelable(SavingPartialView, this, saveEventArgs)) { uow.Commit(); return Attempt<IPartialView>.Fail(); } var repository = GetPartialViewRepository(partialViewType, uow); repository.AddOrUpdate(partialView); saveEventArgs.CanCancel = false; uow.Events.Dispatch(SavedPartialView, this, saveEventArgs); Audit(uow, AuditType.Save, string.Format("Save {0} performed by user", partialViewType), userId, -1); uow.Commit(); } return Attempt.Succeed(partialView); } public bool ValidatePartialView(PartialView partialView) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreatePartialViewRepository(uow); return repository.ValidatePartialView(partialView); } } public bool ValidatePartialViewMacro(PartialView partialView) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = RepositoryFactory.CreatePartialViewMacroRepository(uow); return repository.ValidatePartialView(partialView); } } internal string StripPartialViewHeader(string contents) { var headerMatch = new Regex("^@inherits\\s+?.*$", RegexOptions.Multiline); return headerMatch.Replace(contents, string.Empty); } internal Attempt<string> TryGetSnippetPath(string fileName) { if (fileName.EndsWith(".cshtml") == false) { fileName += ".cshtml"; } var snippetPath = IOHelper.MapPath(string.Format("{0}/PartialViewMacros/Templates/{1}", SystemDirectories.Umbraco, fileName)); return System.IO.File.Exists(snippetPath) ? Attempt<string>.Succeed(snippetPath) : Attempt<string>.Fail(); } private IPartialViewRepository GetPartialViewRepository(PartialViewType partialViewType, IUnitOfWork uow) { switch (partialViewType) { case PartialViewType.PartialView: return RepositoryFactory.CreatePartialViewRepository(uow); case PartialViewType.PartialViewMacro: return RepositoryFactory.CreatePartialViewMacroRepository(uow); } throw new ArgumentOutOfRangeException("partialViewType"); } public Stream GetPartialViewMacroFileContentStream(string filepath) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = GetPartialViewRepository(PartialViewType.PartialViewMacro, uow); return repository.GetFileContentStream(filepath); } } public string GetPartialViewSnippetContent(string snippetName) { return GetPartialViewMacroSnippetContent(snippetName, PartialViewType.PartialView); } public string GetPartialViewMacroSnippetContent(string snippetName) { return GetPartialViewMacroSnippetContent(snippetName, PartialViewType.PartialViewMacro); } private string GetPartialViewMacroSnippetContent(string snippetName, PartialViewType partialViewType) { if (snippetName.IsNullOrWhiteSpace()) throw new ArgumentNullException("snippetName"); string partialViewHeader; switch (partialViewType) { case PartialViewType.PartialView: partialViewHeader = PartialViewHeader; break; case PartialViewType.PartialViewMacro: partialViewHeader = PartialViewMacroHeader; break; default: throw new ArgumentOutOfRangeException("partialViewType"); } // Try and get the snippet path var snippetPathAttempt = TryGetSnippetPath(snippetName); if (snippetPathAttempt.Success == false) { throw new InvalidOperationException("Could not load snippet with name " + snippetName); } using (var snippetFile = new StreamReader(System.IO.File.OpenRead(snippetPathAttempt.Result))) { var snippetContent = snippetFile.ReadToEnd().Trim(); //strip the @inherits if it's there snippetContent = StripPartialViewHeader(snippetContent); var content = string.Format("{0}{1}{2}", partialViewHeader, Environment.NewLine, snippetContent); return content; } } public void SetPartialViewMacroFileContent(string filepath, Stream content) { using (var uow = UowProvider.GetUnitOfWork()) { var repository = GetPartialViewRepository(PartialViewType.PartialViewMacro, uow); repository.SetFileContent(filepath, content); uow.Commit(); } } public long GetPartialViewMacroFileSize(string filepath) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = GetPartialViewRepository(PartialViewType.PartialViewMacro, uow); return repository.GetFileSize(filepath); } } public Stream GetPartialViewFileContentStream(string filepath) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = GetPartialViewRepository(PartialViewType.PartialView, uow); return repository.GetFileContentStream(filepath); } } public void SetPartialViewFileContent(string filepath, Stream content) { using (var uow = UowProvider.GetUnitOfWork()) { var repository = GetPartialViewRepository(PartialViewType.PartialView, uow); repository.SetFileContent(filepath, content); uow.Commit(); } } public long GetPartialViewFileSize(string filepath) { using (var uow = UowProvider.GetUnitOfWork(readOnly: true)) { var repository = GetPartialViewRepository(PartialViewType.PartialView, uow); return repository.GetFileSize(filepath); } } #endregion private void Audit(IScopeUnitOfWork uow, AuditType type, string message, int userId, int objectId) { var repository = RepositoryFactory.CreateAuditRepository(uow); repository.AddOrUpdate(new AuditItem(objectId, message, type, userId)); } //TODO Method to change name and/or alias of view/masterpage template #region Event Handlers /// <summary> /// Occurs before Delete /// </summary> public static event TypedEventHandler<IFileService, DeleteEventArgs<ITemplate>> DeletingTemplate; /// <summary> /// Occurs after Delete /// </summary> public static event TypedEventHandler<IFileService, DeleteEventArgs<ITemplate>> DeletedTemplate; /// <summary> /// Occurs before Delete /// </summary> public static event TypedEventHandler<IFileService, DeleteEventArgs<Script>> DeletingScript; /// <summary> /// Occurs after Delete /// </summary> public static event TypedEventHandler<IFileService, DeleteEventArgs<Script>> DeletedScript; /// <summary> /// Occurs before Delete /// </summary> public static event TypedEventHandler<IFileService, DeleteEventArgs<Stylesheet>> DeletingStylesheet; /// <summary> /// Occurs after Delete /// </summary> public static event TypedEventHandler<IFileService, DeleteEventArgs<Stylesheet>> DeletedStylesheet; /// <summary> /// Occurs before Save /// </summary> public static event TypedEventHandler<IFileService, SaveEventArgs<ITemplate>> SavingTemplate; /// <summary> /// Occurs after Save /// </summary> public static event TypedEventHandler<IFileService, SaveEventArgs<ITemplate>> SavedTemplate; /// <summary> /// Occurs before Save /// </summary> public static event TypedEventHandler<IFileService, SaveEventArgs<Script>> SavingScript; /// <summary> /// Occurs after Save /// </summary> public static event TypedEventHandler<IFileService, SaveEventArgs<Script>> SavedScript; /// <summary> /// Occurs before Save /// </summary> public static event TypedEventHandler<IFileService, SaveEventArgs<Stylesheet>> SavingStylesheet; /// <summary> /// Occurs after Save /// </summary> public static event TypedEventHandler<IFileService, SaveEventArgs<Stylesheet>> SavedStylesheet; /// <summary> /// Occurs before Save /// </summary> public static event TypedEventHandler<IFileService, SaveEventArgs<IPartialView>> SavingPartialView; /// <summary> /// Occurs after Save /// </summary> public static event TypedEventHandler<IFileService, SaveEventArgs<IPartialView>> SavedPartialView; /// <summary> /// Occurs before Create /// </summary> public static event TypedEventHandler<IFileService, NewEventArgs<IPartialView>> CreatingPartialView; /// <summary> /// Occurs after Create /// </summary> public static event TypedEventHandler<IFileService, NewEventArgs<IPartialView>> CreatedPartialView; /// <summary> /// Occurs before Delete /// </summary> public static event TypedEventHandler<IFileService, DeleteEventArgs<IPartialView>> DeletingPartialView; /// <summary> /// Occurs after Delete /// </summary> public static event TypedEventHandler<IFileService, DeleteEventArgs<IPartialView>> DeletedPartialView; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void SubtractByte() { var test = new SimpleBinaryOpTest__SubtractByte(); 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(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (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(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__SubtractByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__SubtractByte testClass) { var result = Sse2.Subtract(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__SubtractByte testClass) { fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Sse2.Subtract( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__SubtractByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public SimpleBinaryOpTest__SubtractByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[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.Subtract( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.Subtract( Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.Subtract( Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.Subtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Byte>* pClsVar1 = &_clsVar1) fixed (Vector128<Byte>* pClsVar2 = &_clsVar2) { var result = Sse2.Subtract( Sse2.LoadVector128((Byte*)(pClsVar1)), Sse2.LoadVector128((Byte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = Sse2.Subtract(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Sse2.Subtract(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Sse2.Subtract(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__SubtractByte(); var result = Sse2.Subtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__SubtractByte(); fixed (Vector128<Byte>* pFld1 = &test._fld1) fixed (Vector128<Byte>* pFld2 = &test._fld2) { var result = Sse2.Subtract( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.Subtract(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Sse2.Subtract( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.Subtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.Subtract( Sse2.LoadVector128((Byte*)(&test._fld1)), Sse2.LoadVector128((Byte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((byte)(left[0] - right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((byte)(left[i] - right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Subtract)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using Zeus.UserInterface; using Zeus.Data; namespace Zeus.UserInterface.WinForms { public class FormBuilder { private Form form; private TabControl tabs = null; private ToolTip tooltip = new ToolTip(); private ArrayList orderedGuiControls = new ArrayList(); private Hashtable guiControls = new Hashtable(); private Hashtable win32Controls = new Hashtable(); private FileDialog fileDialog = new OpenFileDialog(); private FolderBrowserDialog folderDialog = new FolderBrowserDialog(); public FormBuilder(Form form) { this.form = form; form.Closing += new CancelEventHandler(OnFormClosing); } public FormBuilder(Form form, TabControl tabs) { this.form = form; this.tabs = tabs; form.Closing += new CancelEventHandler(OnFormClosing); } private void addControl(GuiControl gctrl, Control c) { if (tabs == null) { form.Controls.Add(c); } else { tabs.TabPages[gctrl.TabStripIndex].Controls.Add(c); } win32Controls[gctrl.ID] = c; } public void AddToForm(GuiControl control) { guiControls.Add(control.ID, control); orderedGuiControls.Add(control); if (control is GuiLabel) { GuiLabel guiLabel = control as GuiLabel; Label l = new Label(); l.Left = guiLabel.Left; l.Top = guiLabel.Top; l.Width = guiLabel.Width; l.Height = guiLabel.Height; l.Visible = guiLabel.Visible; l.Enabled = guiLabel.Enabled; l.Enabled = guiLabel.Enabled; l.ForeColor = Color.FromName(guiLabel.ForeColor); if (guiLabel.BackColor != string.Empty) { l.BackColor = Color.FromName(guiLabel.BackColor); } l.TextAlign = ContentAlignment.BottomLeft; l.Name = guiLabel.ID; l.Text = guiLabel.Text; tooltip.SetToolTip(l, guiLabel.ToolTip); Font font = l.Font; FontStyle style = FontStyle.Regular; if (guiLabel.Bold) { style = style | FontStyle.Bold; } if (guiLabel.Underline) { style = style | FontStyle.Underline; } if (guiLabel.Strikeout) { style = style | FontStyle.Strikeout; } if (guiLabel.Italic) { style = style | FontStyle.Italic; } l.Font = new Font(font, style); l.LostFocus += new EventHandler(ControlLostFocus); l.Enter += new EventHandler(ControlEnter); addControl(control, l); } else if (control is GuiButton) { GuiButton guiButton = control as GuiButton; Button b = new Button(); b.Click += new EventHandler(OnButtonClick); b.LostFocus += new EventHandler(ControlLostFocus); b.Enter += new EventHandler(ControlEnter); if (guiButton.ClosesForm) { b.Click += new EventHandler(OnButtonOkClick); } else if (guiButton.CancelGeneration) { b.Click += new EventHandler(OnButtonCancelClick); } b.Text = guiButton.Text; b.Left = guiButton.Left; b.Top = guiButton.Top; b.Width = guiButton.Width; b.Height = guiButton.Height; b.Name = guiButton.ID; b.Visible = guiButton.Visible; b.Enabled = guiButton.Enabled; b.ForeColor = Color.FromName(guiButton.ForeColor); if (guiButton.BackColor != string.Empty) { b.BackColor = Color.FromName(guiButton.BackColor); } tooltip.SetToolTip(b, guiButton.ToolTip); addControl(control, b); } else if (control is GuiCheckBox) { GuiCheckBox guiCheckBox = control as GuiCheckBox; CheckBox cb = new CheckBox(); cb.Checked = guiCheckBox.Checked; cb.CheckedChanged += new EventHandler(OnCheckBoxClick); cb.LostFocus += new EventHandler(ControlLostFocus); cb.Enter += new EventHandler(ControlEnter); cb.Text = guiCheckBox.Text; cb.Left = guiCheckBox.Left; cb.Top = guiCheckBox.Top; cb.Width = guiCheckBox.Width; cb.Height = guiCheckBox.Height; cb.Name = guiCheckBox.ID; cb.Visible = guiCheckBox.Visible; cb.Enabled = guiCheckBox.Enabled; cb.ForeColor = Color.FromName(guiCheckBox.ForeColor); if (guiCheckBox.BackColor != string.Empty) { cb.BackColor = Color.FromName(guiCheckBox.BackColor); } tooltip.SetToolTip(cb, guiCheckBox.ToolTip); addControl(control, cb); } else if (control is GuiFilePicker) { GuiFilePicker guiPicker = control as GuiFilePicker; Button b = new Button(); if (guiPicker.PicksFolder) { b.Click += new EventHandler(OnFolderSelectorClick); } else { b.Click += new EventHandler(OnFileSelectorClick); } b.Text = guiPicker.Text; b.Left = guiPicker.Left; b.Top = guiPicker.Top; b.Width = guiPicker.Width; b.Height = guiPicker.Height; b.Name = guiPicker.ID; b.Visible = guiPicker.Visible; b.Enabled = guiPicker.Enabled; b.ForeColor = Color.FromName(guiPicker.ForeColor); if (guiPicker.BackColor != string.Empty) { b.BackColor = Color.FromName(guiPicker.BackColor); } tooltip.SetToolTip(b, guiPicker.ToolTip); b.LostFocus += new EventHandler(ControlLostFocus); b.Enter += new EventHandler(ControlEnter); addControl(control, b); } else if (control is GuiTextBox) { GuiTextBox guiTextBox = control as GuiTextBox; TextBox tb = new TextBox(); tb.Left = guiTextBox.Left; tb.Top = guiTextBox.Top; tb.Width = guiTextBox.Width; tb.Height = guiTextBox.Height; tb.Visible = guiTextBox.Visible; tb.Enabled = guiTextBox.Enabled; tb.Multiline = guiTextBox.Multiline; tb.WordWrap = guiTextBox.WordWrap; if (guiTextBox.VerticalScroll && guiTextBox.HorizontalScroll) tb.ScrollBars = ScrollBars.Both; else if (guiTextBox.VerticalScroll) tb.ScrollBars = ScrollBars.Vertical; else if (guiTextBox.HorizontalScroll) tb.ScrollBars = ScrollBars.Horizontal; else tb.ScrollBars = ScrollBars.None; tb.ForeColor = Color.FromName(guiTextBox.ForeColor); if (guiTextBox.BackColor != string.Empty) { tb.BackColor = Color.FromName(guiTextBox.BackColor); } tb.Name = guiTextBox.ID; tb.Text = guiTextBox.Text; tooltip.SetToolTip(tb, guiTextBox.ToolTip); tb.KeyPress += new KeyPressEventHandler(OnTextBoxKeyPress); tb.LostFocus += new EventHandler(ControlLostFocus); tb.Enter += new EventHandler(ControlEnter); addControl(control, tb); } else if (control is GuiComboBox) { GuiComboBox guiComboBox = control as GuiComboBox; ComboBox cb = new ComboBox(); cb.DropDownStyle = ComboBoxStyle.DropDownList; cb.Sorted = guiComboBox.Sorted; foreach (string val in guiComboBox.Items) { ListControlItem item = new ListControlItem(val, guiComboBox[val]); cb.Items.Add(item); if (val == guiComboBox.SelectedValue) { cb.SelectedItem = item; } } cb.SelectedValueChanged += new EventHandler(OnComboBoxChange); cb.LostFocus += new EventHandler(ControlLostFocus); cb.Enter += new EventHandler(ControlEnter); cb.Left = guiComboBox.Left; cb.Top = guiComboBox.Top; cb.Width = guiComboBox.Width; cb.Height = guiComboBox.Height; cb.Visible = guiComboBox.Visible; cb.Enabled = guiComboBox.Enabled; cb.ForeColor = Color.FromName(guiComboBox.ForeColor); if (guiComboBox.BackColor != string.Empty) { cb.BackColor = Color.FromName(guiComboBox.BackColor); } cb.Name = guiComboBox.ID; tooltip.SetToolTip(cb, guiComboBox.ToolTip); addControl(control, cb); } else if (control is GuiListBox) { GuiListBox guiListBox = control as GuiListBox; ListBox lb = new ListBox(); if (guiListBox.IsMultiSelect) { lb.SelectionMode = SelectionMode.MultiExtended; } else { lb.SelectionMode = SelectionMode.One; } lb.Sorted = guiListBox.Sorted; lb.Left = guiListBox.Left; lb.Top = guiListBox.Top; lb.Width = guiListBox.Width; lb.Height = guiListBox.Height; lb.Visible = guiListBox.Visible; lb.Enabled = guiListBox.Enabled; lb.ForeColor = Color.FromName(guiListBox.ForeColor); if (guiListBox.BackColor != string.Empty) { lb.BackColor = Color.FromName(guiListBox.BackColor); } lb.Name = guiListBox.ID; tooltip.SetToolTip(lb, guiListBox.ToolTip); foreach (string val in guiListBox.Items) { ListControlItem item = new ListControlItem(val, guiListBox[val]); int index = lb.Items.Add(item); if (guiListBox.SelectedItems.Contains(val)) { lb.SetSelected(index, true); } } // For some reason this fixes all of my timing issues! object s; foreach (object o in lb.SelectedIndices) s = o; lb.KeyUp += new KeyEventHandler(OnListBoxKeyUp); lb.SelectedValueChanged += new EventHandler(OnListBoxChange); lb.LostFocus += new EventHandler(ControlLostFocus); lb.Enter += new EventHandler(ControlEnter); addControl(control, lb); } else if (control is GuiGrid) { GuiGrid guiGrid = control as GuiGrid; DataGrid dg = new DataGrid(); dg.Left = guiGrid.Left; dg.Top = guiGrid.Top; dg.Width = guiGrid.Width; dg.Height = guiGrid.Height; dg.Visible = guiGrid.Visible; dg.Enabled = guiGrid.Enabled; if (guiGrid.ForeColor != string.Empty) { dg.ForeColor = Color.FromName(guiGrid.ForeColor); } else if (guiGrid.BackColor != string.Empty) { dg.BackColor = Color.FromName(guiGrid.BackColor); } dg.Name = guiGrid.ID; dg.DataSource = SimpleTableTools.ConvertToDataTable(guiGrid.DataSource); tooltip.SetToolTip(dg, guiGrid.ToolTip); dg.LostFocus += new EventHandler(ControlLostFocus); dg.Enter += new EventHandler(ControlEnter); addControl(control, dg); } else if (control is GuiCheckBoxList) { GuiCheckBoxList guiCheckBoxList = control as GuiCheckBoxList; CheckedListBox lb = new CheckedListBox(); lb.Sorted = guiCheckBoxList.Sorted; lb.CheckOnClick = true; lb.Left = guiCheckBoxList.Left; lb.Top = guiCheckBoxList.Top; lb.Width = guiCheckBoxList.Width; lb.Height = guiCheckBoxList.Height; lb.Visible = guiCheckBoxList.Visible; lb.Enabled = guiCheckBoxList.Enabled; lb.ForeColor = Color.FromName(guiCheckBoxList.ForeColor); if (guiCheckBoxList.BackColor != string.Empty) { lb.BackColor = Color.FromName(guiCheckBoxList.BackColor); } lb.Name = guiCheckBoxList.ID; tooltip.SetToolTip(lb, guiCheckBoxList.ToolTip); foreach (string val in guiCheckBoxList.Items) { ListControlItem item = new ListControlItem(val, guiCheckBoxList[val]); int index = lb.Items.Add(item); if (guiCheckBoxList.SelectedItems.Contains(val)) { lb.SetItemChecked(index, true); } } // For some reason this fixes all of my timing issues! object s; foreach (object o in lb.CheckedItems) s = o; lb.KeyUp += new KeyEventHandler(OnCheckedListBoxKeyUp); lb.SelectedValueChanged += new EventHandler(OnCheckedListBoxChange); lb.LostFocus += new EventHandler(ControlLostFocus); lb.Enter += new EventHandler(ControlEnter); addControl(control, lb); } } public void UpdateData() { Control w32ctrl; foreach (GuiControl control in guiControls.Values) { w32ctrl = win32Controls[control.ID] as Control; if (control is GuiLabel) { GuiLabel guiLabel = control as GuiLabel; Label l = w32ctrl as Label; guiLabel.Text = l.Text; } else if (control is GuiButton) { GuiButton guiButton = control as GuiButton; Button b = w32ctrl as Button; guiButton.Text = b.Text; } else if (control is GuiCheckBox) { GuiCheckBox guiCheckBox = control as GuiCheckBox; CheckBox cb = w32ctrl as CheckBox; guiCheckBox.Text = cb.Text; guiCheckBox.Checked = cb.Checked; } else if (control is GuiFilePicker) { GuiFilePicker guiPicker = control as GuiFilePicker; Button b = w32ctrl as Button; guiPicker.Text = b.Text; b.Tag = win32Controls[guiPicker.TargetControl]; } else if (control is GuiTextBox) { GuiTextBox guiTextBox = control as GuiTextBox; TextBox tb = w32ctrl as TextBox; guiTextBox.Text = tb.Text; } else if (control is GuiComboBox) { GuiComboBox guiComboBox = control as GuiComboBox; ComboBox cb = w32ctrl as ComboBox; if (cb.SelectedItem is ListControlItem) guiComboBox.SelectedValue = ((ListControlItem)cb.SelectedItem).Value; } else if (control is GuiListBox) { GuiListBox guiListBox = control as GuiListBox; ListBox lb = w32ctrl as ListBox; guiListBox.Clear(); foreach (ListControlItem item in lb.Items) { guiListBox[item.Value] = item.Text; } foreach (ListControlItem item in lb.SelectedItems) { guiListBox.SelectedItems.Add(item.Value); } } else if (control is GuiGrid) { GuiGrid guiGrid = control as GuiGrid; DataGrid dg = w32ctrl as DataGrid; guiGrid.DataSource = SimpleTableTools.ConvertToSimpleTable(dg.DataSource as DataTable); } else if (control is GuiCheckBoxList) { GuiCheckBoxList guiCheckBoxList = control as GuiCheckBoxList; CheckedListBox lb = w32ctrl as CheckedListBox; guiCheckBoxList.Clear(); foreach (ListControlItem item in lb.Items) { guiCheckBoxList[item.Value] = item.Text; } foreach (ListControlItem item in lb.CheckedItems) { guiCheckBoxList.SelectedItems.Add(item.Value); } } } } protected void UpdateForm(Control eventSource) { Control w32ctrl; foreach (GuiControl control in guiControls.Values) { w32ctrl = win32Controls[control.ID] as Control; if (eventSource != w32ctrl) { if (control is GuiLabel) { GuiLabel guiLabel = control as GuiLabel; Label l = w32ctrl as Label; l.Text = guiLabel.Text; Font font = l.Font; FontStyle style = FontStyle.Regular; if (guiLabel.Bold) { style = style | FontStyle.Bold; } if (guiLabel.Underline) { style = style | FontStyle.Underline; } if (guiLabel.Strikeout) { style = style | FontStyle.Strikeout; } if (guiLabel.Italic) { style = style | FontStyle.Italic; } l.Font = new Font(font, style); } else if (control is GuiButton) { GuiButton guiButton = control as GuiButton; Button b = w32ctrl as Button; b.Text = guiButton.Text; } else if (control is GuiCheckBox) { GuiCheckBox guiCheckBox = control as GuiCheckBox; CheckBox b = w32ctrl as CheckBox; b.CheckedChanged -= new EventHandler(OnCheckBoxClick); b.Checked = guiCheckBox.Checked; b.CheckedChanged += new EventHandler(OnCheckBoxClick); b.Text = guiCheckBox.Text; } else if (control is GuiFilePicker) { GuiFilePicker guiPicker = control as GuiFilePicker; Button b = w32ctrl as Button; b.Text = guiPicker.Text; } else if (control is GuiTextBox) { GuiTextBox guiTextBox = control as GuiTextBox; TextBox tb = w32ctrl as TextBox; tb.Text = guiTextBox.Text; tb.Multiline = guiTextBox.Multiline; tb.WordWrap = guiTextBox.WordWrap; if (guiTextBox.VerticalScroll && guiTextBox.HorizontalScroll) tb.ScrollBars = ScrollBars.Both; else if (guiTextBox.VerticalScroll) tb.ScrollBars = ScrollBars.Vertical; else if (guiTextBox.HorizontalScroll) tb.ScrollBars = ScrollBars.Horizontal; else tb.ScrollBars = ScrollBars.None; } else if (control is GuiComboBox) { GuiComboBox guiComboBox = control as GuiComboBox; ComboBox cb = w32ctrl as ComboBox; cb.SelectedValueChanged -= new EventHandler(OnComboBoxChange); cb.Items.Clear(); foreach (string val in guiComboBox.Items) { ListControlItem item = new ListControlItem(val, guiComboBox[val]); cb.Items.Add(item); if (item.Value == guiComboBox.SelectedValue) { cb.SelectedItem = item; } } cb.SelectedValueChanged += new EventHandler(OnComboBoxChange); } else if (control is GuiListBox) { GuiListBox guiListBox = control as GuiListBox; ListBox lb = w32ctrl as ListBox; lb.SelectedValueChanged -= new EventHandler(OnListBoxChange); lb.Items.Clear(); foreach (string val in guiListBox.Items) { ListControlItem item = new ListControlItem(val, guiListBox[val]); lb.Items.Add(item); if (guiListBox.SelectedItems.Contains(val)) { lb.SetSelected(lb.Items.IndexOf(item), true); } } lb.SelectedValueChanged += new EventHandler(OnListBoxChange); lb.SelectionMode = guiListBox.IsMultiSelect ? SelectionMode.MultiExtended : SelectionMode.One; lb.Sorted = guiListBox.Sorted; } else if (control is GuiGrid) { GuiGrid guiGrid = control as GuiGrid; DataGrid dg = w32ctrl as DataGrid; dg.DataSource = SimpleTableTools.ConvertToDataTable(guiGrid.DataSource); } else if (control is GuiCheckBoxList) { GuiCheckBoxList guiCheckBoxList = control as GuiCheckBoxList; CheckedListBox lb = w32ctrl as CheckedListBox; lb.SelectedValueChanged -= new EventHandler(OnCheckedListBoxChange); lb.Items.Clear(); foreach (string val in guiCheckBoxList.Items) { ListControlItem item = new ListControlItem(val, guiCheckBoxList[val]); lb.Items.Add(item); if (guiCheckBoxList.SelectedItems.Contains(val)) { lb.SetItemChecked(lb.Items.IndexOf(item), true); } } lb.SelectedValueChanged += new EventHandler(OnCheckedListBoxChange); lb.Sorted = guiCheckBoxList.Sorted; } } w32ctrl.Left = control.Left; w32ctrl.Top = control.Top; w32ctrl.Width = control.Width; w32ctrl.Height = control.Height; w32ctrl.Visible = control.Visible; w32ctrl.Enabled = control.Enabled; if (control.ForeColor != string.Empty) w32ctrl.ForeColor = Color.FromName(control.ForeColor); if (control.BackColor != string.Empty) w32ctrl.BackColor = Color.FromName(control.BackColor); tooltip.SetToolTip(w32ctrl, control.ToolTip); } } public void InitializeControlData(Hashtable input) { Control w32ctrl; object objData; foreach (GuiControl control in this.orderedGuiControls) { try { w32ctrl = win32Controls[control.ID] as Control; if (input.Contains(control.ID)) { objData = input[control.ID]; if (control is GuiCheckBox) { GuiCheckBox guiCheckBox = control as GuiCheckBox; CheckBox b = w32ctrl as CheckBox; b.Checked = Convert.ToBoolean(objData); } else if (control is GuiLabel) { GuiLabel guiLabel = control as GuiLabel; Label l = w32ctrl as Label; l.Text = Convert.ToString(objData); } else if (control is GuiTextBox) { GuiTextBox guiTextBox = control as GuiTextBox; TextBox tb = w32ctrl as TextBox; tb.Text = Convert.ToString(objData); } else if (control is GuiComboBox) { GuiComboBox guiComboBox = control as GuiComboBox; ComboBox cb = w32ctrl as ComboBox; foreach (ListControlItem item in cb.Items) { if ( item.Value == Convert.ToString(objData) ) { cb.SelectedItem = item; break; } } } else if (control is GuiListBox) { GuiListBox guiListBox = control as GuiListBox; ListBox lb = w32ctrl as ListBox; ArrayList list = objData as ArrayList; if (list != null) { for (int i = 0; i < lb.Items.Count; i++) { ListControlItem item = lb.Items[i] as ListControlItem; lb.SetSelected( i, list.Contains(item.Value) ); } } } else if (control is GuiGrid) { GuiGrid guiGrid = control as GuiGrid; DataGrid dg = w32ctrl as DataGrid; SimpleTable table = objData as SimpleTable; if (table != null) { guiGrid.DataSource = table; dg.DataSource = SimpleTableTools.ConvertToDataTable(table); } } else if (control is GuiCheckBoxList) { GuiCheckBoxList guiListBox = control as GuiCheckBoxList; CheckedListBox lb = w32ctrl as CheckedListBox; ArrayList list = objData as ArrayList; if (list != null) { for (int i = 0; i < lb.Items.Count; i++) { ListControlItem item = lb.Items[i] as ListControlItem; lb.SetItemChecked( i, list.Contains(item.Value) ); } } } } } catch { // Do nothing in the catch for now. We want it to fill in as many items as possible. } } } public void OnListBoxKeyUp(object sender, System.Windows.Forms.KeyEventArgs e) { if ((e.KeyCode == Keys.A) && e.Control) { ListBox list = sender as ListBox; if (list.SelectionMode == SelectionMode.MultiSimple || list.SelectionMode == SelectionMode.MultiExtended) { for (int i =0; i < list.Items.Count; i++) { list.SetSelected(i, true); } } } } public void OnCheckedListBoxKeyUp(object sender, System.Windows.Forms.KeyEventArgs e) { if ((e.KeyCode == Keys.A) && e.Control) { e.Handled = true; CheckedListBox list = sender as CheckedListBox; for (int i =0; i < list.Items.Count; i++) { list.SetItemCheckState(i, CheckState.Checked); } } } public void OnFormClosing(object sender, CancelEventArgs e) { if (FormClosing != null) { FormClosing(sender, e); } } public void ControlEnter(object sender, EventArgs e) { if (ControlOnFocus != null) { Control s = sender as Control; GuiControl gc = guiControls[s.Name] as GuiControl; if (gc.HasEventHandlers("onfocus")) { UpdateData(); ControlOnFocus(sender, e); UpdateForm(sender as Control); } } } public void ControlLostFocus(object sender, EventArgs e) { if (ControlOnBlur != null) { Control s = sender as Control; GuiControl gc = guiControls[s.Name] as GuiControl; if (gc.HasEventHandlers("onblur")) { UpdateData(); ControlOnBlur(sender, e); UpdateForm(sender as Control); } } } public void OnTextBoxKeyPress(object sender, KeyPressEventArgs e) { if (TextBoxKeyPress != null) { Control s = sender as Control; GuiControl gc = guiControls[s.Name] as GuiControl; if (gc.HasEventHandlers("onkeypress")) { UpdateData(); TextBoxKeyPress(sender, e); UpdateForm(sender as Control); } } } public void OnComboBoxChange(object sender, EventArgs e) { if (ComboBoxChange != null) { Control s = sender as Control; GuiControl gc = guiControls[s.Name] as GuiControl; if (gc.HasEventHandlers("onchange") || gc.AutoBindingChildControls.Count > 0) { UpdateData(); ComboBoxChange(sender, e); UpdateForm(sender as Control); } } } public void OnListBoxChange(object sender, EventArgs e) { if (ListBoxChange != null) { Control s = sender as Control; GuiControl gc = guiControls[s.Name] as GuiControl; if (gc.HasEventHandlers("onchange") || gc.AutoBindingChildControls.Count > 0) { UpdateData(); ListBoxChange(sender, e); UpdateForm(sender as Control); } } } public void OnCheckedListBoxChange(object sender, EventArgs e) { if (CheckedListBoxChange != null) { Control s = sender as Control; GuiControl gc = guiControls[s.Name] as GuiControl; if (gc.HasEventHandlers("onchange")) { UpdateData(); CheckedListBoxChange(sender, e); UpdateForm(sender as Control); } } } public void OnButtonOkClick(object sender, EventArgs e) { this.form.DialogResult = DialogResult.OK; this.form.Close(); } public void OnButtonCancelClick(object sender, EventArgs e) { this.form.DialogResult = DialogResult.Cancel; this.form.Close(); } public void OnButtonClick(object sender, EventArgs e) { if (ButtonClick != null) { Control s = sender as Control; GuiControl gc = guiControls[s.Name] as GuiControl; if (gc.HasEventHandlers("onclick")) { UpdateData(); ButtonClick(sender, e); UpdateForm(sender as Control); } } } public void OnCheckBoxClick(object sender, EventArgs e) { if (CheckBoxClick != null) { Control s = sender as Control; GuiControl gc = guiControls[s.Name] as GuiControl; if (gc.HasEventHandlers("onclick")) { UpdateData(); CheckBoxClick(sender, e); UpdateForm(sender as Control); } } } public void OnFileSelectorClick(object sender, EventArgs e) { UpdateData(); Button b = sender as Button; if (b != null) { if (b.Tag is Control) { Control c = b.Tag as Control; this.fileDialog.FileName = c.Text; this.fileDialog.RestoreDirectory = true; } } DialogResult result = this.fileDialog.ShowDialog(); if ( (sender is Button) && (result == DialogResult.OK) ) { UpdateFromDialogSelection(sender as Button); UpdateData(); FileSelectorSelect(sender, e); UpdateForm(sender as Control); } } public void OnFolderSelectorClick(object sender, EventArgs e) { UpdateData(); Button b = sender as Button; if (b != null) { if (b.Tag is Control) { Control c = b.Tag as Control; this.folderDialog.SelectedPath = c.Text; this.folderDialog.ShowNewFolderButton = true; } } DialogResult result = this.folderDialog.ShowDialog(); if ( (sender is Button) && (result == DialogResult.OK) ) { UpdateFromDialogSelection(sender as Button); UpdateData(); FileSelectorSelect(sender, e); UpdateForm(sender as Control); } } protected void UpdateFromDialogSelection(Button btn) { string targetField = null; GuiFilePicker guiPicker = null; foreach (GuiControl ctrl in this.guiControls.Values) { if (ctrl.ID == btn.Name) { guiPicker = ctrl as GuiFilePicker; if (guiPicker.PicksFolder) guiPicker.ItemData = this.folderDialog.SelectedPath; else guiPicker.ItemData = this.fileDialog.FileName; targetField = guiPicker.TargetControl; break; } } if ((targetField != null) && (guiPicker != null)) { foreach (GuiControl ctrl in this.guiControls.Values) { if ( (ctrl.ID == targetField) && (ctrl is GuiTextBox) ) { ((GuiTextBox)ctrl).Text = guiPicker.ItemData; break; } } } UpdateForm(btn); } public event EventHandler ComboBoxChange; public event EventHandler ListBoxChange; public event EventHandler ButtonClick; public event EventHandler CheckBoxClick; public event EventHandler FormClosing; public event EventHandler FileSelectorSelect; public event EventHandler CheckedListBoxChange; public event EventHandler TextBoxKeyPress; public event EventHandler ControlOnBlur; public event EventHandler ControlOnFocus; } public class ListControlItem { private string text = string.Empty; private string val = string.Empty; public ListControlItem(string val, string text) { this.val = val; this.text = text; } public override string ToString() { return text; } public string Text { get { return text; } } public string Value { get { return val; } } } }
namespace BaristaLabs.BaristaCore.Extensions.Tests { using BaristaLabs.BaristaCore.Extensions; using BaristaLabs.BaristaCore.ModuleLoaders; using BaristaLabs.BaristaCore.Modules; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using System; using Xunit; public class Fetch_Facts { public IBaristaRuntimeFactory GetRuntimeFactory() { var myMemoryModuleLoader = new InMemoryModuleLoader(); myMemoryModuleLoader.RegisterModule(new BlobModule()); myMemoryModuleLoader.RegisterModule(new FetchModule()); var serviceCollection = new ServiceCollection(); serviceCollection.AddBaristaCore(moduleLoader: myMemoryModuleLoader); var provider = serviceCollection.BuildServiceProvider(); return provider.GetRequiredService<IBaristaRuntimeFactory>(); } [Fact] public void CanFetchText() { var script = @" import fetch from 'barista-fetch'; export default fetch('https://httpbin.org/get'); "; var baristaRuntime = GetRuntimeFactory(); using (var rt = baristaRuntime.CreateRuntime()) { using (var ctx = rt.CreateContext()) { using (ctx.Scope()) { var response = ctx.EvaluateModule<JsObject>(script); var fnText = response.GetProperty<JsFunction>("text"); var textPromise = fnText.Call<JsObject>(response); var text = ctx.Promise.Wait<JsString>(textPromise); Assert.NotNull(text.ToString()); } } } } [Fact] public void CanFetchTextViaScript() { var script = @" import fetch from 'barista-fetch'; var fn = (async () => { var response = await fetch('https://httpbin.org/get'); var txt = await response.text(); return txt; })(); export default fn; "; var baristaRuntime = GetRuntimeFactory(); using (var rt = baristaRuntime.CreateRuntime()) { using (var ctx = rt.CreateContext()) { using (ctx.Scope()) { var text = ctx.EvaluateModule<JsString>(script); Assert.NotNull(text.ToString()); } } } } [Fact] public void CanFetchArrayBuffer() { Random rnd = new Random(); var byteLength = rnd.Next(1024); var script = $@" import fetch from 'barista-fetch'; export default fetch('https://httpbin.org/bytes/{byteLength}'); "; var baristaRuntime = GetRuntimeFactory(); using (var rt = baristaRuntime.CreateRuntime()) { using (var ctx = rt.CreateContext()) { using (ctx.Scope()) { var response = ctx.EvaluateModule<JsObject>(script); var fnText = response.GetProperty<JsFunction>("arrayBuffer"); var abPromise = fnText.Call<JsObject>(response); var imageBuffer = ctx.Promise.Wait<JsArrayBuffer>(abPromise); var data = imageBuffer.GetArrayBufferStorage(); Assert.NotNull(data); Assert.Equal(byteLength, data.Length); } } } } [Fact] public void CanPostAndGetJson() { var script = @" import fetch from 'barista-fetch'; var fn = (async () => { var response = await fetch('https://httpbin.org/post', { method: 'POST', body: JSON.stringify({ foo: 'bar' }) }); var json = await response.json(); return JSON.stringify(json); })(); export default fn; "; var baristaRuntime = GetRuntimeFactory(); using (var rt = baristaRuntime.CreateRuntime()) { using (var ctx = rt.CreateContext()) { using (ctx.Scope()) { var promise = ctx.EvaluateModule<JsObject>(script); var response = ctx.Promise.Wait<JsString>(promise); Assert.NotNull(response); var jsonData = response.ToString(); Assert.True(jsonData.Length > 0); dynamic data = JsonConvert.DeserializeObject(jsonData); Assert.Equal("bar", (string)data.json.foo); } } } } [Fact] public void CanPostAndGetBlob() { var script = @" import Blob from 'barista-blob'; import fetch from 'barista-fetch'; var fn = (async () => { var myBlob = Blob.fromUtf8String(JSON.stringify({ foo: 'bar' })); var response = await fetch('https://httpbin.org/post', { method: 'POST', body: myBlob }); var blob = await response.blob(); return blob.toUtf8String(); })(); export default fn; "; var baristaRuntime = GetRuntimeFactory(); using (var rt = baristaRuntime.CreateRuntime()) { using (var ctx = rt.CreateContext()) { using (ctx.Scope()) { var promise = ctx.EvaluateModule<JsString>(script); var response = ctx.Promise.Wait<JsObject>(promise); Assert.NotNull(response); var jsonData = response.ToString(); Assert.True(jsonData.Length > 0); dynamic data = JsonConvert.DeserializeObject(jsonData); Assert.Equal("bar", (string)data.json.foo); } } } } [Fact] public void CanPostAndGetArrayBuffer() { var script = @" import fetch from 'barista-fetch'; var fn = (async () => { function ab2str(buf) { return String.fromCharCode.apply(null, new Uint8Array(buf)); }; function str2ab(str) { var buf = new ArrayBuffer(str.length); var bufView = new Uint8Array(buf); for (var i=0, strLen=str.length; i<strLen; i++) { bufView[i] = str.charCodeAt(i); } return buf; }; var myAB = str2ab(JSON.stringify({ foo: 'bar' })); var response = await fetch('https://httpbin.org/post', { method: 'POST', body: myAB }); var ab = await response.arrayBuffer(); return ab2str(ab); })(); export default fn; "; var baristaRuntime = GetRuntimeFactory(); using (var rt = baristaRuntime.CreateRuntime()) { using (var ctx = rt.CreateContext()) { using (ctx.Scope()) { var promise = ctx.EvaluateModule<JsObject>(script); var response = ctx.Promise.Wait<JsString>(promise); Assert.NotNull(response); var jsonData = response.ToString(); Assert.True(jsonData.Length > 0); dynamic data = JsonConvert.DeserializeObject(jsonData); Assert.Equal("bar", (string)data.json.foo); } } } } [Fact] public void CanPostAndGetText() { var script = @" import fetch from 'barista-fetch'; var fn = (async () => { var response = await fetch('https://httpbin.org/post', { method: 'POST', body: 'hello, world!' }); var text = await response.text(); return text; })(); export default fn; "; var baristaRuntime = GetRuntimeFactory(); using (var rt = baristaRuntime.CreateRuntime()) { using (var ctx = rt.CreateContext()) { using (ctx.Scope()) { var promise = ctx.EvaluateModule<JsObject>(script); var response = ctx.Promise.Wait<JsString>(promise); Assert.NotNull(response); var jsonData = response.ToString(); Assert.True(jsonData.Length > 0); dynamic data = JsonConvert.DeserializeObject(jsonData); Assert.Equal("hello, world!", (string)data.data); } } } } [Fact] public void CanSetHeadersFromPOJO() { var script = @" import fetch from 'barista-fetch'; var fn = (async () => { var response = await fetch('https://httpbin.org/post', { method: 'POST', headers: { 'X-Foobar': 'foobar' }, body: JSON.stringify({ foo: 'bar' }) }); var json = await response.json(); return JSON.stringify(json); })(); export default fn; "; var baristaRuntime = GetRuntimeFactory(); using (var rt = baristaRuntime.CreateRuntime()) { using (var ctx = rt.CreateContext()) { using (ctx.Scope()) { var promise = ctx.EvaluateModule<JsObject>(script); var response = ctx.Promise.Wait<JsString>(promise); Assert.NotNull(response); var jsonData = response.ToString(); Assert.True(jsonData.Length > 0); dynamic data = JsonConvert.DeserializeObject(jsonData); Assert.Equal("foobar", (string)data.headers["X-Foobar"]); } } } } [Fact] public void CanSetHeadersFromHeadersObj() { var script = @" import fetch from 'barista-fetch'; var fn = (async () => { var headers = new fetch.Headers(); headers.append('X-Pure-and-natural', 'wild-caught-fish'); var response = await fetch('https://httpbin.org/post', { method: 'POST', headers: headers, body: JSON.stringify({ foo: 'bar' }) }); var json = await response.json(); return JSON.stringify(json); })(); export default fn; "; var baristaRuntime = GetRuntimeFactory(); using (var rt = baristaRuntime.CreateRuntime()) { using (var ctx = rt.CreateContext()) { using (ctx.Scope()) { var promise = ctx.EvaluateModule<JsObject>(script); var response = ctx.Promise.Wait<JsString>(promise); Assert.NotNull(response); var jsonData = response.ToString(); Assert.True(jsonData.Length > 0); dynamic data = JsonConvert.DeserializeObject(jsonData); Assert.Equal("wild-caught-fish", (string)data.headers["X-Pure-And-Natural"]); //Auto-Pascal-Casing is a thing, apparently, but confirmed that it's coming from httpbin } } } } [Fact] public void CanSetReferrer() { var script = @" import fetch from 'barista-fetch'; var fn = (async () => { var response = await fetch('https://httpbin.org/post', { method: 'POST', referrer: 'http://foo', body: JSON.stringify({ foo: 'bar' }) }); var json = await response.json(); return JSON.stringify(json); })(); export default fn; "; var baristaRuntime = GetRuntimeFactory(); using (var rt = baristaRuntime.CreateRuntime()) { using (var ctx = rt.CreateContext()) { using (ctx.Scope()) { var promise = ctx.EvaluateModule<JsObject>(script); var response = ctx.Promise.Wait<JsString>(promise); Assert.NotNull(response); var jsonData = response.ToString(); Assert.True(jsonData.Length > 0); dynamic data = JsonConvert.DeserializeObject(jsonData); Assert.Equal("http://foo/", (string)data.headers.Referer); } } } } [Fact] public void CanSetCache() { var script = @" import fetch from 'barista-fetch'; var fn = (async () => { var response = await fetch('https://httpbin.org/post', { method: 'POST', cache: 'only-if-cached', body: JSON.stringify({ foo: 'bar' }) }); var json = await response.json(); return JSON.stringify(json); })(); export default fn; "; var baristaRuntime = GetRuntimeFactory(); using (var rt = baristaRuntime.CreateRuntime()) { using (var ctx = rt.CreateContext()) { using (ctx.Scope()) { var promise = ctx.EvaluateModule<JsObject>(script); var response = ctx.Promise.Wait<JsString>(promise); Assert.NotNull(response); } } } } [Fact] public void CanSetCredentials() { var script = @" import fetch from 'barista-fetch'; var fn = (async () => { var response = await fetch('https://httpbin.org/post', { method: 'POST', credentials: 'include', body: JSON.stringify({ foo: 'bar' }) }); var json = await response.json(); return JSON.stringify(json); })(); export default fn; "; var baristaRuntime = GetRuntimeFactory(); using (var rt = baristaRuntime.CreateRuntime()) { using (var ctx = rt.CreateContext()) { using (ctx.Scope()) { var promise = ctx.EvaluateModule<JsObject>(script); var response = ctx.Promise.Wait<JsString>(promise); Assert.NotNull(response); } } } } [Fact] public void CanSetCookies() { var script = @" import fetch from 'barista-fetch'; var fn = (async () => { var response = await fetch('https://httpbin.org/post', { method: 'POST', cookies: { foo: 'bar' }, body: JSON.stringify({ foo: 'bar' }) }); var json = await response.json(); return JSON.stringify(json); })(); export default fn; "; var baristaRuntime = GetRuntimeFactory(); using (var rt = baristaRuntime.CreateRuntime()) { using (var ctx = rt.CreateContext()) { using (ctx.Scope()) { var promise = ctx.EvaluateModule<JsObject>(script); var response = ctx.Promise.Wait<JsString>(promise); Assert.NotNull(response); var jsonData = response.ToString(); Assert.True(jsonData.Length > 0); dynamic data = JsonConvert.DeserializeObject(jsonData); Assert.Equal("foo=bar", (string)data.headers.Cookie); } } } } [Fact] public void CanSetTimeout() { var script = @" import fetch from 'barista-fetch'; var fn = (async () => { var response = await fetch('https://httpbin.org/post', { method: 'POST', timeout: 30000, body: JSON.stringify({ foo: 'bar' }) }); var json = await response.json(); return JSON.stringify(json); })(); export default fn; "; var baristaRuntime = GetRuntimeFactory(); using (var rt = baristaRuntime.CreateRuntime()) { using (var ctx = rt.CreateContext()) { using (ctx.Scope()) { var promise = ctx.EvaluateModule<JsObject>(script); var response = ctx.Promise.Wait<JsString>(promise); Assert.NotNull(response); } } } } [Fact] public void CanSetUserAgent() { var script = @" import fetch from 'barista-fetch'; var fn = (async () => { var response = await fetch('https://httpbin.org/post', { method: 'POST', 'user-agent': 'curl/7.9.8 (i686-pc-linux-gnu) libcurl 7.9.8 (OpenSSL 0.9.6b) (ipv6 enabled)', body: JSON.stringify({ foo: 'bar' }) }); var json = await response.json(); return JSON.stringify(json); })(); export default fn; "; var baristaRuntime = GetRuntimeFactory(); using (var rt = baristaRuntime.CreateRuntime()) { using (var ctx = rt.CreateContext()) { using (ctx.Scope()) { var promise = ctx.EvaluateModule<JsString>(script); var response = ctx.Promise.Wait<JsString>(promise); Assert.NotNull(response); var jsonData = response.ToString(); Assert.True(jsonData.Length > 0); dynamic data = JsonConvert.DeserializeObject(jsonData); Assert.Equal("curl/7.9.8 (i686-pc-linux-gnu) libcurl 7.9.8 (OpenSSL 0.9.6b) (ipv6 enabled)", (string)data.headers["User-Agent"]); } } } } [Fact] public void CanCreateAndCloneRequest() { var script = @" import fetch from 'barista-fetch'; var myRequest = new fetch.Request('https://httpbin.org/get', null); var clonedRequest = myRequest.clone(); var newNewRequest = new fetch.Request(clonedRequest); export default fetch(clonedRequest); "; var baristaRuntime = GetRuntimeFactory(); using (var rt = baristaRuntime.CreateRuntime()) { using (var ctx = rt.CreateContext()) { using (ctx.Scope()) { var response = ctx.EvaluateModule<JsObject>(script); var fnText = response.GetProperty<JsFunction>("text"); var textPromise = fnText.Call<JsObject>(response); var text = ctx.Promise.Wait<JsString>(textPromise); Assert.NotNull(text.ToString()); } } } } [Fact] public void CanGetResponseProperties() { var script = @" import fetch from 'barista-fetch'; var fn = (async () => { var response = await fetch('https://httpbin.org/status/418'); return response; })(); export default fn; "; var baristaRuntime = GetRuntimeFactory(); using (var rt = baristaRuntime.CreateRuntime()) { using (var ctx = rt.CreateContext()) { using (ctx.Scope()) { var promise = ctx.EvaluateModule<JsObject>(script); var response = ctx.Promise.Wait<JsObject>(promise); Assert.NotNull(response); Assert.False(response["ok"].ToBoolean()); Assert.Equal(418, response["statusCode"].ToInt32()); Assert.Equal("I'M A TEAPOT", response["statusText"].ToString()); Assert.False(response["bodyUsed"].ToBoolean()); ctx.Promise.Wait((response["text"] as JsFunction).Call(response) as JsObject); Assert.True(response["bodyUsed"].ToBoolean()); } } } } [Fact] public void CanSetRedirect() { var script = @" import fetch from 'barista-fetch'; var fn = (async () => { var response = await fetch('https://httpbin.org/redirect/6', { redirect: 'error' } ); return response; })(); export default fn; "; var baristaRuntime = GetRuntimeFactory(); using (var rt = baristaRuntime.CreateRuntime()) { using (var ctx = rt.CreateContext()) { using (ctx.Scope()) { var promise = ctx.EvaluateModule<JsObject>(script); var response = ctx.Promise.Wait<JsObject>(promise); Assert.NotNull(response); Assert.False(response["ok"].ToBoolean()); Assert.Equal(302, response["statusCode"].ToInt32()); Assert.Equal("FOUND", response["statusText"].ToString()); } } } } [Fact] public void CanCloneResponse() { var script = @" import fetch from 'barista-fetch'; var fn = (async () => { var response = await fetch('https://httpbin.org/status/418'); var newResponse = response.clone(); await response.text(); return newResponse; })(); export default fn; "; var baristaRuntime = GetRuntimeFactory(); using (var rt = baristaRuntime.CreateRuntime()) { using (var ctx = rt.CreateContext()) { using (ctx.Scope()) { var promise = ctx.EvaluateModule<JsObject>(script); var response = ctx.Promise.Wait<JsObject>(promise); Assert.NotNull(response); Assert.False(response["ok"].ToBoolean()); Assert.Equal(418, response["statusCode"].ToInt32()); Assert.False(response["bodyUsed"].ToBoolean()); } } } } [Fact] public void CanGetResponseHeaders() { var script = @" import fetch from 'barista-fetch'; var fn = (async () => { var response = await fetch('https://httpbin.org/response-headers?X-Foo=bar'); return response.headers.get('X-Foo'); })(); export default fn; "; var baristaRuntime = GetRuntimeFactory(); using (var rt = baristaRuntime.CreateRuntime()) { using (var ctx = rt.CreateContext()) { using (ctx.Scope()) { var promise = ctx.EvaluateModule<JsObject>(script); var response = ctx.Promise.Wait<JsObject>(promise); Assert.NotNull(response); Assert.Equal("bar", response.ToString()); } } } } [Fact] public void CanManipulateResponseHeaders() { var script = @" import fetch from 'barista-fetch'; var fn = (async () => { var response = await fetch('https://httpbin.org/response-headers?X-Foo=bar'); return response.headers; })(); export default fn; "; var baristaRuntime = GetRuntimeFactory(); using (var rt = baristaRuntime.CreateRuntime()) { using (var ctx = rt.CreateContext()) { using (ctx.Scope()) { var promise = ctx.EvaluateModule<JsObject>(script); dynamic headers = ctx.Promise.Wait<JsObject>(promise); Assert.NotNull(headers); Assert.Equal("bar", (string)headers.get("X-Foo")); headers.set("X-Bag", "bagman"); Assert.True((bool)headers.has("X-Bag")); headers.append("X-Bag", "robbin"); //Yield statement -- this contains an auto-generated iterator. var entriesIterator = headers.entries() as JsObject; Assert.NotNull(entriesIterator); //KeyCollection -- this is an object with an iterator property. var keysIterator = headers.keys("X-Bag") as JsObject; Assert.NotNull(keysIterator); //yield statement -- this contains an auto-generatoed iterator. var valuesIterator = headers.values("X-Bag") as JsObject; Assert.NotNull(valuesIterator); headers.delete("X-Bag"); Assert.False((bool)headers.has("X-Bag")); } } } } [Fact] public void CanIterateHeaders() { var script = @" import fetch from 'barista-fetch'; var fn = (async () => { var response = await fetch('https://httpbin.org/response-headers?X-Foo=bar&X-Foo=baz'); var result = {}; result.entries = []; for(var entry of response.headers.entries()) { result.entries.push(entry); } result.keys = []; for(var entry of response.headers.keys('X-Foo')) { result.keys.push(entry); } result.values = []; for(var entry of response.headers.values('X-Foo')) { result.values.push(entry); } return result; })(); export default fn; "; var baristaRuntime = GetRuntimeFactory(); using (var rt = baristaRuntime.CreateRuntime()) { using (var ctx = rt.CreateContext()) { using (ctx.Scope()) { var promise = ctx.EvaluateModule<JsObject>(script); var headersResult = ctx.Promise.Wait<JsObject>(promise); Assert.NotNull(headersResult); Assert.Equal(9, headersResult.GetProperty<JsObject>("entries")["length"].ToInt32()); Assert.Equal(9, headersResult.GetProperty<JsObject>("keys")["length"].ToInt32()); Assert.Equal(9, headersResult.GetProperty<JsObject>("values")["length"].ToInt32()); } } } } } }
namespace Reverb.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class InitialCreate : DbMigration { public override void Up() { CreateTable( "dbo.Albums", c => new { Id = c.Guid(nullable: false), Title = c.String(nullable: false), IsDeleted = c.Boolean(nullable: false), DeletedOn = c.DateTime(), CreatedOn = c.DateTime(), ModifiedOn = c.DateTime(), Artist_Id = c.Guid(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Artists", t => t.Artist_Id) .Index(t => t.IsDeleted) .Index(t => t.Artist_Id); CreateTable( "dbo.Artists", c => new { Id = c.Guid(nullable: false), Name = c.String(nullable: false, maxLength: 20), IsDeleted = c.Boolean(nullable: false), DeletedOn = c.DateTime(), CreatedOn = c.DateTime(), ModifiedOn = c.DateTime(), }) .PrimaryKey(t => t.Id) .Index(t => t.IsDeleted); CreateTable( "dbo.Songs", c => new { Id = c.Guid(nullable: false), Title = c.String(nullable: false, maxLength: 20), Duration = c.Int(), Lyrics = c.String(storeType: "ntext"), IsDeleted = c.Boolean(nullable: false), DeletedOn = c.DateTime(), CreatedOn = c.DateTime(), ModifiedOn = c.DateTime(), Album_Id = c.Guid(), Artist_Id = c.Guid(nullable: false), User_Id = c.String(maxLength: 128), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Albums", t => t.Album_Id) .ForeignKey("dbo.Artists", t => t.Artist_Id, cascadeDelete: true) .ForeignKey("dbo.AspNetUsers", t => t.User_Id) .Index(t => t.IsDeleted) .Index(t => t.Album_Id) .Index(t => t.Artist_Id) .Index(t => t.User_Id); CreateTable( "dbo.Genres", c => new { Id = c.Guid(nullable: false), Name = c.String(nullable: false, maxLength: 20), IsDeleted = c.Boolean(nullable: false), DeletedOn = c.DateTime(), CreatedOn = c.DateTime(), ModifiedOn = c.DateTime(), }) .PrimaryKey(t => t.Id) .Index(t => t.IsDeleted); CreateTable( "dbo.AspNetRoles", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.Name, unique: true, name: "RoleNameIndex"); CreateTable( "dbo.AspNetUserRoles", c => new { UserId = c.String(nullable: false, maxLength: 128), RoleId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.UserId, t.RoleId }) .ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: true) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId) .Index(t => t.RoleId); CreateTable( "dbo.AspNetUsers", c => new { Id = c.String(nullable: false, maxLength: 128), IsDeleted = c.Boolean(nullable: false), DeletedOn = c.DateTime(), CreatedOn = c.DateTime(), ModifiedOn = c.DateTime(), Email = c.String(maxLength: 256), EmailConfirmed = c.Boolean(nullable: false), PasswordHash = c.String(), SecurityStamp = c.String(), PhoneNumber = c.String(), PhoneNumberConfirmed = c.Boolean(nullable: false), TwoFactorEnabled = c.Boolean(nullable: false), LockoutEndDateUtc = c.DateTime(), LockoutEnabled = c.Boolean(nullable: false), AccessFailedCount = c.Int(nullable: false), UserName = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.IsDeleted) .Index(t => t.UserName, unique: true, name: "UserNameIndex"); CreateTable( "dbo.AspNetUserClaims", c => new { Id = c.Int(nullable: false, identity: true), UserId = c.String(nullable: false, maxLength: 128), ClaimType = c.String(), ClaimValue = c.String(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AspNetUserLogins", c => new { LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 128), UserId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.GenreSongs", c => new { Genre_Id = c.Guid(nullable: false), Song_Id = c.Guid(nullable: false), }) .PrimaryKey(t => new { t.Genre_Id, t.Song_Id }) .ForeignKey("dbo.Genres", t => t.Genre_Id, cascadeDelete: true) .ForeignKey("dbo.Songs", t => t.Song_Id, cascadeDelete: true) .Index(t => t.Genre_Id) .Index(t => t.Song_Id); } public override void Down() { DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.Songs", "User_Id", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles"); DropForeignKey("dbo.GenreSongs", "Song_Id", "dbo.Songs"); DropForeignKey("dbo.GenreSongs", "Genre_Id", "dbo.Genres"); DropForeignKey("dbo.Songs", "Artist_Id", "dbo.Artists"); DropForeignKey("dbo.Songs", "Album_Id", "dbo.Albums"); DropForeignKey("dbo.Albums", "Artist_Id", "dbo.Artists"); DropIndex("dbo.GenreSongs", new[] { "Song_Id" }); DropIndex("dbo.GenreSongs", new[] { "Genre_Id" }); DropIndex("dbo.AspNetUserLogins", new[] { "UserId" }); DropIndex("dbo.AspNetUserClaims", new[] { "UserId" }); DropIndex("dbo.AspNetUsers", "UserNameIndex"); DropIndex("dbo.AspNetUsers", new[] { "IsDeleted" }); DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" }); DropIndex("dbo.AspNetUserRoles", new[] { "UserId" }); DropIndex("dbo.AspNetRoles", "RoleNameIndex"); DropIndex("dbo.Genres", new[] { "IsDeleted" }); DropIndex("dbo.Songs", new[] { "User_Id" }); DropIndex("dbo.Songs", new[] { "Artist_Id" }); DropIndex("dbo.Songs", new[] { "Album_Id" }); DropIndex("dbo.Songs", new[] { "IsDeleted" }); DropIndex("dbo.Artists", new[] { "IsDeleted" }); DropIndex("dbo.Albums", new[] { "Artist_Id" }); DropIndex("dbo.Albums", new[] { "IsDeleted" }); DropTable("dbo.GenreSongs"); DropTable("dbo.AspNetUserLogins"); DropTable("dbo.AspNetUserClaims"); DropTable("dbo.AspNetUsers"); DropTable("dbo.AspNetUserRoles"); DropTable("dbo.AspNetRoles"); DropTable("dbo.Genres"); DropTable("dbo.Songs"); DropTable("dbo.Artists"); DropTable("dbo.Albums"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.Apple; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class AppleCrypto { [DllImport(Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_SecKeyImportEphemeral( byte[] pbKeyBlob, int cbKeyBlob, int isPrivateKey, out SafeSecKeyRefHandle ppKeyOut, out int pOSStatus); private static int AppleCryptoNative_GenerateSignature( SafeSecKeyRefHandle privateKey, ReadOnlySpan<byte> pbDataHash, int cbDataHash, out SafeCFDataHandle pSignatureOut, out SafeCFErrorHandle pErrorOut) => AppleCryptoNative_GenerateSignature( privateKey, ref pbDataHash.DangerousGetPinnableReference(), cbDataHash, out pSignatureOut, out pErrorOut); [DllImport(Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_GenerateSignature( SafeSecKeyRefHandle privateKey, ref byte pbDataHash, int cbDataHash, out SafeCFDataHandle pSignatureOut, out SafeCFErrorHandle pErrorOut); private static int AppleCryptoNative_GenerateSignatureWithHashAlgorithm( SafeSecKeyRefHandle privateKey, ReadOnlySpan<byte> pbDataHash, int cbDataHash, PAL_HashAlgorithm hashAlgorithm, out SafeCFDataHandle pSignatureOut, out SafeCFErrorHandle pErrorOut) => AppleCryptoNative_GenerateSignatureWithHashAlgorithm( privateKey, ref pbDataHash.DangerousGetPinnableReference(), cbDataHash, hashAlgorithm, out pSignatureOut, out pErrorOut); [DllImport(Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_GenerateSignatureWithHashAlgorithm( SafeSecKeyRefHandle privateKey, ref byte pbDataHash, int cbDataHash, PAL_HashAlgorithm hashAlgorithm, out SafeCFDataHandle pSignatureOut, out SafeCFErrorHandle pErrorOut); private static int AppleCryptoNative_VerifySignature( SafeSecKeyRefHandle publicKey, ReadOnlySpan<byte> pbDataHash, int cbDataHash, ReadOnlySpan<byte> pbSignature, int cbSignature, out SafeCFErrorHandle pErrorOut) => AppleCryptoNative_VerifySignature( publicKey, ref pbDataHash.DangerousGetPinnableReference(), cbDataHash, ref pbSignature.DangerousGetPinnableReference(), cbSignature, out pErrorOut); [DllImport(Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_VerifySignature( SafeSecKeyRefHandle publicKey, ref byte pbDataHash, int cbDataHash, ref byte pbSignature, int cbSignature, out SafeCFErrorHandle pErrorOut); private static int AppleCryptoNative_VerifySignatureWithHashAlgorithm( SafeSecKeyRefHandle publicKey, ReadOnlySpan<byte> pbDataHash, int cbDataHash, ReadOnlySpan<byte> pbSignature, int cbSignature, PAL_HashAlgorithm hashAlgorithm, out SafeCFErrorHandle pErrorOut) => AppleCryptoNative_VerifySignatureWithHashAlgorithm( publicKey, ref pbDataHash.DangerousGetPinnableReference(), cbDataHash, ref pbSignature.DangerousGetPinnableReference(), cbSignature, hashAlgorithm, out pErrorOut); [DllImport(Libraries.AppleCryptoNative)] private static extern int AppleCryptoNative_VerifySignatureWithHashAlgorithm( SafeSecKeyRefHandle publicKey, ref byte pbDataHash, int cbDataHash, ref byte pbSignature, int cbSignature, PAL_HashAlgorithm hashAlgorithm, out SafeCFErrorHandle pErrorOut); [DllImport(Libraries.AppleCryptoNative)] private static extern ulong AppleCryptoNative_SecKeyGetSimpleKeySizeInBytes(SafeSecKeyRefHandle publicKey); private delegate int SecKeyTransform(ReadOnlySpan<byte> source, out SafeCFDataHandle outputHandle, out SafeCFErrorHandle errorHandle); private static byte[] ExecuteTransform(ReadOnlySpan<byte> source, SecKeyTransform transform) { const int Success = 1; const int kErrorSeeError = -2; SafeCFDataHandle data; SafeCFErrorHandle error; int ret = transform(source, out data, out error); using (error) using (data) { if (ret == Success) { return CoreFoundation.CFGetData(data); } if (ret == kErrorSeeError) { throw CreateExceptionForCFError(error); } Debug.Fail($"transform returned {ret}"); throw new CryptographicException(); } } private static bool TryExecuteTransform( ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten, SecKeyTransform transform) { SafeCFDataHandle outputHandle; SafeCFErrorHandle errorHandle; int ret = transform(source, out outputHandle, out errorHandle); using (errorHandle) using (outputHandle) { const int Success = 1; const int kErrorSeeError = -2; switch (ret) { case Success: return CoreFoundation.TryCFWriteData(outputHandle, destination, out bytesWritten); case kErrorSeeError: throw CreateExceptionForCFError(errorHandle); default: Debug.Fail($"transform returned {ret}"); throw new CryptographicException(); } } } internal static int GetSimpleKeySizeInBits(SafeSecKeyRefHandle publicKey) { ulong keySizeInBytes = AppleCryptoNative_SecKeyGetSimpleKeySizeInBytes(publicKey); checked { return (int)(keySizeInBytes * 8); } } internal static SafeSecKeyRefHandle ImportEphemeralKey(byte[] keyBlob, bool hasPrivateKey) { Debug.Assert(keyBlob != null); SafeSecKeyRefHandle keyHandle; int osStatus; int ret = AppleCryptoNative_SecKeyImportEphemeral( keyBlob, keyBlob.Length, hasPrivateKey ? 1 : 0, out keyHandle, out osStatus); if (ret == 1 && !keyHandle.IsInvalid) { return keyHandle; } if (ret == 0) { throw CreateExceptionForOSStatus(osStatus); } Debug.Fail($"SecKeyImportEphemeral returned {ret}"); throw new CryptographicException(); } internal static byte[] GenerateSignature(SafeSecKeyRefHandle privateKey, ReadOnlySpan<byte> dataHash) { Debug.Assert(privateKey != null, "privateKey != null"); return ExecuteTransform( dataHash, (ReadOnlySpan<byte> source, out SafeCFDataHandle signature, out SafeCFErrorHandle error) => AppleCryptoNative_GenerateSignature( privateKey, source, source.Length, out signature, out error)); } internal static byte[] GenerateSignature( SafeSecKeyRefHandle privateKey, ReadOnlySpan<byte> dataHash, PAL_HashAlgorithm hashAlgorithm) { Debug.Assert(privateKey != null, "privateKey != null"); Debug.Assert(hashAlgorithm != PAL_HashAlgorithm.Unknown, "hashAlgorithm != PAL_HashAlgorithm.Unknown"); return ExecuteTransform( dataHash, (ReadOnlySpan<byte> source, out SafeCFDataHandle signature, out SafeCFErrorHandle error) => AppleCryptoNative_GenerateSignatureWithHashAlgorithm( privateKey, source, source.Length, hashAlgorithm, out signature, out error)); } internal static bool TryGenerateSignature( SafeSecKeyRefHandle privateKey, ReadOnlySpan<byte> source, Span<byte> destination, PAL_HashAlgorithm hashAlgorithm, out int bytesWritten) { Debug.Assert(privateKey != null, "privateKey != null"); Debug.Assert(hashAlgorithm != PAL_HashAlgorithm.Unknown, "hashAlgorithm != PAL_HashAlgorithm.Unknown"); return TryExecuteTransform( source, destination, out bytesWritten, delegate (ReadOnlySpan<byte> innerSource, out SafeCFDataHandle outputHandle, out SafeCFErrorHandle errorHandle) { return AppleCryptoNative_GenerateSignatureWithHashAlgorithm( privateKey, innerSource, innerSource.Length, hashAlgorithm, out outputHandle, out errorHandle); }); } internal static bool VerifySignature( SafeSecKeyRefHandle publicKey, ReadOnlySpan<byte> dataHash, ReadOnlySpan<byte> signature) { Debug.Assert(publicKey != null, "publicKey != null"); SafeCFErrorHandle error; int ret = AppleCryptoNative_VerifySignature( publicKey, dataHash, dataHash.Length, signature, signature.Length, out error); const int True = 1; const int False = 0; const int kErrorSeeError = -2; using (error) { switch (ret) { case True: return true; case False: return false; case kErrorSeeError: throw CreateExceptionForCFError(error); default: Debug.Fail($"VerifySignature returned {ret}"); throw new CryptographicException(); } } } internal static bool VerifySignature( SafeSecKeyRefHandle publicKey, ReadOnlySpan<byte> dataHash, ReadOnlySpan<byte> signature, PAL_HashAlgorithm hashAlgorithm) { Debug.Assert(publicKey != null, "publicKey != null"); Debug.Assert(hashAlgorithm != PAL_HashAlgorithm.Unknown); SafeCFErrorHandle error; int ret = AppleCryptoNative_VerifySignatureWithHashAlgorithm( publicKey, dataHash, dataHash.Length, signature, signature.Length, hashAlgorithm, out error); const int True = 1; const int False = 0; const int kErrorSeeError = -2; using (error) { switch (ret) { case True: return true; case False: return false; case kErrorSeeError: throw CreateExceptionForCFError(error); default: Debug.Fail($"VerifySignature returned {ret}"); throw new CryptographicException(); } } } } } namespace System.Security.Cryptography.Apple { internal sealed class SafeSecKeyRefHandle : SafeKeychainItemHandle { } }
using System; using System.Runtime.InteropServices; using System.Text; namespace DbgEng.NoExceptions { [ComImport, Guid("D98ADA1F-29E9-4EF5-A6C0-E53349883212"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDebugDataSpaces4 : IDebugDataSpaces3 { #pragma warning disable CS0108 // XXX hides inherited member. This is COM default. #region IDebugDataSpaces [PreserveSig] int ReadVirtual( [In] ulong Offset, [Out] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesRead); [PreserveSig] int WriteVirtual( [In] ulong Offset, [In] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesWritten); [PreserveSig] int SearchVirtual( [In] ulong Offset, [In] ulong Length, [In] IntPtr Pattern, [In] uint PatternSize, [In] uint PatternGranularity, [Out] out ulong Address); [PreserveSig] int ReadVirtualUncached( [In] ulong Offset, [Out] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesRead); [PreserveSig] int WriteVirtualUncached( [In] ulong Offset, [In] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesWritten); [PreserveSig] int ReadPointersVirtual( [In] uint Count, [In] ulong Offset, [Out] out ulong Address); [PreserveSig] int WritePointersVirtual( [In] uint Count, [In] ulong Offset, [In] ref ulong Ptrs); [PreserveSig] int ReadPhysical( [In] ulong Offset, [Out] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesRead); [PreserveSig] int WritePhysical( [In] ulong Offset, [In] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesWritten); [PreserveSig] int ReadControl( [In] uint Processor, [In] ulong Offset, [Out] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesRead); [PreserveSig] int WriteControl( [In] uint Processor, [In] ulong Offset, [In] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesWritten); [PreserveSig] int ReadIo( [In] uint InterfaceType, [In] uint BusNumber, [In] uint AddressSpace, [In] ulong Offset, [Out] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesRead); [PreserveSig] int WriteIo( [In] uint InterfaceType, [In] uint BusNumber, [In] uint AddressSpace, [In] ulong Offset, [In] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesWritten); [PreserveSig] int ReadMsr( [In] uint Msr, [Out] out ulong Value); [PreserveSig] int WriteMsr( [In] uint Msr, [In] ulong Value); [PreserveSig] int ReadBusData( [In] uint BusDataType, [In] uint BusNumber, [In] uint SlotNumber, [In] uint Offset, [Out] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesRead); [PreserveSig] int WriteBusData( [In] uint BusDataType, [In] uint BusNumber, [In] uint SlotNumber, [In] uint Offset, [In] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesWritten); [PreserveSig] int CheckLowMemory(); [PreserveSig] int ReadDebuggerData( [In] uint Index, [Out] IntPtr Buffer, [In] uint BufferSize, [Out] out uint DataSize); [PreserveSig] int ReadProcessorSystemData( [In] uint Processor, [In] uint Index, [Out] IntPtr Buffer, [In] uint BufferSize, [Out] out uint DataSize); #endregion #region IDebugDataSpaces2 [PreserveSig] int VirtualToPhysical( [In] ulong Virtual, [Out] out ulong Physical); [PreserveSig] int GetVirtualTranslationPhysicalOffsets( [In] ulong Virtual, [Out] out ulong Offsets, [In] uint OffsetsSize, [Out] out uint Levels); [PreserveSig] int ReadHandleData( [In] ulong Handle, [In] uint DataType, [Out] IntPtr Buffer, [In] uint BufferSize, [Out] out uint DataSize); [PreserveSig] int FillVirtual( [In] ulong Start, [In] uint Size, [In] IntPtr Pattern, [In] uint PatternSize, [Out] out uint Filled); [PreserveSig] int FillPhysical( [In] ulong Start, [In] uint Size, [In] IntPtr Pattern, [In] uint PatternSize, [Out] out uint Filled); [PreserveSig] int QueryVirtual( [In] ulong Offset, [Out] out _MEMORY_BASIC_INFORMATION64 Information); #endregion #region IDebugDataSpaces3 [PreserveSig] int ReadImageNtHeaders( [In] ulong ImageBase, [Out] out _IMAGE_NT_HEADERS64 Headers); [PreserveSig] int ReadTagged( [In] ref Guid Tag, [In] uint Offset, [Out] IntPtr Buffer, [In] uint BufferSize, [Out] out uint TotalSize); [PreserveSig] int StartEnumTagged( [Out] out ulong Handle); [PreserveSig] int GetNextTagged( [In] ulong Handle, [Out] out Guid Tag, [Out] out uint Size); [PreserveSig] int EndEnumTagged( [In] ulong Handle); #endregion #pragma warning restore CS0108 // XXX hides inherited member. This is COM default. [PreserveSig] int GetOffsetInformation( [In] uint Space, [In] uint Which, [In] ulong Offset, [Out] IntPtr Buffer, [In] uint BufferSize, [Out] out uint InfoSize); [PreserveSig] int GetNextDifferentlyValidOffsetVirtual( [In] ulong Offset, [Out] out ulong Address); [PreserveSig] int GetValidRegionVirtual( [In] ulong Base, [In] uint Size, [Out] out ulong ValidBase, [Out] out uint ValidSize); [PreserveSig] int SearchVirtual2( [In] ulong Offset, [In] ulong Length, [In] uint Flags, [In] IntPtr Pattern, [In] uint PatternSize, [In] uint PatternGranularity, [Out] out ulong Address); [PreserveSig] int ReadMultiByteStringVirtual( [In] ulong Offset, [In] uint MaxBytes, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint StringBytes); [PreserveSig] int ReadMultiByteStringVirtualWide( [In] ulong Offset, [In] uint MaxBytes, [In] uint CodePage, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint StringBytes); [PreserveSig] int ReadUnicodeStringVirtual( [In] ulong Offset, [In] uint MaxBytes, [In] uint CodePage, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint StringBytes); [PreserveSig] int ReadUnicodeStringVirtualWide( [In] ulong Offset, [In] uint MaxBytes, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint StringBytes); [PreserveSig] int ReadPhysical2( [In] ulong Offset, [In] uint Flags, [Out] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesRead); [PreserveSig] int WritePhysical2( [In] ulong Offset, [In] uint Flags, [In] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesWritten); } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using JCG = J2N.Collections.Generic; namespace YAF.Lucene.Net.Util.Automaton { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Just holds a set of <see cref="T:int[]"/> states, plus a corresponding /// <see cref="T:int[]"/> count per state. Used by /// <see cref="BasicOperations.Determinize(Automaton)"/>. /// <para/> /// NOTE: This was SortedIntSet in Lucene /// </summary> internal sealed class SortedInt32Set : IEquatable<SortedInt32Set>, IEquatable<SortedInt32Set.FrozenInt32Set> { internal int[] values; internal int[] counts; internal int upto; private int hashCode; // If we hold more than this many states, we switch from // O(N^2) linear ops to O(N log(N)) TreeMap private const int TREE_MAP_CUTOVER = 30; private readonly IDictionary<int, int> map = new JCG.SortedDictionary<int, int>(); private bool useTreeMap; internal State state; public SortedInt32Set(int capacity) { values = new int[capacity]; counts = new int[capacity]; } // Adds this state to the set public void Incr(int num) { if (useTreeMap) { int key = num; int val; if (!map.TryGetValue(key, out val)) { map[key] = 1; } else { map[key] = 1 + val; } return; } if (upto == values.Length) { values = ArrayUtil.Grow(values, 1 + upto); counts = ArrayUtil.Grow(counts, 1 + upto); } for (int i = 0; i < upto; i++) { if (values[i] == num) { counts[i]++; return; } else if (num < values[i]) { // insert here int j = upto - 1; while (j >= i) { values[1 + j] = values[j]; counts[1 + j] = counts[j]; j--; } values[i] = num; counts[i] = 1; upto++; return; } } // append values[upto] = num; counts[upto] = 1; upto++; if (upto == TREE_MAP_CUTOVER) { useTreeMap = true; for (int i = 0; i < upto; i++) { map[values[i]] = counts[i]; } } } // Removes this state from the set, if count decrs to 0 public void Decr(int num) { if (useTreeMap) { int count = map[num]; if (count == 1) { map.Remove(num); } else { map[num] = count - 1; } // Fall back to simple arrays once we touch zero again if (map.Count == 0) { useTreeMap = false; upto = 0; } return; } for (int i = 0; i < upto; i++) { if (values[i] == num) { counts[i]--; if (counts[i] == 0) { int limit = upto - 1; while (i < limit) { values[i] = values[i + 1]; counts[i] = counts[i + 1]; i++; } upto = limit; } return; } } Debug.Assert(false); } public void ComputeHash() { if (useTreeMap) { if (map.Count > values.Length) { int size = ArrayUtil.Oversize(map.Count, RamUsageEstimator.NUM_BYTES_INT32); values = new int[size]; counts = new int[size]; } hashCode = map.Count; upto = 0; foreach (int state in map.Keys) { hashCode = 683 * hashCode + state; values[upto++] = state; } } else { hashCode = upto; for (int i = 0; i < upto; i++) { hashCode = 683 * hashCode + values[i]; } } } public FrozenInt32Set ToFrozenInt32Set() // LUCENENET TODO: This didn't exist in the original { int[] c = new int[upto]; Array.Copy(values, 0, c, 0, upto); return new FrozenInt32Set(c, this.hashCode, this.state); } public FrozenInt32Set Freeze(State state) { int[] c = new int[upto]; Array.Copy(values, 0, c, 0, upto); return new FrozenInt32Set(c, hashCode, state); } public override int GetHashCode() { return hashCode; } public override bool Equals(object other) { if (other == null) { return false; } if (!(other is FrozenInt32Set)) { return false; } FrozenInt32Set other2 = (FrozenInt32Set)other; if (hashCode != other2.hashCode) { return false; } if (other2.values.Length != upto) { return false; } for (int i = 0; i < upto; i++) { if (other2.values[i] != values[i]) { return false; } } return true; } public bool Equals(SortedInt32Set other) // LUCENENET TODO: This didn't exist in the original { throw new NotImplementedException("SortedIntSet Equals"); } public bool Equals(FrozenInt32Set other) // LUCENENET TODO: This didn't exist in the original { if (other == null) { return false; } if (hashCode != other.hashCode) { return false; } if (other.values.Length != upto) { return false; } for (int i = 0; i < upto; i++) { if (other.values[i] != values[i]) { return false; } } return true; } public override string ToString() { StringBuilder sb = (new StringBuilder()).Append('['); for (int i = 0; i < upto; i++) { if (i > 0) { sb.Append(' '); } sb.Append(values[i]).Append(':').Append(counts[i]); } sb.Append(']'); return sb.ToString(); } /// <summary> /// NOTE: This was FrozenIntSet in Lucene /// </summary> public sealed class FrozenInt32Set : IEquatable<SortedInt32Set>, IEquatable<FrozenInt32Set> { internal readonly int[] values; internal readonly int hashCode; internal readonly State state; public FrozenInt32Set(int[] values, int hashCode, State state) { this.values = values; this.hashCode = hashCode; this.state = state; } public FrozenInt32Set(int num, State state) { this.values = new int[] { num }; this.state = state; this.hashCode = 683 + num; } public override int GetHashCode() { return hashCode; } public override bool Equals(object other) { if (other == null) { return false; } if (other is FrozenInt32Set) { FrozenInt32Set other2 = (FrozenInt32Set)other; if (hashCode != other2.hashCode) { return false; } if (other2.values.Length != values.Length) { return false; } for (int i = 0; i < values.Length; i++) { if (other2.values[i] != values[i]) { return false; } } return true; } else if (other is SortedInt32Set) { SortedInt32Set other3 = (SortedInt32Set)other; if (hashCode != other3.hashCode) { return false; } if (other3.values.Length != values.Length) { return false; } for (int i = 0; i < values.Length; i++) { if (other3.values[i] != values[i]) { return false; } } return true; } return false; } public bool Equals(SortedInt32Set other) // LUCENENET TODO: This didn't exist in the original { if (other == null) { return false; } if (hashCode != other.hashCode) { return false; } if (other.values.Length != values.Length) { return false; } for (int i = 0; i < values.Length; i++) { if (other.values[i] != values[i]) { return false; } } return true; } public bool Equals(FrozenInt32Set other) // LUCENENET TODO: This didn't exist in the original { if (other == null) { return false; } if (hashCode != other.hashCode) { return false; } if (other.values.Length != values.Length) { return false; } for (int i = 0; i < values.Length; i++) { if (other.values[i] != values[i]) { return false; } } return true; } public override string ToString() { StringBuilder sb = (new StringBuilder()).Append('['); for (int i = 0; i < values.Length; i++) { if (i > 0) { sb.Append(' '); } sb.Append(values[i]); } sb.Append(']'); return sb.ToString(); } } } }
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange // // Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; #if CORE #endif #if GDI using System.Drawing; using System.Drawing.Drawing2D; #endif #if WPF using System.Windows; using System.Windows.Media; using SysPoint = System.Windows.Point; using SysSize = System.Windows.Size; using SysRect = System.Windows.Rect; #endif #if NETFX_CORE using Windows.UI.Xaml.Media; using SysPoint = Windows.Foundation.Point; using SysSize = Windows.Foundation.Size; using SysRect = Windows.Foundation.Rect; #endif #if !EDF_CORE using PdfSharp.Internal; #else using PdfSharp.Internal; #endif namespace PdfSharp.Drawing { /// <summary> /// Stores a set of four floating-point numbers that represent the location and size of a rectangle. /// </summary> [DebuggerDisplay("{DebuggerDisplay}")] [Serializable, StructLayout(LayoutKind.Sequential)] // , ValueSerializer(typeof(RectValueSerializer)), TypeConverter(typeof(RectConverter))] public struct XRect : IFormattable { /// <summary> /// Initializes a new instance of the XRect class. /// </summary> public XRect(double x, double y, double width, double height) { if (width < 0 || height < 0) throw new ArgumentException("WidthAndHeightCannotBeNegative"); //SR.Get(SRID.Size_WidthAndHeightCannotBeNegative, new object[0])); _x = x; _y = y; _width = width; _height = height; } /// <summary> /// Initializes a new instance of the XRect class. /// </summary> public XRect(XPoint point1, XPoint point2) { _x = Math.Min(point1.X, point2.X); _y = Math.Min(point1.Y, point2.Y); _width = Math.Max(Math.Max(point1.X, point2.X) - _x, 0); _height = Math.Max(Math.Max(point1.Y, point2.Y) - _y, 0); } /// <summary> /// Initializes a new instance of the XRect class. /// </summary> public XRect(XPoint point, XVector vector) : this(point, point + vector) { } /// <summary> /// Initializes a new instance of the XRect class. /// </summary> public XRect(XPoint location, XSize size) { if (size.IsEmpty) this = s_empty; else { _x = location.X; _y = location.Y; _width = size.Width; _height = size.Height; } } /// <summary> /// Initializes a new instance of the XRect class. /// </summary> public XRect(XSize size) { if (size.IsEmpty) this = s_empty; else { _x = _y = 0; _width = size.Width; _height = size.Height; } } #if GDI /// <summary> /// Initializes a new instance of the XRect class. /// </summary> public XRect(PointF location, SizeF size) { _x = location.X; _y = location.Y; _width = size.Width; _height = size.Height; } #endif #if GDI /// <summary> /// Initializes a new instance of the XRect class. /// </summary> public XRect(RectangleF rect) { _x = rect.X; _y = rect.Y; _width = rect.Width; _height = rect.Height; } #endif #if WPF || NETFX_CORE /// <summary> /// Initializes a new instance of the XRect class. /// </summary> public XRect(SysRect rect) { _x = rect.X; _y = rect.Y; _width = rect.Width; _height = rect.Height; } #endif /// <summary> /// Creates a rectangle from for straight lines. /// </summary> // ReSharper disable InconsistentNaming public static XRect FromLTRB(double left, double top, double right, double bottom) // ReSharper restore InconsistentNaming { return new XRect(left, top, right - left, bottom - top); } /// <summary> /// Determines whether the two rectangles are equal. /// </summary> public static bool operator ==(XRect rect1, XRect rect2) { // ReSharper disable CompareOfFloatsByEqualityOperator return rect1.X == rect2.X && rect1.Y == rect2.Y && rect1.Width == rect2.Width && rect1.Height == rect2.Height; // ReSharper restore CompareOfFloatsByEqualityOperator } /// <summary> /// Determines whether the two rectangles are not equal. /// </summary> public static bool operator !=(XRect rect1, XRect rect2) { return !(rect1 == rect2); } /// <summary> /// Determines whether the two rectangles are equal. /// </summary> public static bool Equals(XRect rect1, XRect rect2) { if (rect1.IsEmpty) return rect2.IsEmpty; return rect1.X.Equals(rect2.X) && rect1.Y.Equals(rect2.Y) && rect1.Width.Equals(rect2.Width) && rect1.Height.Equals(rect2.Height); } /// <summary> /// Determines whether this instance and the specified object are equal. /// </summary> public override bool Equals(object o) { if (!(o is XRect)) return false; return Equals(this, (XRect)o); } /// <summary> /// Determines whether this instance and the specified rect are equal. /// </summary> public bool Equals(XRect value) { return Equals(this, value); } /// <summary> /// Returns the hash code for this instance. /// </summary> public override int GetHashCode() { if (IsEmpty) return 0; return X.GetHashCode() ^ Y.GetHashCode() ^ Width.GetHashCode() ^ Height.GetHashCode(); } /// <summary> /// Parses the rectangle from a string. /// </summary> public static XRect Parse(string source) { XRect empty; CultureInfo cultureInfo = CultureInfo.InvariantCulture; TokenizerHelper helper = new TokenizerHelper(source, cultureInfo); string str = helper.NextTokenRequired(); if (str == "Empty") empty = Empty; else empty = new XRect(Convert.ToDouble(str, cultureInfo), Convert.ToDouble(helper.NextTokenRequired(), cultureInfo), Convert.ToDouble(helper.NextTokenRequired(), cultureInfo), Convert.ToDouble(helper.NextTokenRequired(), cultureInfo)); helper.LastTokenRequired(); return empty; } /// <summary> /// Converts this XRect to a human readable string. /// </summary> public override string ToString() { return ConvertToString(null, null); } /// <summary> /// Converts this XRect to a human readable string. /// </summary> public string ToString(IFormatProvider provider) { return ConvertToString(null, provider); } /// <summary> /// Converts this XRect to a human readable string. /// </summary> string IFormattable.ToString(string format, IFormatProvider provider) { return ConvertToString(format, provider); } internal string ConvertToString(string format, IFormatProvider provider) { if (IsEmpty) return "Empty"; char numericListSeparator = TokenizerHelper.GetNumericListSeparator(provider); provider = provider ?? CultureInfo.InvariantCulture; // ReSharper disable FormatStringProblem return string.Format(provider, "{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "}{0}{4:" + format + "}", new object[] { numericListSeparator, _x, _y, _width, _height }); // ReSharper restore FormatStringProblem } /// <summary> /// Gets the empty rectangle. /// </summary> public static XRect Empty { get { return s_empty; } } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> public bool IsEmpty { get { return _width < 0; } } /// <summary> /// Gets or sets the location of the rectangle. /// </summary> public XPoint Location { get { return new XPoint(_x, _y); } set { if (IsEmpty) throw new InvalidOperationException("CannotModifyEmptyRect"); //SR.Get(SRID.Rect_CannotModifyEmptyRect, new object[0])); _x = value.X; _y = value.Y; } } /// <summary> /// Gets or sets the size of the rectangle. /// </summary> //[Browsable(false)] public XSize Size { get { if (IsEmpty) return XSize.Empty; return new XSize(_width, _height); } set { if (value.IsEmpty) this = s_empty; else { if (IsEmpty) throw new InvalidOperationException("CannotModifyEmptyRect"); //SR.Get(SRID.Rect_CannotModifyEmptyRect, new object[0])); _width = value.Width; _height = value.Height; } } } /// <summary> /// Gets or sets the X value of the rectangle. /// </summary> public double X { get { return _x; } set { if (IsEmpty) throw new InvalidOperationException("CannotModifyEmptyRect"); //SR.Get(SRID.Rect_CannotModifyEmptyRect, new object[0])); _x = value; } } double _x; /// <summary> /// Gets or sets the Y value of the rectangle. /// </summary> public double Y { get { return _y; } set { if (IsEmpty) throw new InvalidOperationException("CannotModifyEmptyRect"); //SR.Get(SRID.Rect_CannotModifyEmptyRect, new object[0])); _y = value; } } double _y; /// <summary> /// Gets or sets the width of the rectangle. /// </summary> public double Width { get { return _width; } set { if (IsEmpty) throw new InvalidOperationException("CannotModifyEmptyRect"); //SR.Get(SRID.Rect_CannotModifyEmptyRect, new object[0])); if (value < 0) throw new ArgumentException("WidthCannotBeNegative"); //SR.Get(SRID.Size_WidthCannotBeNegative, new object[0])); _width = value; } } double _width; /// <summary> /// Gets or sets the height of the rectangle. /// </summary> public double Height { get { return _height; } set { if (IsEmpty) throw new InvalidOperationException("CannotModifyEmptyRect"); //SR.Get(SRID.Rect_CannotModifyEmptyRect, new object[0])); if (value < 0) throw new ArgumentException("WidthCannotBeNegative"); //SR.Get(SRID.Size_WidthCannotBeNegative, new object[0])); _height = value; } } double _height; /// <summary> /// Gets the x-axis value of the left side of the rectangle. /// </summary> public double Left { get { return _x; } } /// <summary> /// Gets the y-axis value of the top side of the rectangle. /// </summary> public double Top { get { return _y; } } /// <summary> /// Gets the x-axis value of the right side of the rectangle. /// </summary> public double Right { get { if (IsEmpty) return double.NegativeInfinity; return _x + _width; } } /// <summary> /// Gets the y-axis value of the bottom side of the rectangle. /// </summary> public double Bottom { get { if (IsEmpty) return double.NegativeInfinity; return _y + _height; } } /// <summary> /// Gets the position of the top-left corner of the rectangle. /// </summary> public XPoint TopLeft { get { return new XPoint(Left, Top); } } /// <summary> /// Gets the position of the top-right corner of the rectangle. /// </summary> public XPoint TopRight { get { return new XPoint(Right, Top); } } /// <summary> /// Gets the position of the bottom-left corner of the rectangle. /// </summary> public XPoint BottomLeft { get { return new XPoint(Left, Bottom); } } /// <summary> /// Gets the position of the bottom-right corner of the rectangle. /// </summary> public XPoint BottomRight { get { return new XPoint(Right, Bottom); } } /// <summary> /// Gets the center of the rectangle. /// </summary> //[Browsable(false)] public XPoint Center { get { return new XPoint(_x + _width / 2, _y + _height / 2); } } /// <summary> /// Indicates whether the rectangle contains the specified point. /// </summary> public bool Contains(XPoint point) { return Contains(point.X, point.Y); } /// <summary> /// Indicates whether the rectangle contains the specified point. /// </summary> public bool Contains(double x, double y) { if (IsEmpty) return false; return ContainsInternal(x, y); } /// <summary> /// Indicates whether the rectangle contains the specified rectangle. /// </summary> public bool Contains(XRect rect) { return !IsEmpty && !rect.IsEmpty && _x <= rect._x && _y <= rect._y && _x + _width >= rect._x + rect._width && _y + _height >= rect._y + rect._height; } /// <summary> /// Indicates whether the specified rectangle intersects with the current rectangle. /// </summary> public bool IntersectsWith(XRect rect) { return !IsEmpty && !rect.IsEmpty && rect.Left <= Right && rect.Right >= Left && rect.Top <= Bottom && rect.Bottom >= Top; } /// <summary> /// Sets current rectangle to the intersection of the current rectangle and the specified rectangle. /// </summary> public void Intersect(XRect rect) { if (!IntersectsWith(rect)) this = Empty; else { double left = Math.Max(Left, rect.Left); double top = Math.Max(Top, rect.Top); _width = Math.Max(Math.Min(Right, rect.Right) - left, 0.0); _height = Math.Max(Math.Min(Bottom, rect.Bottom) - top, 0.0); _x = left; _y = top; } } /// <summary> /// Returns the intersection of two rectangles. /// </summary> public static XRect Intersect(XRect rect1, XRect rect2) { rect1.Intersect(rect2); return rect1; } /// <summary> /// Sets current rectangle to the union of the current rectangle and the specified rectangle. /// </summary> public void Union(XRect rect) { // ReSharper disable CompareOfFloatsByEqualityOperator if (IsEmpty) this = rect; else if (!rect.IsEmpty) { double left = Math.Min(Left, rect.Left); double top = Math.Min(Top, rect.Top); if (rect.Width == Double.PositiveInfinity || Width == Double.PositiveInfinity) _width = Double.PositiveInfinity; else { double right = Math.Max(Right, rect.Right); _width = Math.Max(right - left, 0.0); } if (rect.Height == Double.PositiveInfinity || _height == Double.PositiveInfinity) _height = Double.PositiveInfinity; else { double bottom = Math.Max(Bottom, rect.Bottom); _height = Math.Max(bottom - top, 0.0); } _x = left; _y = top; } // ReSharper restore CompareOfFloatsByEqualityOperator } /// <summary> /// Returns the union of two rectangles. /// </summary> public static XRect Union(XRect rect1, XRect rect2) { rect1.Union(rect2); return rect1; } /// <summary> /// Sets current rectangle to the union of the current rectangle and the specified point. /// </summary> public void Union(XPoint point) { Union(new XRect(point, point)); } /// <summary> /// Returns the intersection of a rectangle and a point. /// </summary> public static XRect Union(XRect rect, XPoint point) { rect.Union(new XRect(point, point)); return rect; } /// <summary> /// Moves a rectangle by the specified amount. /// </summary> public void Offset(XVector offsetVector) { if (IsEmpty) throw new InvalidOperationException("CannotCallMethod"); //SR.Get(SRID.Rect_CannotCallMethod, new object[0])); _x += offsetVector.X; _y += offsetVector.Y; } /// <summary> /// Moves a rectangle by the specified amount. /// </summary> public void Offset(double offsetX, double offsetY) { if (IsEmpty) throw new InvalidOperationException("CannotCallMethod"); //SR.Get(SRID.Rect_CannotCallMethod, new object[0])); _x += offsetX; _y += offsetY; } /// <summary> /// Returns a rectangle that is offset from the specified rectangle by using the specified vector. /// </summary> public static XRect Offset(XRect rect, XVector offsetVector) { rect.Offset(offsetVector.X, offsetVector.Y); return rect; } /// <summary> /// Returns a rectangle that is offset from the specified rectangle by using specified horizontal and vertical amounts. /// </summary> public static XRect Offset(XRect rect, double offsetX, double offsetY) { rect.Offset(offsetX, offsetY); return rect; } /// <summary> /// Translates the rectangle by adding the specified point. /// </summary> //[Obsolete("Use Offset.")] public static XRect operator +(XRect rect, XPoint point) { return new XRect(rect._x + point.X, rect.Y + point.Y, rect._width, rect._height); } /// <summary> /// Translates the rectangle by subtracting the specified point. /// </summary> //[Obsolete("Use Offset.")] public static XRect operator -(XRect rect, XPoint point) { return new XRect(rect._x - point.X, rect.Y - point.Y, rect._width, rect._height); } /// <summary> /// Expands the rectangle by using the specified Size, in all directions. /// </summary> public void Inflate(XSize size) { Inflate(size.Width, size.Height); } /// <summary> /// Expands or shrinks the rectangle by using the specified width and height amounts, in all directions. /// </summary> public void Inflate(double width, double height) { if (IsEmpty) throw new InvalidOperationException("CannotCallMethod"); //SR.Get(SRID.Rect_CannotCallMethod, new object[0])); _x -= width; _y -= height; _width += width; _width += width; _height += height; _height += height; if (_width < 0 || _height < 0) this = s_empty; } /// <summary> /// Returns the rectangle that results from expanding the specified rectangle by the specified Size, in all directions. /// </summary> public static XRect Inflate(XRect rect, XSize size) { rect.Inflate(size.Width, size.Height); return rect; } /// <summary> /// Creates a rectangle that results from expanding or shrinking the specified rectangle by the specified width and height amounts, in all directions. /// </summary> public static XRect Inflate(XRect rect, double width, double height) { rect.Inflate(width, height); return rect; } /// <summary> /// Returns the rectangle that results from applying the specified matrix to the specified rectangle. /// </summary> public static XRect Transform(XRect rect, XMatrix matrix) { XMatrix.MatrixHelper.TransformRect(ref rect, ref matrix); return rect; } /// <summary> /// Transforms the rectangle by applying the specified matrix. /// </summary> public void Transform(XMatrix matrix) { XMatrix.MatrixHelper.TransformRect(ref this, ref matrix); } /// <summary> /// Multiplies the size of the current rectangle by the specified x and y values. /// </summary> public void Scale(double scaleX, double scaleY) { if (!IsEmpty) { _x *= scaleX; _y *= scaleY; _width *= scaleX; _height *= scaleY; if (scaleX < 0) { _x += _width; _width *= -1.0; } if (scaleY < 0) { _y += _height; _height *= -1.0; } } } #if CORE // Internal version in CORE build. #if UseGdiObjects /// <summary> /// Converts this instance to a System.Drawing.RectangleF. /// </summary> internal RectangleF ToRectangleF() { return new RectangleF((float)_x, (float)_y, (float)_width, (float)_height); } #endif #endif #if GDI /// <summary> /// Converts this instance to a System.Drawing.RectangleF. /// </summary> public RectangleF ToRectangleF() { return new RectangleF((float)_x, (float)_y, (float)_width, (float)_height); } #endif #if GDI /// <summary> /// Performs an implicit conversion from a System.Drawing.Rectangle to an XRect. /// </summary> public static implicit operator XRect(Rectangle rect) { return new XRect(rect.X, rect.Y, rect.Width, rect.Height); } /// <summary> /// Performs an implicit conversion from a System.Drawing.RectangleF to an XRect. /// </summary> public static implicit operator XRect(RectangleF rect) { return new XRect(rect.X, rect.Y, rect.Width, rect.Height); } #endif #if WPF || NETFX_CORE /// <summary> /// Performs an implicit conversion from System.Windows.Rect to XRect. /// </summary> public static implicit operator XRect(SysRect rect) { return new XRect(rect.X, rect.Y, rect.Width, rect.Height); } #endif bool ContainsInternal(double x, double y) { return x >= _x && x - _width <= _x && y >= _y && y - _height <= _y; } static XRect CreateEmptyRect() { XRect rect = new XRect(); rect._x = double.PositiveInfinity; rect._y = double.PositiveInfinity; rect._width = double.NegativeInfinity; rect._height = double.NegativeInfinity; return rect; } static XRect() { s_empty = CreateEmptyRect(); } private static readonly XRect s_empty; /// <summary> /// Gets the DebuggerDisplayAttribute text. /// </summary> /// <value>The debugger display.</value> // ReSharper disable UnusedMember.Local string DebuggerDisplay // ReSharper restore UnusedMember.Local { get { const string format = Config.SignificantFigures10; return String.Format(CultureInfo.InvariantCulture, "rect=({0:" + format + "}, {1:" + format + "}, {2:" + format + "}, {3:" + format + "})", _x, _y, _width, _height); } } } }
/* 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.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using CameraFlybyFromPath; using ESRI.ArcGIS.Analyst3D; using ESRI.ArcGIS.GlobeCore; using ESRI.ArcGIS.Animation; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Display; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Geodatabase; namespace cameraflybyfrompath { /// <summary> /// Summary description for frmCameraPath. /// </summary> public class frmCameraPath : System.Windows.Forms.Form { private System.Windows.Forms.GroupBox groupBox_PathSource; private System.Windows.Forms.RadioButton radiobutton_Sel_line_feat; private System.Windows.Forms.CheckBox checkBox_ReverseOrder; private System.Windows.Forms.Label label_VertOffset; private System.Windows.Forms.TextBox textBox_VertOffset; private System.Windows.Forms.Label label_Simp_Factor; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.GroupBox groupBox_PathDest; private System.Windows.Forms.RadioButton radioButton_flyby; private System.Windows.Forms.RadioButton radioButton_currentTarget; private System.Windows.Forms.RadioButton radioButton_currentObserver; private System.Windows.Forms.Label label_TrackName; private System.Windows.Forms.TextBox textBox_TrackName; private System.Windows.Forms.Button button_Import; private System.Windows.Forms.Button button_Cancel; private System.Windows.Forms.GroupBox groupBox_TrackProps; private System.Windows.Forms.CheckBox checkBox_Overwrite; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private System.Windows.Forms.TrackBar trackBarSimplificationFactor; private System.Windows.Forms.ComboBox comboBoxLayers; private IGlobe globe; private IArray layerArray = new ArrayClass(); public frmCameraPath() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <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 Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.groupBox_PathSource = new System.Windows.Forms.GroupBox(); this.comboBoxLayers = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label_Simp_Factor = new System.Windows.Forms.Label(); this.textBox_VertOffset = new System.Windows.Forms.TextBox(); this.label_VertOffset = new System.Windows.Forms.Label(); this.checkBox_ReverseOrder = new System.Windows.Forms.CheckBox(); this.radiobutton_Sel_line_feat = new System.Windows.Forms.RadioButton(); this.trackBarSimplificationFactor = new System.Windows.Forms.TrackBar(); this.groupBox_PathDest = new System.Windows.Forms.GroupBox(); this.radioButton_currentObserver = new System.Windows.Forms.RadioButton(); this.radioButton_currentTarget = new System.Windows.Forms.RadioButton(); this.radioButton_flyby = new System.Windows.Forms.RadioButton(); this.label_TrackName = new System.Windows.Forms.Label(); this.textBox_TrackName = new System.Windows.Forms.TextBox(); this.button_Import = new System.Windows.Forms.Button(); this.button_Cancel = new System.Windows.Forms.Button(); this.checkBox_Overwrite = new System.Windows.Forms.CheckBox(); this.groupBox_TrackProps = new System.Windows.Forms.GroupBox(); this.groupBox_PathSource.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.trackBarSimplificationFactor)).BeginInit(); this.groupBox_PathDest.SuspendLayout(); this.groupBox_TrackProps.SuspendLayout(); this.SuspendLayout(); // // groupBox_PathSource // this.groupBox_PathSource.Controls.Add(this.comboBoxLayers); this.groupBox_PathSource.Controls.Add(this.label1); this.groupBox_PathSource.Controls.Add(this.label2); this.groupBox_PathSource.Controls.Add(this.label_Simp_Factor); this.groupBox_PathSource.Controls.Add(this.textBox_VertOffset); this.groupBox_PathSource.Controls.Add(this.label_VertOffset); this.groupBox_PathSource.Controls.Add(this.checkBox_ReverseOrder); this.groupBox_PathSource.Controls.Add(this.radiobutton_Sel_line_feat); this.groupBox_PathSource.Controls.Add(this.trackBarSimplificationFactor); this.groupBox_PathSource.Location = new System.Drawing.Point(8, 8); this.groupBox_PathSource.Name = "groupBox_PathSource"; this.groupBox_PathSource.Size = new System.Drawing.Size(296, 160); this.groupBox_PathSource.TabIndex = 0; this.groupBox_PathSource.TabStop = false; this.groupBox_PathSource.Text = "Path source"; // // comboBoxLayers // this.comboBoxLayers.Location = new System.Drawing.Point(152, 24); this.comboBoxLayers.Name = "comboBoxLayers"; this.comboBoxLayers.Size = new System.Drawing.Size(136, 21); this.comboBoxLayers.TabIndex = 8; // // label1 // this.label1.Location = new System.Drawing.Point(258, 137); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(30, 16); this.label1.TabIndex = 6; this.label1.Text = "High"; // // label2 // this.label2.Location = new System.Drawing.Point(117, 137); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(32, 16); this.label2.TabIndex = 7; this.label2.Text = "Low"; // // label_Simp_Factor // this.label_Simp_Factor.Location = new System.Drawing.Point(16, 112); this.label_Simp_Factor.Name = "label_Simp_Factor"; this.label_Simp_Factor.Size = new System.Drawing.Size(104, 24); this.label_Simp_Factor.TabIndex = 5; this.label_Simp_Factor.Text = "Simplification factor"; // // textBox_VertOffset // this.textBox_VertOffset.Location = new System.Drawing.Point(88, 72); this.textBox_VertOffset.Name = "textBox_VertOffset"; this.textBox_VertOffset.Size = new System.Drawing.Size(56, 20); this.textBox_VertOffset.TabIndex = 3; this.textBox_VertOffset.Text = "0.0"; this.textBox_VertOffset.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // label_VertOffset // this.label_VertOffset.Location = new System.Drawing.Point(16, 80); this.label_VertOffset.Name = "label_VertOffset"; this.label_VertOffset.Size = new System.Drawing.Size(88, 16); this.label_VertOffset.TabIndex = 2; this.label_VertOffset.Text = "Vertical offset"; // // checkBox_ReverseOrder // this.checkBox_ReverseOrder.Location = new System.Drawing.Point(16, 48); this.checkBox_ReverseOrder.Name = "checkBox_ReverseOrder"; this.checkBox_ReverseOrder.Size = new System.Drawing.Size(144, 24); this.checkBox_ReverseOrder.TabIndex = 1; this.checkBox_ReverseOrder.Text = "Apply in reverse order"; // // radiobutton_Sel_line_feat // this.radiobutton_Sel_line_feat.Checked = true; this.radiobutton_Sel_line_feat.Location = new System.Drawing.Point(16, 24); this.radiobutton_Sel_line_feat.Name = "radiobutton_Sel_line_feat"; this.radiobutton_Sel_line_feat.Size = new System.Drawing.Size(144, 24); this.radiobutton_Sel_line_feat.TabIndex = 0; this.radiobutton_Sel_line_feat.TabStop = true; this.radiobutton_Sel_line_feat.Text = "Selected line feature in"; // // trackBarSimplificationFactor // this.trackBarSimplificationFactor.Cursor = System.Windows.Forms.Cursors.Hand; this.trackBarSimplificationFactor.Location = new System.Drawing.Point(120, 108); this.trackBarSimplificationFactor.Maximum = 100; this.trackBarSimplificationFactor.Name = "trackBarSimplificationFactor"; this.trackBarSimplificationFactor.Size = new System.Drawing.Size(168, 45); this.trackBarSimplificationFactor.TabIndex = 4; this.trackBarSimplificationFactor.Value = 5; // // groupBox_PathDest // this.groupBox_PathDest.Controls.Add(this.radioButton_currentObserver); this.groupBox_PathDest.Controls.Add(this.radioButton_currentTarget); this.groupBox_PathDest.Controls.Add(this.radioButton_flyby); this.groupBox_PathDest.Location = new System.Drawing.Point(8, 176); this.groupBox_PathDest.Name = "groupBox_PathDest"; this.groupBox_PathDest.Size = new System.Drawing.Size(296, 104); this.groupBox_PathDest.TabIndex = 1; this.groupBox_PathDest.TabStop = false; this.groupBox_PathDest.Text = "Path destination"; // // radioButton_currentObserver // this.radioButton_currentObserver.Location = new System.Drawing.Point(16, 72); this.radioButton_currentObserver.Name = "radioButton_currentObserver"; this.radioButton_currentObserver.Size = new System.Drawing.Size(272, 16); this.radioButton_currentObserver.TabIndex = 2; this.radioButton_currentObserver.Text = "Move target along path with current observer"; // // radioButton_currentTarget // this.radioButton_currentTarget.Location = new System.Drawing.Point(16, 48); this.radioButton_currentTarget.Name = "radioButton_currentTarget"; this.radioButton_currentTarget.Size = new System.Drawing.Size(272, 16); this.radioButton_currentTarget.TabIndex = 1; this.radioButton_currentTarget.Text = "Move observer along path with current target"; // // radioButton_flyby // this.radioButton_flyby.Checked = true; this.radioButton_flyby.Location = new System.Drawing.Point(16, 24); this.radioButton_flyby.Name = "radioButton_flyby"; this.radioButton_flyby.Size = new System.Drawing.Size(272, 16); this.radioButton_flyby.TabIndex = 0; this.radioButton_flyby.TabStop = true; this.radioButton_flyby.Text = "Move both observer and target along path (fly by)"; // // label_TrackName // this.label_TrackName.Location = new System.Drawing.Point(16, 24); this.label_TrackName.Name = "label_TrackName"; this.label_TrackName.Size = new System.Drawing.Size(88, 16); this.label_TrackName.TabIndex = 2; this.label_TrackName.Text = "Track name:"; // // textBox_TrackName // this.textBox_TrackName.Location = new System.Drawing.Point(96, 23); this.textBox_TrackName.Name = "textBox_TrackName"; this.textBox_TrackName.Size = new System.Drawing.Size(192, 20); this.textBox_TrackName.TabIndex = 3; this.textBox_TrackName.Text = "Track from path"; // // button_Import // this.button_Import.Location = new System.Drawing.Point(144, 368); this.button_Import.Name = "button_Import"; this.button_Import.Size = new System.Drawing.Size(80, 24); this.button_Import.TabIndex = 4; this.button_Import.Text = "Import"; this.button_Import.Click += new System.EventHandler(this.button_Import_Click); // // button_Cancel // this.button_Cancel.Location = new System.Drawing.Point(232, 368); this.button_Cancel.Name = "button_Cancel"; this.button_Cancel.Size = new System.Drawing.Size(72, 24); this.button_Cancel.TabIndex = 5; this.button_Cancel.Text = "Cancel"; this.button_Cancel.Click += new System.EventHandler(this.button_Cancel_Click); // // checkBox_Overwrite // this.checkBox_Overwrite.Checked = true; this.checkBox_Overwrite.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox_Overwrite.Enabled = false; this.checkBox_Overwrite.Location = new System.Drawing.Point(16, 48); this.checkBox_Overwrite.Name = "checkBox_Overwrite"; this.checkBox_Overwrite.Size = new System.Drawing.Size(184, 16); this.checkBox_Overwrite.TabIndex = 7; this.checkBox_Overwrite.Text = "Overwrite last imported track"; // // groupBox_TrackProps // this.groupBox_TrackProps.Controls.Add(this.textBox_TrackName); this.groupBox_TrackProps.Controls.Add(this.label_TrackName); this.groupBox_TrackProps.Controls.Add(this.checkBox_Overwrite); this.groupBox_TrackProps.Location = new System.Drawing.Point(8, 288); this.groupBox_TrackProps.Name = "groupBox_TrackProps"; this.groupBox_TrackProps.Size = new System.Drawing.Size(296, 72); this.groupBox_TrackProps.TabIndex = 8; this.groupBox_TrackProps.TabStop = false; this.groupBox_TrackProps.Text = "Animation track properties"; // // frmCameraPath // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(312, 398); this.Controls.Add(this.groupBox_TrackProps); this.Controls.Add(this.button_Cancel); this.Controls.Add(this.button_Import); this.Controls.Add(this.groupBox_PathDest); this.Controls.Add(this.groupBox_PathSource); this.Name = "frmCameraPath"; this.Text = "Camera flyby from path"; this.Load += new System.EventHandler(this.frmCameraPath_Load); this.groupBox_PathSource.ResumeLayout(false); this.groupBox_PathSource.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.trackBarSimplificationFactor)).EndInit(); this.groupBox_PathDest.ResumeLayout(false); this.groupBox_TrackProps.ResumeLayout(false); this.groupBox_TrackProps.PerformLayout(); this.ResumeLayout(false); } #endregion private void frmCameraPath_Load(object sender, System.EventArgs e) { IScene scene = globe.GlobeDisplay.Scene; //check IEnumLayer enumFtrLayers = scene.get_Layers(null, true); enumFtrLayers.Reset(); ILayer lyr = null; IFeatureLayer fLayer = null; lyr = enumFtrLayers.Next(); do { if (lyr is IFeatureLayer) { fLayer = lyr as IFeatureLayer; break; } lyr = enumFtrLayers.Next(); } while (lyr != null); if (fLayer != null) { UID uid = new UIDClass(); uid.Value = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}"; IEnumLayer enumLayers = scene.get_Layers(uid, true); enumLayers.Reset(); fLayer = (IFeatureLayer)enumLayers.Next(); while (fLayer != null) { if (fLayer.FeatureClass.ShapeType.ToString() == esriGeometryType.esriGeometryPolyline.ToString() || fLayer.FeatureClass.ShapeType.ToString() == esriGeometryType.esriGeometryLine.ToString()) { comboBoxLayers.Items.Add(fLayer.Name); } layerArray.Add(fLayer); fLayer = (IFeatureLayer)enumLayers.Next(); } } else { MessageBox.Show("You don't have any line feature layers in your document"); } } private void button_Cancel_Click(object sender, System.EventArgs e) { this.Close(); } private void button_Import_Click(object sender, System.EventArgs e) { // point to the first selected feature: ESRI.ArcGIS.Animation.IAGImportPathOptions AGImportPathOptionsCls = new ESRI.ArcGIS.Animation.AGImportPathOptionsClass(); // Set properties for AGImportPathOptions AGImportPathOptionsCls.BasicMap = (ESRI.ArcGIS.Carto.IBasicMap)globe; // Explicit Cast AGImportPathOptionsCls.AnimationTracks = (ESRI.ArcGIS.Animation.IAGAnimationTracks)globe; // Explicit Cast AGImportPathOptionsCls.AnimationType = new ESRI.ArcGIS.GlobeCore.AnimationTypeGlobeCameraClass(); AGImportPathOptionsCls.AnimatedObject = globe.GlobeDisplay.ActiveViewer.Camera; if (this.radioButton_flyby.Checked == true) { AGImportPathOptionsCls.ConversionType = esriFlyFromPathType.esriFlyFromPathObsAndTarget; AGImportPathOptionsCls.PutAngleCalculationMethods(esriPathAngleCalculation.esriAngleAddRelative, esriPathAngleCalculation.esriAngleAddRelative, esriPathAngleCalculation.esriAngleAddRelative); AGImportPathOptionsCls.PutAngleCalculationValues(0.0, 0.0, 0.0); } else if (this.radioButton_currentTarget.Checked == true) { AGImportPathOptionsCls.ConversionType = esriFlyFromPathType.esriFlyFromPathObserver; } else if (this.radioButton_currentObserver.Checked == true) { AGImportPathOptionsCls.ConversionType = esriFlyFromPathType.esriFlyFromPathTarget; } double pAzimuth, pInclination, pRollVal; AGImportPathOptionsCls.GetAngleCalculationValues(out pAzimuth, out pInclination, out pRollVal); AGImportPathOptionsCls.LookaheadFactor = this.trackBarSimplificationFactor.Value/100; AGImportPathOptionsCls.TrackName = this.textBox_TrackName.Text; AGImportPathOptionsCls.OverwriteExisting = Convert.ToBoolean(this.checkBox_Overwrite.CheckState); AGImportPathOptionsCls.VerticalOffset = Convert.ToDouble(this.textBox_VertOffset.Text); AGImportPathOptionsCls.ReversePath = Convert.ToBoolean(this.checkBox_ReverseOrder.CheckState); // get the layer selected in the combo box if (this.comboBoxLayers.SelectedIndex == -1) { MessageBox.Show("Please select a layer before you proceed"); } else { //set the layer based on the item selected in the combo box ESRI.ArcGIS.Carto.ILayer layer = (ESRI.ArcGIS.Carto.ILayer) layerArray.get_Element(this.comboBoxLayers.SelectedIndex); // Explicit Cast // Get the line feature selected in the layer ESRI.ArcGIS.Carto.IFeatureLayer featureLayer = (ESRI.ArcGIS.Carto.IFeatureLayer)layer; // Explicit Cast ESRI.ArcGIS.Carto.IFeatureSelection featureSelection = (ESRI.ArcGIS.Carto.IFeatureSelection)layer; // Explicit Cast ESRI.ArcGIS.Geodatabase.ISelectionSet selectionSet = featureSelection.SelectionSet; ESRI.ArcGIS.Geodatabase.IFeatureClass featureClass = featureLayer.FeatureClass; string shapeField = featureClass.ShapeFieldName; ESRI.ArcGIS.Geodatabase.ISpatialFilter spatialFilterCls = new ESRI.ArcGIS.Geodatabase.SpatialFilterClass(); IScene scene = globe.GlobeDisplay.Scene; ESRI.ArcGIS.Geometry.ISpatialReference spatialReference = scene.SpatialReference; spatialFilterCls.GeometryField = shapeField; spatialFilterCls.set_OutputSpatialReference(shapeField, spatialReference); ESRI.ArcGIS.Geodatabase.ICursor cursor; selectionSet.Search(spatialFilterCls, true, out cursor); ESRI.ArcGIS.Geodatabase.IFeatureCursor featureCursor = (ESRI.ArcGIS.Geodatabase.IFeatureCursor)cursor; // Explicit Cast ESRI.ArcGIS.Geodatabase.IFeature lineFeature; lineFeature = featureCursor.NextFeature(); if (lineFeature == null) { MessageBox.Show("Please select a feature in the feature layer selected"); } else { CreateFlybyFromPathAnimation(globe, lineFeature, AGImportPathOptionsCls); } } this.Close(); } public void SetVariables(IGlobe pGlobe) { globe = pGlobe; } private void CreateFlybyFromPathAnimation(ESRI.ArcGIS.GlobeCore.IGlobe globe, ESRI.ArcGIS.Geodatabase.IFeature lineFeature, ESRI.ArcGIS.Animation.IAGImportPathOptions AGImportPathOptionsCls) { ESRI.ArcGIS.GlobeCore.IGlobeDisplay globeDisplay = globe.GlobeDisplay; ESRI.ArcGIS.Analyst3D.IScene scene = globeDisplay.Scene; // Get a handle to the animation extension ESRI.ArcGIS.Analyst3D.IBasicScene2 basicScene2 = (ESRI.ArcGIS.Analyst3D.IBasicScene2)scene; // Explicit Cast ESRI.ArcGIS.Animation.IAnimationExtension animationExtension = basicScene2.AnimationExtension; // Get the geometry of the line feature ESRI.ArcGIS.Geometry.IGeometry geometry = lineFeature.Shape; // Create AGAnimationUtils and AGImportPathOptions objects ESRI.ArcGIS.Animation.IAGAnimationUtils AGAnimationUtilsCls = new ESRI.ArcGIS.Animation.AGAnimationUtilsClass(); AGImportPathOptionsCls.PathGeometry = geometry; AGImportPathOptionsCls.AnimationEnvironment = animationExtension.AnimationEnvironment; ESRI.ArcGIS.Animation.IAGAnimationContainer AGAnimationContainer = animationExtension.AnimationTracks.AnimationObjectContainer; // Call "CreateFlybyFromPath" method AGAnimationUtilsCls.CreateFlybyFromPath(AGAnimationContainer, AGImportPathOptionsCls); } } }
// --------------------------------------------------------------------------- // <copyright file="ServiceObjectInfo.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- //----------------------------------------------------------------------- // <summary>Defines the ServiceObjectInfo class.</summary> //----------------------------------------------------------------------- namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; internal delegate object CreateServiceObjectWithServiceParam(ExchangeService srv); internal delegate object CreateServiceObjectWithAttachmentParam(ItemAttachment itemAttachment, bool isNew); /// <summary> /// ServiceObjectInfo contains metadata on how to map from an element name to a ServiceObject type /// as well as how to map from a ServiceObject type to appropriate constructors. /// </summary> internal class ServiceObjectInfo { private Dictionary<string, Type> xmlElementNameToServiceObjectClassMap; private Dictionary<Type, CreateServiceObjectWithServiceParam> serviceObjectConstructorsWithServiceParam; private Dictionary<Type, CreateServiceObjectWithAttachmentParam> serviceObjectConstructorsWithAttachmentParam; /// <summary> /// Default constructor /// </summary> internal ServiceObjectInfo() { this.xmlElementNameToServiceObjectClassMap = new Dictionary<string, Type>(); this.serviceObjectConstructorsWithServiceParam = new Dictionary<Type, CreateServiceObjectWithServiceParam>(); this.serviceObjectConstructorsWithAttachmentParam = new Dictionary<Type, CreateServiceObjectWithAttachmentParam>(); this.InitializeServiceObjectClassMap(); } /// <summary> /// Initializes the service object class map. /// </summary> /// <remarks> /// If you add a new ServiceObject subclass that can be returned by the Server, add the type /// to the class map as well as associated delegate(s) to call the constructor(s). /// </remarks> private void InitializeServiceObjectClassMap() { // Appointment this.AddServiceObjectType( XmlElementNames.CalendarItem, typeof(Appointment), delegate(ExchangeService srv) { return new Appointment(srv); }, delegate(ItemAttachment itemAttachment, bool isNew) { return new Appointment(itemAttachment, isNew); }); // CalendarFolder this.AddServiceObjectType( XmlElementNames.CalendarFolder, typeof(CalendarFolder), delegate(ExchangeService srv) { return new CalendarFolder(srv); }, null); // Contact this.AddServiceObjectType( XmlElementNames.Contact, typeof(Contact), delegate(ExchangeService srv) { return new Contact(srv); }, delegate(ItemAttachment itemAttachment, bool isNew) { return new Contact(itemAttachment); }); // ContactsFolder this.AddServiceObjectType( XmlElementNames.ContactsFolder, typeof(ContactsFolder), delegate(ExchangeService srv) { return new ContactsFolder(srv); }, null); // ContactGroup this.AddServiceObjectType( XmlElementNames.DistributionList, typeof(ContactGroup), delegate(ExchangeService srv) { return new ContactGroup(srv); }, delegate(ItemAttachment itemAttachment, bool isNew) { return new ContactGroup(itemAttachment); }); // Conversation this.AddServiceObjectType( XmlElementNames.Conversation, typeof(Conversation), delegate(ExchangeService srv) { return new Conversation(srv); }, null); // EmailMessage this.AddServiceObjectType( XmlElementNames.Message, typeof(EmailMessage), delegate(ExchangeService srv) { return new EmailMessage(srv); }, delegate(ItemAttachment itemAttachment, bool isNew) { return new EmailMessage(itemAttachment); }); // Folder this.AddServiceObjectType( XmlElementNames.Folder, typeof(Folder), delegate(ExchangeService srv) { return new Folder(srv); }, null); // Item this.AddServiceObjectType( XmlElementNames.Item, typeof(Item), delegate(ExchangeService srv) { return new Item(srv); }, delegate(ItemAttachment itemAttachment, bool isNew) { return new Item(itemAttachment); }); // MeetingCancellation this.AddServiceObjectType( XmlElementNames.MeetingCancellation, typeof(MeetingCancellation), delegate(ExchangeService srv) { return new MeetingCancellation(srv); }, delegate(ItemAttachment itemAttachment, bool isNew) { return new MeetingCancellation(itemAttachment); }); // MeetingMessage this.AddServiceObjectType( XmlElementNames.MeetingMessage, typeof(MeetingMessage), delegate(ExchangeService srv) { return new MeetingMessage(srv); }, delegate(ItemAttachment itemAttachment, bool isNew) { return new MeetingMessage(itemAttachment); }); // MeetingRequest this.AddServiceObjectType( XmlElementNames.MeetingRequest, typeof(MeetingRequest), delegate(ExchangeService srv) { return new MeetingRequest(srv); }, delegate(ItemAttachment itemAttachment, bool isNew) { return new MeetingRequest(itemAttachment); }); // MeetingResponse this.AddServiceObjectType( XmlElementNames.MeetingResponse, typeof(MeetingResponse), delegate(ExchangeService srv) { return new MeetingResponse(srv); }, delegate(ItemAttachment itemAttachment, bool isNew) { return new MeetingResponse(itemAttachment); }); // Persona this.AddServiceObjectType( XmlElementNames.Persona, typeof(Persona), delegate(ExchangeService srv) { return new Persona(srv); }, null); // PostItem this.AddServiceObjectType( XmlElementNames.PostItem, typeof(PostItem), delegate(ExchangeService srv) { return new PostItem(srv); }, delegate(ItemAttachment itemAttachment, bool isNew) { return new PostItem(itemAttachment); }); // SearchFolder this.AddServiceObjectType( XmlElementNames.SearchFolder, typeof(SearchFolder), delegate(ExchangeService srv) { return new SearchFolder(srv); }, null); // Task this.AddServiceObjectType( XmlElementNames.Task, typeof(Task), delegate(ExchangeService srv) { return new Task(srv); }, delegate(ItemAttachment itemAttachment, bool isNew) { return new Task(itemAttachment); }); // TasksFolder this.AddServiceObjectType( XmlElementNames.TasksFolder, typeof(TasksFolder), delegate(ExchangeService srv) { return new TasksFolder(srv); }, null); } /// <summary> /// Adds specified type of service object to map. /// </summary> /// <param name="xmlElementName">Name of the XML element.</param> /// <param name="type">The ServiceObject type.</param> /// <param name="createServiceObjectWithServiceParam">Delegate to create service object with service param.</param> /// <param name="createServiceObjectWithAttachmentParam">Delegate to create service object with attachment param.</param> private void AddServiceObjectType( string xmlElementName, Type type, CreateServiceObjectWithServiceParam createServiceObjectWithServiceParam, CreateServiceObjectWithAttachmentParam createServiceObjectWithAttachmentParam) { this.xmlElementNameToServiceObjectClassMap.Add(xmlElementName, type); this.serviceObjectConstructorsWithServiceParam.Add(type, createServiceObjectWithServiceParam); if (createServiceObjectWithAttachmentParam != null) { this.serviceObjectConstructorsWithAttachmentParam.Add(type, createServiceObjectWithAttachmentParam); } } /// <summary> /// Return Dictionary that maps from element name to ServiceObject Type. /// </summary> internal Dictionary<string, Type> XmlElementNameToServiceObjectClassMap { get { return this.xmlElementNameToServiceObjectClassMap; } } /// <summary> /// Return Dictionary that maps from ServiceObject Type to CreateServiceObjectWithServiceParam delegate with ExchangeService parameter. /// </summary> internal Dictionary<Type, CreateServiceObjectWithServiceParam> ServiceObjectConstructorsWithServiceParam { get { return this.serviceObjectConstructorsWithServiceParam; } } /// <summary> /// Return Dictionary that maps from ServiceObject Type to CreateServiceObjectWithAttachmentParam delegate with ItemAttachment parameter. /// </summary> internal Dictionary<Type, CreateServiceObjectWithAttachmentParam> ServiceObjectConstructorsWithAttachmentParam { get { return this.serviceObjectConstructorsWithAttachmentParam; } } } }
using System.Runtime.InteropServices; using size_t = System.UInt32; using cl_float = System.Single; using cl_double= System.Double; using cl_uint = System.UInt32; using cl_mem = System.IntPtr; using cl_event = System.IntPtr; using cl_command_queue = System.IntPtr; namespace CLMathLibraries.CLBLAS { public static class CLBLAS { private const string PathToDll = "clBLAS"; #region Init [DllImport(PathToDll, CharSet = CharSet.Ansi, EntryPoint = "clblasSetup")] public static extern CLBLASStatus Setup(); [DllImport(PathToDll, CharSet = CharSet.Ansi, EntryPoint = "clblasTeardown")] public static extern void Teardown(); [DllImport(PathToDll, CharSet = CharSet.Ansi, EntryPoint = "clblasGetVersion")] public static extern CLBLASStatus GetVersion(out size_t major, out size_t minor, out size_t patch); #endregion #region Level 3 General Matrix-Matrix multiplication /** * @brief Matrix-matrix product of general rectangular matrices with float * elements. Extended version. * * Matrix-matrix products: * - \f$ C \leftarrow \alpha A B + \beta C \f$ * - \f$ C \leftarrow \alpha A^T B + \beta C \f$ * - \f$ C \leftarrow \alpha A B^T + \beta C \f$ * - \f$ C \leftarrow \alpha A^T B^T + \beta C \f$ * * @param[in] order Row/column order. * @param[in] transA How matrix \b A is to be transposed. * @param[in] transB How matrix \b B is to be transposed. * @param[in] M Number of rows in matrix \b A. * @param[in] N Number of columns in matrix \b B. * @param[in] K Number of columns in matrix \b A and rows in matrix \b B. * @param[in] alpha The factor of matrix \b A. * @param[in] A Buffer object storing matrix \b A. * @param[in] offA Offset of the first element of the matrix \b A in the * buffer object. Counted in elements. * @param[in] lda Leading dimension of matrix \b A. It cannot be less * than \b K when the \b order parameter is set to * \b clblasRowMajor,\n or less than \b M when the * parameter is set to \b clblasColumnMajor. * @param[in] B Buffer object storing matrix \b B. * @param[in] offB Offset of the first element of the matrix \b B in the * buffer object. Counted in elements. * @param[in] ldb Leading dimension of matrix \b B. It cannot be less * than \b N when the \b order parameter is set to * \b clblasRowMajor,\n or less than \b K * when it is set to \b clblasColumnMajor. * @param[in] beta The factor of matrix \b C. * @param[out] C Buffer object storing matrix \b C. * @param[in] offC Offset of the first element of the matrix \b C in the * buffer object. Counted in elements. * @param[in] ldc Leading dimension of matrix \b C. It cannot be less * than \b N when the \b order parameter is set to * \b clblasRowMajor,\n or less than \b M when * it is set to \b clblasColumnMajorOrder. * @param[in] numCommandQueues Number of OpenCL command queues in which the * task is to be performed. * @param[in] commandQueues OpenCL command queues. * @param[in] numEventsInWaitList Number of events in the event wait list. * @param[in] eventWaitList Event wait list. * @param[in] events Event objects per each command queue that identify * a particular kernel execution instance. * * @return * - \b clblasSuccess on success; * - \b clblasInvalidValue if either \b offA, \b offB or \b offC exceeds * the size of the respective buffer object; * - the same error codes as clblasSgemm() otherwise. * * @ingroup GEMM */ [DllImport(PathToDll, CharSet = CharSet.Ansi, EntryPoint = "clblasSgemm")] public static extern CLBLASStatus Sgemm( CLBLASOrder order, CLBLASTranspose transA, CLBLASTranspose transB, size_t m, size_t n, size_t k, cl_float alpha, cl_mem a, // const cl_mem size_t offA, size_t lda, cl_mem b, // const cl_mem size_t offB, size_t ldb, cl_float beta, cl_mem c, size_t offC, size_t ldc, cl_uint numCommandQueues, [MarshalAs(UnmanagedType.LPArray)] cl_command_queue[] commandQueues, cl_uint numEventsInWaitList, [MarshalAs(UnmanagedType.LPArray)] cl_event[] eventWaitList, [Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] cl_event[] events); /** * @example example_sgemm.c * This is an example of how to use the @ref clblasSgemmEx function. */ /** * @brief Matrix-matrix product of general rectangular matrices with double * elements. Extended version. * * Matrix-matrix products: * - \f$ C \leftarrow \alpha A B + \beta C \f$ * - \f$ C \leftarrow \alpha A^T B + \beta C \f$ * - \f$ C \leftarrow \alpha A B^T + \beta C \f$ * - \f$ C \leftarrow \alpha A^T B^T + \beta C \f$ * * @param[in] order Row/column order. * @param[in] transA How matrix \b A is to be transposed. * @param[in] transB How matrix \b B is to be transposed. * @param[in] M Number of rows in matrix \b A. * @param[in] N Number of columns in matrix \b B. * @param[in] K Number of columns in matrix \b A and rows in matrix \b B. * @param[in] alpha The factor of matrix \b A. * @param[in] A Buffer object storing matrix \b A. * @param[in] offA Offset of the first element of the matrix \b A in the * buffer object. Counted in elements. * @param[in] lda Leading dimension of matrix \b A. For detailed description, * see clblasSgemm(). * @param[in] B Buffer object storing matrix \b B. * @param[in] offB Offset of the first element of the matrix \b B in the * buffer object. Counted in elements. * @param[in] ldb Leading dimension of matrix \b B. For detailed description, * see clblasSgemm(). * @param[in] beta The factor of matrix \b C. * @param[out] C Buffer object storing matrix \b C. * @param[in] offC Offset of the first element of the matrix \b C in the * buffer object. Counted in elements. * @param[in] ldc Leading dimension of matrix \b C. For detailed description, * see clblasSgemm(). * @param[in] numCommandQueues Number of OpenCL command queues in which the * task is to be performed. * @param[in] commandQueues OpenCL command queues. * @param[in] numEventsInWaitList Number of events in the event wait list. * @param[in] eventWaitList Event wait list. * @param[in] events Event objects per each command queue that identify * a particular kernel execution instance. * * @return * - \b clblasSuccess on success; * - \b clblasInvalidDevice if a target device does not support floating * point arithmetic with double precision; * - \b clblasInvalidValue if either \b offA, \b offB or offC exceeds * the size of the respective buffer object; * - the same error codes as the clblasSgemm() function otherwise. * * @ingroup GEMM */ [DllImport(PathToDll, CharSet = CharSet.Ansi, EntryPoint = "clblasDgemm")] public static extern CLBLASStatus Dgemm( CLBLASOrder order, CLBLASTranspose transA, CLBLASTranspose transB, size_t m, size_t n, size_t k, cl_double alpha, cl_mem a, // const cl_mem size_t offA, size_t lda, cl_mem b, // const cl_mem size_t offB, size_t ldb, cl_double beta, cl_mem c, size_t offC, size_t ldc, cl_uint numCommandQueues, [MarshalAs(UnmanagedType.LPArray)] cl_command_queue[] commandQueues, cl_uint numEventsInWaitList, [MarshalAs(UnmanagedType.LPArray)] cl_event[] eventWaitList, [Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] cl_event[] events); /** * @brief Matrix-matrix product of general rectangular matrices with float * complex elements. Extended version. * * Matrix-matrix products: * - \f$ C \leftarrow \alpha A B + \beta C \f$ * - \f$ C \leftarrow \alpha A^T B + \beta C \f$ * - \f$ C \leftarrow \alpha A B^T + \beta C \f$ * - \f$ C \leftarrow \alpha A^T B^T + \beta C \f$ * * @param[in] order Row/column order. * @param[in] transA How matrix \b A is to be transposed. * @param[in] transB How matrix \b B is to be transposed. * @param[in] M Number of rows in matrix \b A. * @param[in] N Number of columns in matrix \b B. * @param[in] K Number of columns in matrix \b A and rows in matrix \b B. * @param[in] alpha The factor of matrix \b A. * @param[in] A Buffer object storing matrix \b A. * @param[in] offA Offset of the first element of the matrix \b A in the * buffer object. Counted in elements. * @param[in] lda Leading dimension of matrix \b A. For detailed description, * see clblasSgemm(). * @param[in] B Buffer object storing matrix \b B. * @param[in] offB Offset of the first element of the matrix \b B in the * buffer object. Counted in elements. * @param[in] ldb Leading dimension of matrix \b B. For detailed description, * see clblasSgemm(). * @param[in] beta The factor of matrix \b C. * @param[out] C Buffer object storing matrix \b C. * @param[in] offC Offset of the first element of the matrix \b C in the * buffer object. Counted in elements. * @param[in] ldc Leading dimension of matrix \b C. For detailed description, * see clblasSgemm(). * @param[in] numCommandQueues Number of OpenCL command queues in which the * task is to be performed. * @param[in] commandQueues OpenCL command queues. * @param[in] numEventsInWaitList Number of events in the event wait list. * @param[in] eventWaitList Event wait list. * @param[in] events Event objects per each command queue that identify * a particular kernel execution instance. * * @return * - \b clblasSuccess on success; * - \b clblasInvalidValue if either \b offA, \b offB or offC exceeds * the size of the respective buffer object; * - the same error codes as the clblasSgemm() function otherwise. * * @ingroup GEMM */ [DllImport(PathToDll, CharSet = CharSet.Ansi, EntryPoint = "clblasCgemm")] public static extern CLBLASStatus Cgemm( CLBLASOrder order, CLBLASTranspose transA, CLBLASTranspose transB, size_t m, size_t n, size_t k, FloatComplex alpha, cl_mem a, // const cl_mem size_t offA, size_t lda, cl_mem b, // const cl_mem size_t offB, size_t ldb, FloatComplex beta, cl_mem c, size_t offC, size_t ldc, cl_uint numCommandQueues, [MarshalAs(UnmanagedType.LPArray)] cl_command_queue[] commandQueues, cl_uint numEventsInWaitList, [MarshalAs(UnmanagedType.LPArray)] cl_event[] eventWaitList, [Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] cl_event[] events); /** * @brief Matrix-matrix product of general rectangular matrices with double * complex elements. Exteneded version. * * Matrix-matrix products: * - \f$ C \leftarrow \alpha A B + \beta C \f$ * - \f$ C \leftarrow \alpha A^T B + \beta C \f$ * - \f$ C \leftarrow \alpha A B^T + \beta C \f$ * - \f$ C \leftarrow \alpha A^T B^T + \beta C \f$ * * @param[in] order Row/column order. * @param[in] transA How matrix \b A is to be transposed. * @param[in] transB How matrix \b B is to be transposed. * @param[in] M Number of rows in matrix \b A. * @param[in] N Number of columns in matrix \b B. * @param[in] K Number of columns in matrix \b A and rows in matrix \b B. * @param[in] alpha The factor of matrix \b A. * @param[in] A Buffer object storing matrix \b A. * @param[in] offA Offset of the first element of the matrix \b A in the * buffer object. Counted in elements. * @param[in] lda Leading dimension of matrix \b A. For detailed description, * see clblasSgemm(). * @param[in] B Buffer object storing matrix \b B. * @param[in] offB Offset of the first element of the matrix \b B in the * buffer object. Counted in elements. * @param[in] ldb Leading dimension of matrix \b B. For detailed description, * see clblasSgemm(). * @param[in] beta The factor of matrix \b C. * @param[out] C Buffer object storing matrix \b C. * @param[in] offC Offset of the first element of the matrix \b C in the * buffer object. Counted in elements. * @param[in] ldc Leading dimension of matrix \b C. For detailed description, * see clblasSgemm(). * @param[in] numCommandQueues Number of OpenCL command queues in which the * task is to be performed. * @param[in] commandQueues OpenCL command queues. * @param[in] numEventsInWaitList Number of events in the event wait list. * @param[in] eventWaitList Event wait list. * @param[in] events Event objects per each command queue that identify * a particular kernel execution instance. * * @return * - \b clblasSuccess on success; * - \b clblasInvalidDevice if a target device does not support floating * point arithmetic with double precision; * - \b clblasInvalidValue if either \b offA, \b offB or offC exceeds * the size of the respective buffer object; * - the same error codes as the clblasSgemm() function otherwise. * * @ingroup GEMM */ [DllImport(PathToDll, CharSet = CharSet.Ansi, EntryPoint = "clblasZgemm")] public static extern CLBLASStatus Zgemm( CLBLASOrder order, CLBLASTranspose transA, CLBLASTranspose transB, size_t m, size_t n, size_t k, DoubleComplex alpha, cl_mem a, // const cl_mem size_t offA, size_t lda, cl_mem b, // const cl_mem size_t offB, size_t ldb, DoubleComplex beta, cl_mem c, size_t offC, size_t ldc, cl_uint numCommandQueues, [MarshalAs(UnmanagedType.LPArray)] cl_command_queue[] commandQueues, cl_uint numEventsInWaitList, [MarshalAs(UnmanagedType.LPArray)] cl_event[] eventWaitList, [Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] cl_event[] events); #endregion #region Level 3 Triangular Matrix-Matrix multiplication /*@}*/ /** * @defgroup TRMM TRMM - Triangular matrix-matrix multiplication * @ingroup BLAS3 */ /*@{*/ /** * @brief Multiplying a matrix by a triangular matrix with float elements. * Extended version. * * Matrix-triangular matrix products: * - \f$ B \leftarrow \alpha A B \f$ * - \f$ B \leftarrow \alpha A^T B \f$ * - \f$ B \leftarrow \alpha B A \f$ * - \f$ B \leftarrow \alpha B A^T \f$ * * where \b T is an upper or lower triangular matrix. * * @param[in] order Row/column order. * @param[in] side The side of triangular matrix. * @param[in] uplo The triangle in matrix being referenced. * @param[in] transA How matrix \b A is to be transposed. * @param[in] diag Specify whether matrix is unit triangular. * @param[in] M Number of rows in matrix \b B. * @param[in] N Number of columns in matrix \b B. * @param[in] alpha The factor of matrix \b A. * @param[in] A Buffer object storing matrix \b A. * @param[in] offA Offset of the first element of the matrix \b A in the * buffer object. Counted in elements. * @param[in] lda Leading dimension of matrix \b A. It cannot be less * than \b M when the \b side parameter is set to * \b clblasLeft,\n or less than \b N when it is set * to \b clblasRight. * @param[out] B Buffer object storing matrix \b B. * @param[in] offB Offset of the first element of the matrix \b B in the * buffer object. Counted in elements. * @param[in] ldb Leading dimension of matrix \b B. It cannot be less * than \b N when the \b order parameter is set to * \b clblasRowMajor,\n or not less than \b M * when it is set to \b clblasColumnMajor. * @param[in] numCommandQueues Number of OpenCL command queues in which the * task is to be performed. * @param[in] commandQueues OpenCL command queues. * @param[in] numEventsInWaitList Number of events in the event wait list. * @param[in] eventWaitList Event wait list. * @param[in] events Event objects per each command queue that identify * a particular kernel execution instance. * * @return * - \b clblasSuccess on success; * - \b clblasInvalidValue if either \b offA or \b offB exceeds the size * of the respective buffer object; * - the same error codes as clblasStrmm() otherwise. * * @ingroup TRMM */ [DllImport(PathToDll, CharSet = CharSet.Ansi, EntryPoint = "clblasStrmm")] public static extern CLBLASStatus Strmm( CLBLASOrder order, CLBLASSide side, CLBLASUpLo uplo, CLBLASTranspose transA, CLBLASDiag diag, size_t m, size_t n, cl_double alpha, cl_mem a, // const cl_mem size_t offA, size_t lda, cl_mem b, size_t offB, size_t ldb, cl_uint numCommandQueues, [MarshalAs(UnmanagedType.LPArray)] cl_command_queue[] commandQueues, cl_uint numEventsInWaitList, [MarshalAs(UnmanagedType.LPArray)] cl_event[] eventWaitList, [Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] cl_event[] events); /** * @example example_strmm.c * This is an example of how to use the @ref clblasStrmmEx function. */ /** * @brief Multiplying a matrix by a triangular matrix with double elements. * Extended version. * * Matrix-triangular matrix products: * - \f$ B \leftarrow \alpha A B \f$ * - \f$ B \leftarrow \alpha A^T B \f$ * - \f$ B \leftarrow \alpha B A \f$ * - \f$ B \leftarrow \alpha B A^T \f$ * * where \b T is an upper or lower triangular matrix. * * @param[in] order Row/column order. * @param[in] side The side of triangular matrix. * @param[in] uplo The triangle in matrix being referenced. * @param[in] transA How matrix \b A is to be transposed. * @param[in] diag Specify whether matrix is unit triangular. * @param[in] M Number of rows in matrix \b B. * @param[in] N Number of columns in matrix \b B. * @param[in] alpha The factor of matrix \b A. * @param[in] A Buffer object storing matrix \b A. * @param[in] offA Offset of the first element of the matrix \b A in the * buffer object. Counted in elements. * @param[in] lda Leading dimension of matrix \b A. For detailed * description, see clblasStrmm(). * @param[out] B Buffer object storing matrix \b B. * @param[in] offB Offset of the first element of the matrix \b B in the * buffer object. Counted in elements. * @param[in] ldb Leading dimension of matrix \b B. For detailed * description, see clblasStrmm(). * @param[in] numCommandQueues Number of OpenCL command queues in which the * task is to be performed. * @param[in] commandQueues OpenCL command queues. * @param[in] numEventsInWaitList Number of events in the event wait list. * @param[in] eventWaitList Event wait list. * @param[in] events Event objects per each command queue that identify * a particular kernel execution instance. * * @return * - \b clblasSuccess on success; * - \b clblasInvalidDevice if a target device does not support floating * point arithmetic with double precision; * - \b clblasInvalidValue if either \b offA or \b offB exceeds the size * of the respective buffer object; * - the same error codes as the clblasStrmm() function otherwise. * * @ingroup TRMM */ [DllImport(PathToDll, CharSet = CharSet.Ansi, EntryPoint = "clblasDtrmm")] public static extern CLBLASStatus Dtrmm( CLBLASOrder order, CLBLASSide side, CLBLASUpLo uplo, CLBLASTranspose transA, CLBLASDiag diag, size_t m, size_t n, cl_double alpha, cl_mem a, // const cl_mem size_t offA, size_t lda, cl_mem b, size_t offB, size_t ldb, cl_uint numCommandQueues, [MarshalAs(UnmanagedType.LPArray)] cl_command_queue[] commandQueues, cl_uint numEventsInWaitList, [MarshalAs(UnmanagedType.LPArray)] cl_event[] eventWaitList, [Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] cl_event[] events); #endregion #region Triangular matrix solve /*@}*/ /** * @defgroup TRSM TRSM - Solving triangular systems of equations * @ingroup BLAS3 */ /*@{*/ /** * @brief Solving triangular systems of equations with multiple right-hand * sides and float elements. Extended version. * * Solving triangular systems of equations: * - \f$ B \leftarrow \alpha A^{-1} B \f$ * - \f$ B \leftarrow \alpha A^{-T} B \f$ * - \f$ B \leftarrow \alpha B A^{-1} \f$ * - \f$ B \leftarrow \alpha B A^{-T} \f$ * * where \b T is an upper or lower triangular matrix. * * @param[in] order Row/column order. * @param[in] side The side of triangular matrix. * @param[in] uplo The triangle in matrix being referenced. * @param[in] transA How matrix \b A is to be transposed. * @param[in] diag Specify whether matrix is unit triangular. * @param[in] M Number of rows in matrix \b B. * @param[in] N Number of columns in matrix \b B. * @param[in] alpha The factor of matrix \b A. * @param[in] A Buffer object storing matrix \b A. * @param[in] offA Offset of the first element of the matrix \b A in the * buffer object. Counted in elements. * @param[in] lda Leading dimension of matrix \b A. It cannot be less * than \b M when the \b side parameter is set to * \b clblasLeft,\n or less than \b N * when it is set to \b clblasRight. * @param[out] B Buffer object storing matrix \b B. * @param[in] offB Offset of the first element of the matrix \b B in the * buffer object. Counted in elements. * @param[in] ldb Leading dimension of matrix \b B. It cannot be less * than \b N when the \b order parameter is set to * \b clblasRowMajor,\n or less than \b M * when it is set to \b clblasColumnMajor. * @param[in] numCommandQueues Number of OpenCL command queues in which the * task is to be performed. * @param[in] commandQueues OpenCL command queues. * @param[in] numEventsInWaitList Number of events in the event wait list. * @param[in] eventWaitList Event wait list. * @param[in] events Event objects per each command queue that identify * a particular kernel execution instance. * * @return * - \b clblasSuccess on success; * - \b clblasInvalidValue if either \b offA or \b offB exceeds the size * of the respective buffer object; * - the same error codes as clblasStrsm() otherwise. * * @ingroup TRSM */ [DllImport(PathToDll, CharSet = CharSet.Ansi, EntryPoint = "clblasStrsm")] public static extern CLBLASStatus Strsm( CLBLASOrder order, CLBLASSide side, CLBLASUpLo uplo, CLBLASTranspose transA, CLBLASDiag diag, size_t m, size_t n, cl_float alpha, cl_mem a, // const cl_mem size_t offA, size_t lda, cl_mem b, size_t offB, size_t ldb, cl_uint numCommandQueues, [MarshalAs(UnmanagedType.LPArray)] cl_command_queue[] commandQueues, cl_uint numEventsInWaitList, [MarshalAs(UnmanagedType.LPArray)] cl_event[] eventWaitList, [Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] cl_event[] events); /** * @example example_strsm.c * This is an example of how to use the @ref clblasStrsmEx function. */ /** * @brief Solving triangular systems of equations with multiple right-hand * sides and double elements. Extended version. * * Solving triangular systems of equations: * - \f$ B \leftarrow \alpha A^{-1} B \f$ * - \f$ B \leftarrow \alpha A^{-T} B \f$ * - \f$ B \leftarrow \alpha B A^{-1} \f$ * - \f$ B \leftarrow \alpha B A^{-T} \f$ * * where \b T is an upper or lower triangular matrix. * * @param[in] order Row/column order. * @param[in] side The side of triangular matrix. * @param[in] uplo The triangle in matrix being referenced. * @param[in] transA How matrix \b A is to be transposed. * @param[in] diag Specify whether matrix is unit triangular. * @param[in] M Number of rows in matrix \b B. * @param[in] N Number of columns in matrix \b B. * @param[in] alpha The factor of matrix \b A. * @param[in] A Buffer object storing matrix \b A. * @param[in] offA Offset of the first element of the matrix \b A in the * buffer object. Counted in elements. * @param[in] lda Leading dimension of matrix \b A. For detailed * description, see clblasStrsm(). * @param[out] B Buffer object storing matrix \b B. * @param[in] offB Offset of the first element of the matrix \b A in the * buffer object. Counted in elements. * @param[in] ldb Leading dimension of matrix \b B. For detailed * description, see clblasStrsm(). * @param[in] numCommandQueues Number of OpenCL command queues in which the * task is to be performed. * @param[in] commandQueues OpenCL command queues. * @param[in] numEventsInWaitList Number of events in the event wait list. * @param[in] eventWaitList Event wait list. * @param[in] events Event objects per each command queue that identify * a particular kernel execution instance. * * @return * - \b clblasSuccess on success; * - \b clblasInvalidDevice if a target device does not support floating * point arithmetic with double precision; * - \b clblasInvalidValue if either \b offA or \b offB exceeds the size * of the respective buffer object; * - the same error codes as the clblasStrsm() function otherwise. * * @ingroup TRSM */ [DllImport(PathToDll, CharSet = CharSet.Ansi, EntryPoint = "clblasDtrsm")] public static extern CLBLASStatus Dtrsm( CLBLASOrder order, CLBLASSide side, CLBLASUpLo uplo, CLBLASTranspose transA, CLBLASDiag diag, size_t m, size_t n, cl_double alpha, cl_mem a, // const cl_mem size_t offA, size_t lda, cl_mem b, size_t offB, size_t ldb, cl_uint numCommandQueues, [MarshalAs(UnmanagedType.LPArray)] cl_command_queue[] commandQueues, cl_uint numEventsInWaitList, [MarshalAs(UnmanagedType.LPArray)] cl_event[] eventWaitList, [Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] cl_event[] events); /** * @brief Solving triangular systems of equations with multiple right-hand * sides and float complex elements. Extended version. * * Solving triangular systems of equations: * - \f$ B \leftarrow \alpha A^{-1} B \f$ * - \f$ B \leftarrow \alpha A^{-T} B \f$ * - \f$ B \leftarrow \alpha B A^{-1} \f$ * - \f$ B \leftarrow \alpha B A^{-T} \f$ * * where \b T is an upper or lower triangular matrix. * * @param[in] order Row/column order. * @param[in] side The side of triangular matrix. * @param[in] uplo The triangle in matrix being referenced. * @param[in] transA How matrix \b A is to be transposed. * @param[in] diag Specify whether matrix is unit triangular. * @param[in] M Number of rows in matrix \b B. * @param[in] N Number of columns in matrix \b B. * @param[in] alpha The factor of matrix \b A. * @param[in] A Buffer object storing matrix \b A. * @param[in] offA Offset of the first element of the matrix \b A in the * buffer object. Counted in elements. * @param[in] lda Leading dimension of matrix \b A. For detailed * description, see clblasStrsm(). * @param[out] B Buffer object storing matrix \b B. * @param[in] offB Offset of the first element of the matrix \b B in the * buffer object. Counted in elements. * @param[in] ldb Leading dimension of matrix \b B. For detailed * description, see clblasStrsm(). * @param[in] numCommandQueues Number of OpenCL command queues in which the * task is to be performed. * @param[in] commandQueues OpenCL command queues. * @param[in] numEventsInWaitList Number of events in the event wait list. * @param[in] eventWaitList Event wait list. * @param[in] events Event objects per each command queue that identify * a particular kernel execution instance. * * @return * - \b clblasSuccess on success; * - \b clblasInvalidValue if either \b offA or \b offB exceeds the size * of the respective buffer object; * - the same error codes as clblasStrsm() otherwise. * * @ingroup TRSM */ [DllImport(PathToDll, CharSet = CharSet.Ansi, EntryPoint = "clblasCtrsm")] public static extern CLBLASStatus Ctrsm( CLBLASOrder order, CLBLASSide side, CLBLASUpLo uplo, CLBLASTranspose transA, CLBLASDiag diag, size_t m, size_t n, FloatComplex alpha, cl_mem a, // const cl_mem size_t offA, size_t lda, cl_mem b, size_t offB, size_t ldb, cl_uint numCommandQueues, [MarshalAs(UnmanagedType.LPArray)] cl_command_queue[] commandQueues, cl_uint numEventsInWaitList, [MarshalAs(UnmanagedType.LPArray)] cl_event[] eventWaitList, [Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] cl_event[] events); /** * @brief Solving triangular systems of equations with multiple right-hand * sides and double complex elements. Extended version. * * Solving triangular systems of equations: * - \f$ B \leftarrow \alpha A^{-1} B \f$ * - \f$ B \leftarrow \alpha A^{-T} B \f$ * - \f$ B \leftarrow \alpha B A^{-1} \f$ * - \f$ B \leftarrow \alpha B A^{-T} \f$ * * where \b T is an upper or lower triangular matrix. * * @param[in] order Row/column order. * @param[in] side The side of triangular matrix. * @param[in] uplo The triangle in matrix being referenced. * @param[in] transA How matrix \b A is to be transposed. * @param[in] diag Specify whether matrix is unit triangular. * @param[in] M Number of rows in matrix \b B. * @param[in] N Number of columns in matrix \b B. * @param[in] alpha The factor of matrix \b A. * @param[in] A Buffer object storing matrix \b A. * @param[in] offA Offset of the first element of the matrix \b A in the * buffer object. Counted in elements. * @param[in] lda Leading dimension of matrix \b A. For detailed * description, see clblasStrsm(). * @param[out] B Buffer object storing matrix \b B. * @param[in] offB Offset of the first element of the matrix \b B in the * buffer object. Counted in elements. * @param[in] ldb Leading dimension of matrix \b B. For detailed * description, see clblasStrsm(). * @param[in] numCommandQueues Number of OpenCL command queues in which the * task is to be performed. * @param[in] commandQueues OpenCL command queues. * @param[in] numEventsInWaitList Number of events in the event wait list. * @param[in] eventWaitList Event wait list. * @param[in] events Event objects per each command queue that identify * a particular kernel execution instance. * * @return * - \b clblasSuccess on success; * - \b clblasInvalidDevice if a target device does not support floating * point arithmetic with double precision; * - \b clblasInvalidValue if either \b offA or \b offB exceeds the size * of the respective buffer object; * - the same error codes as the clblasStrsm() function otherwise * * @ingroup TRSM */ [DllImport(PathToDll, CharSet = CharSet.Ansi, EntryPoint = "clblasZtrsm")] public static extern CLBLASStatus Ztrsm( CLBLASOrder order, CLBLASSide side, CLBLASUpLo uplo, CLBLASTranspose transA, CLBLASDiag diag, size_t m, size_t n, DoubleComplex alpha, cl_mem a, // const cl_mem size_t offA, size_t lda, cl_mem b, size_t offB, size_t ldb, cl_uint numCommandQueues, [MarshalAs(UnmanagedType.LPArray)] cl_command_queue[] commandQueues, cl_uint numEventsInWaitList, [MarshalAs(UnmanagedType.LPArray)] cl_event[] eventWaitList, [Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] cl_event[] events); #endregion } }
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; namespace SharpDX.Toolkit.Graphics { /// <summary> /// A parameter of an effect. /// </summary> /// <remarks> /// A parameter can be a value type that will be set to a constant buffer, or a resource type (SRV, UAV, SamplerState). /// </remarks> public sealed class EffectParameter : ComponentBase { internal readonly EffectData.Parameter ParameterDescription; internal readonly EffectConstantBuffer buffer; private readonly EffectResourceLinker resourceLinker; private readonly GetMatrixDelegate GetMatrixImpl; private readonly CopyMatrixDelegate CopyMatrix; private int offset; /// <summary> /// Initializes a new instance of the <see cref="EffectParameter"/> class. /// </summary> internal EffectParameter(EffectData.ValueTypeParameter parameterDescription, EffectConstantBuffer buffer) : base(parameterDescription.Name) { this.ParameterDescription = parameterDescription; this.buffer = buffer; ResourceType = EffectResourceType.None; IsValueType = true; ParameterClass = parameterDescription.Class; ParameterType = parameterDescription.Type; RowCount = parameterDescription.RowCount; ColumnCount = parameterDescription.ColumnCount; ElementCount = parameterDescription.Count; Offset = parameterDescription.Offset; Size = parameterDescription.Size; // If the expecting Matrix is column_major or the expected size is != from Matrix, than we need to remap SharpDX.Matrix to it. if (ParameterClass == EffectParameterClass.MatrixRows || ParameterClass == EffectParameterClass.MatrixColumns) { var isMatrixToMap = parameterDescription.Size != Interop.SizeOf<Matrix>() || ParameterClass == EffectParameterClass.MatrixColumns; // Use the correct function for this parameter CopyMatrix = isMatrixToMap ? (ParameterClass == EffectParameterClass.MatrixRows) ? new CopyMatrixDelegate(CopyMatrixRowMajor) : CopyMatrixColumnMajor : CopyMatrixDirect; GetMatrixImpl = isMatrixToMap ? (ParameterClass == EffectParameterClass.MatrixRows) ? new GetMatrixDelegate(GetMatrixRowMajorFrom) : GetMatrixColumnMajorFrom : GetMatrixDirectFrom; } } /// <summary> /// Initializes a new instance of the <see cref="EffectParameter"/> class. /// </summary> internal EffectParameter(EffectData.ResourceParameter parameterDescription, EffectResourceType resourceType, int offset, EffectResourceLinker resourceLinker) : base(parameterDescription.Name) { this.ParameterDescription = parameterDescription; this.resourceLinker = resourceLinker; ResourceType = resourceType; IsValueType = false; ParameterClass = parameterDescription.Class; ParameterType = parameterDescription.Type; RowCount = ColumnCount = 0; ElementCount = parameterDescription.Count; Offset = offset; } /// <summary> /// A unique index of this parameter instance inside the <see cref="EffectParameterCollection"/> of an effect. See remarks. /// </summary> /// <remarks> /// This unique index can be used between different instance of the effect with different deferred <see cref="GraphicsDevice"/>. /// </remarks> public int Index { get; internal set; } /// <summary> /// Gets the parameter class. /// </summary> /// <value>The parameter class.</value> public readonly EffectParameterClass ParameterClass; /// <summary> /// Gets the resource type. /// </summary> public readonly EffectResourceType ResourceType; /// <summary> /// Gets the type of the parameter. /// </summary> /// <value>The type of the parameter.</value> public readonly EffectParameterType ParameterType; /// <summary> /// Gets a boolean indicating if this parameter is a value type (true) or a resource type (false). /// </summary> public readonly bool IsValueType; /// <summary> /// Number of rows in a matrix. Otherwise a numeric type returns 1, any other type returns 0. /// </summary> /// <unmanaged>int Rows</unmanaged> public readonly int RowCount; /// <summary> /// Number of columns in a matrix. Otherwise a numeric type returns 1, any other type returns 0. /// </summary> /// <unmanaged>int Columns</unmanaged> public readonly int ColumnCount; /// <summary> /// Gets the collection of effect parameters. /// </summary> public readonly int ElementCount; /// <summary> /// Size in bytes of the element, only valid for value types. /// </summary> public readonly int Size; /// <summary> /// Offset of this parameter. /// </summary> /// <remarks> /// For a value type, this offset is the offset in bytes inside the constant buffer. /// For a resource type, this offset is an index to the resource linker. /// </remarks> public int Offset { get { return offset; } internal set { offset = value; } } /// <summary> /// Gets a single value to the associated parameter in the constant buffer. /// </summary> /// <typeparam name="T">The type of the value to read from the buffer.</typeparam> /// <returns>The value of this parameter.</returns> public T GetValue<T>() where T : struct { return buffer.Get<T>(offset); } /// <summary> /// Gets an array of values to the associated parameter in the constant buffer. /// </summary> /// <typeparam name = "T">The type of the value to read from the buffer.</typeparam> /// <returns>The value of this parameter.</returns> public T[] GetValueArray<T>(int count) where T : struct { return buffer.GetRange<T>(offset, count); } /// <summary> /// Gets a single value to the associated parameter in the constant buffer. /// </summary> /// <returns>The value of this parameter.</returns> public Matrix GetMatrix() { return GetMatrixImpl(offset); } /// <summary> /// Gets a single value to the associated parameter in the constant buffer. /// </summary> /// <returns>The value of this parameter.</returns> public Matrix GetMatrix(int startIndex) { return GetMatrixImpl(offset + (startIndex << 6)); } /// <summary> /// Gets an array of matrices to the associated parameter in the constant buffer. /// </summary> /// <param name="count">The count.</param> /// <returns>Matrix[][].</returns> /// <returns>The value of this parameter.</returns> public Matrix[] GetMatrixArray(int count) { return GetMatrixArray(0, count); } /// <summary> /// Gets an array of matrices to the associated parameter in the constant buffer. /// </summary> /// <returns>The value of this parameter.</returns> public unsafe Matrix[] GetMatrixArray(int startIndex, int count) { var result = new Matrix[count]; var localOffset = offset + (startIndex << 6); // Fix the whole buffer fixed (Matrix* pMatrix = result) { for (int i = 0; i < result.Length; i++, localOffset += Utilities.SizeOf<Matrix>()) pMatrix[i] = GetMatrixImpl(localOffset); } buffer.IsDirty = true; return result; } /// <summary> /// Sets a single value to the associated parameter in the constant buffer. /// </summary> /// <typeparam name = "T">The type of the value to be written to the buffer.</typeparam> /// <param name = "value">The value to write to the buffer.</param> public void SetValue<T>(ref T value) where T : struct { buffer.Set(offset, ref value); buffer.IsDirty = true; } /// <summary> /// Sets a single value to the associated parameter in the constant buffer. /// </summary> /// <typeparam name = "T">The type of the value to be written to the buffer.</typeparam> /// <param name = "value">The value to write to the buffer.</param> public void SetValue<T>(T value) where T : struct { buffer.Set(offset, value); buffer.IsDirty = true; } /// <summary> /// Sets a single matrix value to the associated parameter in the constant buffer. /// </summary> /// <param name = "value">The matrix to write to the buffer.</param> public void SetValue(ref Matrix value) { CopyMatrix(ref value, offset); buffer.IsDirty = true; } /// <summary> /// Sets a single matrix value to the associated parameter in the constant buffer. /// </summary> /// <param name = "value">The matrix to write to the buffer.</param> public void SetValue(Matrix value) { CopyMatrix(ref value, offset); buffer.IsDirty = true; } /// <summary> /// Sets an array of matrices to the associated parameter in the constant buffer. /// </summary> /// <param name = "values">An array of matrices to be written to the current buffer.</param> public unsafe void SetValue(Matrix[] values) { var localOffset = offset; // Fix the whole buffer fixed (Matrix* pMatrix = values) { for (int i = 0; i < values.Length; i++, localOffset += Utilities.SizeOf<Matrix>()) CopyMatrix(ref pMatrix[i], localOffset); } buffer.IsDirty = true; } /// <summary> /// Sets a single matrix at the specified index for the associated parameter in the constant buffer. /// </summary> /// <param name="index">Index of the matrix to write in element count.</param> /// <param name = "value">The matrix to write to the buffer.</param> public void SetValue(int index, Matrix value) { CopyMatrix(ref value, offset + (index << 6)); buffer.IsDirty = true; } /// <summary> /// Sets an array of matrices to at the specified index for the associated parameter in the constant buffer. /// </summary> /// <param name="index">Index of the matrix to write in element count.</param> /// <param name = "values">An array of matrices to be written to the current buffer.</param> public unsafe void SetValue(int index, Matrix[] values) { var localOffset = this.offset + (index << 6); // Fix the whole buffer fixed (Matrix* pMatrix = values) { for (int i = 0; i < values.Length; i++, localOffset += Utilities.SizeOf<Matrix>()) CopyMatrix(ref pMatrix[i], localOffset); } buffer.IsDirty = true; } /// <summary> /// Sets an array of values to the associated parameter in the constant buffer. /// </summary> /// <typeparam name = "T">The type of the value to be written to the buffer.</typeparam> /// <param name = "values">An array of values to be written to the current buffer.</param> public void SetValue<T>(T[] values) where T : struct { buffer.Set(offset, values); buffer.IsDirty = true; } /// <summary> /// Sets a single value at the specified index for the associated parameter in the constant buffer. /// </summary> /// <typeparam name = "T">The type of the value to be written to the buffer.</typeparam> /// <param name="index">Index of the value to write in typeof(T) element count.</param> /// <param name = "value">The value to write to the buffer.</param> public void SetValue<T>(int index, ref T value) where T : struct { buffer.Set(offset + Interop.SizeOf<T>() * index, ref value); buffer.IsDirty = true; } /// <summary> /// Sets a single value at the specified index for the associated parameter in the constant buffer. /// </summary> /// <typeparam name = "T">The type of the value to be written to the buffer.</typeparam> /// <param name="index">Index of the value to write in typeof(T) element count.</param> /// <param name = "value">The value to write to the buffer.</param> public void SetValue<T>(int index, T value) where T : struct { buffer.Set(offset + Interop.SizeOf<T>() * index, value); buffer.IsDirty = true; } /// <summary> /// Sets an array of values to at the specified index for the associated parameter in the constant buffer. /// </summary> /// <typeparam name = "T">The type of the value to be written to the buffer.</typeparam> /// <param name="index">Index of the value to write in typeof(T) element count.</param> /// <param name = "values">An array of values to be written to the current buffer.</param> public void SetValue<T>(int index, T[] values) where T : struct { buffer.Set(offset + Interop.SizeOf<T>() * index, values); buffer.IsDirty = true; } /// <summary> /// Gets the resource view set for this parameter. /// </summary> /// <typeparam name = "T">The type of the resource view.</typeparam> /// <returns>The resource view.</returns> public T GetResource<T>() where T : class { return resourceLinker.GetResource<T>(offset); } /// <summary> /// Sets a shader resource for the associated parameter. /// </summary> /// <typeparam name = "T">The type of the resource view.</typeparam> /// <param name="resourceView">The resource view.</param> public void SetResource<T>(T resourceView) where T : class { resourceLinker.SetResource(offset, ResourceType, resourceView); } /// <summary> /// Sets a shader resource for the associated parameter. /// </summary> /// <param name="resourceView">The resource.</param> /// <param name="initialUAVCount">The initial count for the UAV (-1) to keep it</param> public void SetResource(Direct3D11.UnorderedAccessView resourceView, int initialUAVCount) { resourceLinker.SetResource(offset, ResourceType, resourceView, initialUAVCount); } /// <summary> /// Direct access to the resource pointer in order to /// </summary> /// <param name="resourcePointer"></param> internal void SetResourcePointer(IntPtr resourcePointer) { resourceLinker.SetResourcePointer(offset, ResourceType, resourcePointer); } /// <summary> /// Sets a an array of shader resource views for the associated parameter. /// </summary> /// <typeparam name = "T">The type of the resource view.</typeparam> /// <param name="resourceViewArray">The resource view array.</param> public void SetResource<T>(params T[] resourceViewArray) where T : class { resourceLinker.SetResource(offset, ResourceType, resourceViewArray); } /// <summary> /// Sets a an array of shader resource views for the associated parameter. /// </summary> /// <param name="resourceViewArray">The resource view array.</param> /// <param name="uavCounts">Sets the initial uavCount</param> public void SetResource(Direct3D11.UnorderedAccessView[] resourceViewArray, int[] uavCounts) { resourceLinker.SetResource(offset, ResourceType, resourceViewArray, uavCounts); } /// <summary> /// Sets a shader resource at the specified index for the associated parameter. /// </summary> /// <typeparam name = "T">The type of the resource view.</typeparam> /// <param name="index">Index to start to set the resource views</param> /// <param name="resourceView">The resource view.</param> public void SetResource<T>(int index, T resourceView) where T : class { resourceLinker.SetResource(offset + index, ResourceType, resourceView); } /// <summary> /// Sets a an array of shader resource views at the specified index for the associated parameter. /// </summary> /// <typeparam name = "T">The type of the resource view.</typeparam> /// <param name="index">Index to start to set the resource views</param> /// <param name="resourceViewArray">The resource view array.</param> public void SetResource<T>(int index, params T[] resourceViewArray) where T : class { resourceLinker.SetResource(offset + index, ResourceType, resourceViewArray); } /// <summary> /// Sets a an array of shader resource views at the specified index for the associated parameter. /// </summary> /// <param name="index">Index to start to set the resource views</param> /// <param name="resourceViewArray">The resource view array.</param> /// <param name="uavCount">Sets the initial uavCount</param> public void SetResource(int index, Direct3D11.UnorderedAccessView[] resourceViewArray, int[] uavCount) { resourceLinker.SetResource(offset + index, ResourceType, resourceViewArray, uavCount); } internal void SetDefaultValue() { if (IsValueType) { var defaultValue = ((EffectData.ValueTypeParameter) ParameterDescription).DefaultValue; if (defaultValue != null) { SetValue(defaultValue); } } } public override string ToString() { return string.Format("[{0}] {1} Class: {2}, Resource: {3}, Type: {4}, IsValue: {5}, RowCount: {6}, ColumnCount: {7}, ElementCount: {8} Offset: {9}", Index, Name, ParameterClass, ResourceType, ParameterType, IsValueType, RowCount, ColumnCount, ElementCount, Offset); } /// <summary> /// CopyMatrix delegate used to reorder matrix when copying from <see cref="Matrix"/>. /// </summary> /// <param name="matrix">The source matrix.</param> /// <param name="offset">The offset in bytes to write to</param> private delegate void CopyMatrixDelegate(ref Matrix matrix, int offset); /// <summary> /// Copy matrix in row major order. /// </summary> /// <param name="matrix">The source matrix.</param> /// <param name="offset">The offset in bytes to write to</param> private unsafe void CopyMatrixRowMajor(ref Matrix matrix, int offset) { var pDest = (float*)((byte*)buffer.DataPointer + offset); fixed (void* pMatrix = &matrix) { var pSrc = (float*)pMatrix; // If Matrix is row_major but expecting less columns/rows // then copy only necessary columns/rows. for (int i = 0; i < RowCount; i++, pSrc +=4, pDest += 4) { for (int j = 0; j < ColumnCount; j++) pDest[j] = pSrc[j]; } } } /// <summary> /// Copy matrix in column major order. /// </summary> /// <param name="matrix">The source matrix.</param> /// <param name="offset">The offset in bytes to write to</param> private unsafe void CopyMatrixColumnMajor(ref Matrix matrix, int offset) { var pDest = (float*)((byte*)buffer.DataPointer + offset); fixed (void* pMatrix = &matrix) { var pSrc = (float*)pMatrix; // If Matrix is column_major, then we need to transpose it for (int i = 0; i < ColumnCount; i++, pSrc++, pDest += 4) { for (int j = 0; j < RowCount; j++) pDest[j] = pSrc[j * 4]; } } } /// <summary> /// Straight Matrix copy, no conversion. /// </summary> /// <param name="matrix">The source matrix.</param> /// <param name="offset">The offset in bytes to write to</param> private void CopyMatrixDirect(ref Matrix matrix, int offset) { buffer.Set(offset, matrix); } /// <summary> /// CopyMatrix delegate used to reorder matrix when copying from <see cref="Matrix"/>. /// </summary> /// <param name="offset">The offset in bytes to write to</param> private delegate Matrix GetMatrixDelegate(int offset); /// <summary> /// Copy matrix in row major order. /// </summary> /// <param name="offset">The offset in bytes to write to</param> private unsafe Matrix GetMatrixRowMajorFrom(int offset) { var result = default(Matrix); var pSrc = (float*)((byte*)buffer.DataPointer + offset); var pDest = (float*)&result; // If Matrix is row_major but expecting less columns/rows // then copy only necessary columns/rows. for (int i = 0; i < RowCount; i++, pSrc += 4, pDest += 4) { for (int j = 0; j < ColumnCount; j++) pDest[j] = pSrc[j]; } return result; } /// <summary> /// Copy matrix in column major order. /// </summary> /// <param name="offset">The offset in bytes to write to</param> private unsafe Matrix GetMatrixColumnMajorFrom(int offset) { var result = default(Matrix); var pSrc = (float*)((byte*)buffer.DataPointer + offset); var pDest = (float*)&result; // If Matrix is column_major, then we need to transpose it for (int i = 0; i < ColumnCount; i++, pSrc +=4, pDest++) { for (int j = 0; j < RowCount; j++) pDest[j * 4] = pSrc[j]; } return result; } /// <summary> /// Straight Matrix copy, no conversion. /// </summary> /// <param name="offset">The offset in bytes to write to</param> private Matrix GetMatrixDirectFrom(int offset) { return buffer.GetMatrix(offset); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace KnowledgeBase.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// 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 Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class PropertyNamesShouldNotMatchGetMethodsTests : DiagnosticAnalyzerTestBase { private const string CSharpTestTemplate = @" using System; public class Test {{ {0} DateTime Date {{ get; }} {1} string GetDate() {{ return DateTime.Today.ToString(); }} }}"; private const string BasicTestTemplate = @" Imports System Public Class Test {0} ReadOnly Property [Date]() As DateTime Get Return DateTime.Today End Get End Property {1} Function GetDate() As String Return Me.Date.ToString() End Function End Class"; protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new PropertyNamesShouldNotMatchGetMethodsAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new PropertyNamesShouldNotMatchGetMethodsAnalyzer(); } [Fact] public void CSharp_CA1721_PropertyNameDoesNotMatchGetMethodName_Exposed_NoDiagnostic() { VerifyCSharp(@" using System; public class Test { public DateTime Date { get; } public string GetTime() { return DateTime.Today.ToString(); } }"); } [Theory] [InlineData("public", "public")] [InlineData("public", "protected")] [InlineData("public", "protected internal")] [InlineData("protected", "public")] [InlineData("protected", "protected")] [InlineData("protected", "protected internal")] [InlineData("protected internal", "public")] [InlineData("protected internal", "protected")] [InlineData("protected internal", "protected internal")] public void CSharp_CA1721_PropertyNamesMatchGetMethodNames_Exposed_Diagnostics(string propertyAccessibility, string methodAccessibility) { VerifyCSharp( string.Format(CSharpTestTemplate, propertyAccessibility, methodAccessibility), GetCA1721CSharpResultAt( line: 6, column: $" {propertyAccessibility} DateTime ".Length + 1, identifierName: "Date", otherIdentifierName: "GetDate")); } [Theory] [InlineData("private", "private")] [InlineData("private", "internal")] [InlineData("internal", "private")] [InlineData("internal", "internal")] [InlineData("", "")] public void CSharp_CA1721_PropertyNamesMatchGetMethodNames_Unexposed_NoDiagnostics(string propertyAccessibility, string methodAccessibility) { VerifyCSharp(string.Format(CSharpTestTemplate, propertyAccessibility, methodAccessibility)); } [Theory] [InlineData("public", "private")] [InlineData("protected", "private")] [InlineData("protected internal", "private")] [InlineData("public", "internal")] [InlineData("protected", "internal")] [InlineData("protected internal", "internal")] [InlineData("public", "")] [InlineData("protected", "")] [InlineData("protected internal", "")] [InlineData("private", "public")] [InlineData("private", "protected")] [InlineData("private", "protected internal")] [InlineData("internal", "public")] [InlineData("internal", "protected")] [InlineData("internal", "protected internal")] [InlineData("", "public")] [InlineData("", "protected")] [InlineData("", "protected internal")] public void CSharp_CA1721_PropertyNamesMatchGetMethodNames_MixedExposure_NoDiagnostics(string propertyAccessibility, string methodAccessibility) { VerifyCSharp(string.Format(CSharpTestTemplate, propertyAccessibility, methodAccessibility)); } [Fact] public void CSharp_CA1721_PropertyNameMatchesBaseClassGetMethodName_Exposed_Diagnostic() { VerifyCSharp(@" using System; public class Foo { public string GetDate() { return DateTime.Today.ToString(); } } public class Bar : Foo { public DateTime Date { get { return DateTime.Today; } } }", GetCA1721CSharpResultAt(line: 14, column: 21, identifierName: "Date", otherIdentifierName: "GetDate")); } [Fact] public void CSharp_CA1721_GetMethodNameMatchesBaseClassPropertyName_Exposed_Diagnostic() { VerifyCSharp(@" using System; public class Foo { public DateTime Date { get { return DateTime.Today; } } } public class Bar : Foo { public string GetDate() { return DateTime.Today.ToString(); } }", GetCA1721CSharpResultAt(line: 14, column: 19, identifierName: "Date", otherIdentifierName: "GetDate")); } [Fact] public void Basic_CA1721_PropertyNameDoesNotMatchGetMethodName_Exposed_NoDiagnostic() { VerifyBasic(@" Imports System Public Class Test Public ReadOnly Property [Date]() As DateTime Get Return DateTime.Today End Get End Property Public Function GetTime() As String Return Me.Date.ToString() End Function End Class"); } [Theory] [InlineData("Public", "Public")] [InlineData("Public", "Protected")] [InlineData("Public", "Protected Friend")] [InlineData("Protected", "Public")] [InlineData("Protected", "Protected")] [InlineData("Protected", "Protected Friend")] [InlineData("Protected Friend", "Public")] [InlineData("Protected Friend", "Protected")] [InlineData("Protected Friend", "Protected Friend")] public void Basic_CA1721_PropertyNamesMatchGetMethodNames_Exposed_Diagnostics(string propertyAccessibility, string methodAccessibility) { VerifyBasic( string.Format(BasicTestTemplate, propertyAccessibility, methodAccessibility), GetCA1721BasicResultAt( line: 5, column: $" {propertyAccessibility} ReadOnly Property ".Length + 1, identifierName: "Date", otherIdentifierName: "GetDate")); } [Theory] [InlineData("Private", "Private")] [InlineData("Private", "Friend")] [InlineData("Friend", "Private")] [InlineData("Friend", "Friend")] public void Basic_CA1721_PropertyNamesMatchGetMethodNames_Unexposed_NoDiagnostics(string propertyAccessibility, string methodAccessibility) { VerifyBasic(string.Format(BasicTestTemplate, propertyAccessibility, methodAccessibility)); } [Theory] [InlineData("Public", "Private")] [InlineData("Protected", "Private")] [InlineData("Protected Friend", "Private")] [InlineData("Public", "Friend")] [InlineData("Protected", "Friend")] [InlineData("Protected Friend", "Friend")] [InlineData("Private", "Public")] [InlineData("Private", "Protected")] [InlineData("Private", "Protected Friend")] [InlineData("Friend", "Public")] [InlineData("Friend", "Protected")] [InlineData("Friend", "Protected Friend")] public void Basic_CA1721_PropertyNamesMatchGetMethodNames_MixedExposure_NoDiagnostics(string propertyAccessibility, string methodAccessibility) { VerifyBasic(string.Format(BasicTestTemplate, propertyAccessibility, methodAccessibility)); } [Fact] public void Basic_CA1721_PropertyNameMatchesBaseClassGetMethodName_Exposed_Diagnostic() { VerifyBasic(@" Imports System Public Class Foo Public Function GetDate() As String Return DateTime.Today.ToString() End Function End Class Public Class Bar Inherits Foo Public ReadOnly Property [Date]() As DateTime Get Return DateTime.Today End Get End Property End Class", GetCA1721BasicResultAt(line: 12, column: 30, identifierName: "Date", otherIdentifierName: "GetDate")); } [Fact] public void Basic_CA1721_GetMethodNameMatchesBaseClassPropertyName_Exposed_Diagnostic() { VerifyBasic(@" Imports System Public Class Foo Public ReadOnly Property [Date]() As DateTime Get Return DateTime.Today End Get End Property End Class Public Class Bar Inherits Foo Public Function GetDate() As String Return DateTime.Today.ToString() End Function End Class", GetCA1721BasicResultAt(line: 13, column: 21, identifierName: "Date", otherIdentifierName: "GetDate")); } #region Helpers private static DiagnosticResult GetCA1721CSharpResultAt(int line, int column, string identifierName, string otherIdentifierName) { // Add a public read-only property accessor for positional argument '{0}' of attribute '{1}'. string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.PropertyNamesShouldNotMatchGetMethodsMessage, identifierName, otherIdentifierName); return GetCSharpResultAt(line, column, PropertyNamesShouldNotMatchGetMethodsAnalyzer.RuleId, message); } private static DiagnosticResult GetCA1721BasicResultAt(int line, int column, string identifierName, string otherIdentifierName) { // Add a public read-only property accessor for positional argument '{0}' of attribute '{1}'. string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.PropertyNamesShouldNotMatchGetMethodsMessage, identifierName, otherIdentifierName); return GetBasicResultAt(line, column, PropertyNamesShouldNotMatchGetMethodsAnalyzer.RuleId, message); } #endregion } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using SDKTemplate; using System; using System.Threading.Tasks; using Windows.Devices.Sensors; using Windows.Foundation; using Windows.UI.Core; using Windows.Globalization.DateTimeFormatting; using System.Collections.ObjectModel; using System.Collections.Generic; using Windows.Globalization; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace PedometerCS { /// <summary> /// History Page that gets loaded when 'History' scenario is selected. /// </summary> public sealed partial class Scenario2_History : Page { MainPage rootPage = MainPage.Current; public Scenario2_History() { this.InitializeComponent(); historyRecords = new ObservableCollection<HistoryRecord>(); historyRecordsList.DataContext = historyRecords; rootPage.NotifyUser("Choose time span for history", NotifyType.StatusMessage); } private void AllHistory_Checked(object sender, Windows.UI.Xaml.RoutedEventArgs e) { // Collapse SpanPicker - SpanPicker will not be created yet the first time the page is loading if (SpanPicker != null) { SpanPicker.Visibility = Visibility.Collapsed; } getAllHistory = true; rootPage.NotifyUser("This will retrieve all the step count history available on the system", NotifyType.StatusMessage); } private void SpecificHistory_Checked(object sender, Windows.UI.Xaml.RoutedEventArgs e) { SpanPicker.Visibility = Visibility.Visible; getAllHistory = false; rootPage.NotifyUser("This will retrieve all the step count history for the selected time span", NotifyType.StatusMessage); } /// <summary> /// Invoked when 'Get History' button is clicked. /// Depending on the user selection, this handler uses one of the overloaded /// 'GetSystemHistoryAsync' APIs to retrieve the pedometer history of the user /// </summary> /// <param name="sender">unused</param> /// <param name="e">unused</param> async private void GetHistory_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { IReadOnlyList<PedometerReading> historyReadings = null; DateTimeFormatter timestampFormatter = new DateTimeFormatter("shortdate longtime"); // Disable subsequent history retrieval while the async operation is in progress GetHistory.IsEnabled = false; // clear previous content being displayed historyRecords.Clear(); try { if (getAllHistory) { DateTime dt = DateTime.FromFileTimeUtc(0); DateTimeOffset fromBeginning = new DateTimeOffset(dt); rootPage.NotifyUser("Retrieving all available History", NotifyType.StatusMessage); historyReadings = await Pedometer.GetSystemHistoryAsync(fromBeginning); } else { String notificationString = "Retrieving history from: "; Calendar calendar = new Calendar(); calendar.ChangeClock("24HourClock"); // DateTime picker will also include hour, minute and seconds from the the system time. // Decrement the same to be able to correctly add TimePicker values. calendar.SetDateTime(FromDate.Date); calendar.AddNanoseconds(-calendar.Nanosecond); calendar.AddSeconds(-calendar.Second); calendar.AddMinutes(-calendar.Minute); calendar.AddHours(-calendar.Hour); calendar.AddSeconds(Convert.ToInt32(FromTime.Time.TotalSeconds)); DateTimeOffset fromTime = calendar.GetDateTime(); calendar.SetDateTime(ToDate.Date); calendar.AddNanoseconds(-calendar.Nanosecond); calendar.AddSeconds(-calendar.Second); calendar.AddMinutes(-calendar.Minute); calendar.AddHours(-calendar.Hour); calendar.AddSeconds(Convert.ToInt32(ToTime.Time.TotalSeconds)); DateTimeOffset toTime = calendar.GetDateTime(); notificationString += timestampFormatter.Format(fromTime); notificationString += " To "; notificationString += timestampFormatter.Format(toTime); if (toTime.ToFileTime() < fromTime.ToFileTime()) { rootPage.NotifyUser("Invalid time span. 'To Time' must be equal or more than 'From Time'", NotifyType.ErrorMessage); // Enable subsequent history retrieval while the async operation is in progress GetHistory.IsEnabled = true; } else { TimeSpan span; span = TimeSpan.FromTicks(toTime.Ticks - fromTime.Ticks); rootPage.NotifyUser(notificationString, NotifyType.StatusMessage); historyReadings = await Pedometer.GetSystemHistoryAsync(fromTime, span); } } if (historyReadings != null) { foreach(PedometerReading reading in historyReadings) { HistoryRecord record = new HistoryRecord(reading); historyRecords.Add(record); } rootPage.NotifyUser("History retrieval completed", NotifyType.StatusMessage); } } catch (UnauthorizedAccessException) { rootPage.NotifyUser("User has denied access to activity history", NotifyType.ErrorMessage); } // Finally, re-enable history retrieval GetHistory.IsEnabled = true; } private ObservableCollection<HistoryRecord> historyRecords; private bool getAllHistory = true; } /// <summary> /// Represents a history record object that gets binded to the ListView /// controller in the XAML /// </summary> public sealed class HistoryRecord { public String TimeStamp { get { DateTimeFormatter timestampFormatter = new DateTimeFormatter("shortdate longtime"); return timestampFormatter.Format(recordTimestamp); } } public String StepKind { get { String stepString; switch (stepKind) { case PedometerStepKind.Unknown: stepString = "Unknown"; break; case PedometerStepKind.Walking: stepString = "Walking"; break; case PedometerStepKind.Running: stepString = "Running"; break; default: stepString = "Invalid Step Kind"; break; } return stepString; } } public Int32 StepsCount { get { return stepsCount; } } public double StepsDuration { get { // return Duration in ms return stepsDuration.TotalMilliseconds; } } public HistoryRecord(PedometerReading reading) { stepKind = reading.StepKind; stepsCount = reading.CumulativeSteps; recordTimestamp = reading.Timestamp; } private DateTimeOffset recordTimestamp; private PedometerStepKind stepKind; private Int32 stepsCount; private TimeSpan stepsDuration; } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Management.Automation; using System.Net; using System.Reflection; using EnvDTE; using NuGet.VisualStudio; namespace NuGet.PowerShell.Commands { /// <summary> /// This is the base class for all NuGet cmdlets. /// </summary> public abstract class NuGetBaseCommand : PSCmdlet, ILogger, IErrorHandler { // User Agent. Do NOT localize private const string PSCommandsUserAgentClient = "NuGet Package Manager Console"; private Lazy<string> _psCommandsUserAgent = new Lazy<string>(() => HttpUtility.CreateUserAgentString(PSCommandsUserAgentClient)); private IVsPackageManager _packageManager; private readonly ISolutionManager _solutionManager; private readonly IVsPackageManagerFactory _vsPackageManagerFactory; private ProgressRecordCollection _progressRecordCache; private readonly IHttpClientEvents _httpClientEvents; protected NuGetBaseCommand(ISolutionManager solutionManager, IVsPackageManagerFactory vsPackageManagerFactory, IHttpClientEvents httpClientEvents) { _solutionManager = solutionManager; _vsPackageManagerFactory = vsPackageManagerFactory; _httpClientEvents = httpClientEvents; } private ProgressRecordCollection ProgressRecordCache { get { if (_progressRecordCache == null) { _progressRecordCache = new ProgressRecordCollection(); } return _progressRecordCache; } } protected IErrorHandler ErrorHandler { get { return this; } } protected ISolutionManager SolutionManager { get { return _solutionManager; } } protected IVsPackageManagerFactory PackageManagerFactory { get { return _vsPackageManagerFactory; } } internal bool IsSyncMode { get { if (Host == null || Host.PrivateData == null) { return false; } PSObject privateData = Host.PrivateData; var syncModeProp = privateData.Properties["IsSyncMode"]; return syncModeProp != null && (bool)syncModeProp.Value; } } /// <summary> /// Gets an instance of VSPackageManager to be used throughout the execution of this command. /// </summary> /// <value>The package manager.</value> protected internal IVsPackageManager PackageManager { get { if (_packageManager == null) { _packageManager = CreatePackageManager(); } return _packageManager; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to display friendly message to the console.")] protected sealed override void ProcessRecord() { try { ProcessRecordCore(); } catch (Exception ex) { // unhandled exceptions should be terminating ErrorHandler.HandleException(ex, terminating: true); } } /// <summary> /// Derived classess must implement this method instead of ProcessRecord(), which is sealed by NuGetBaseCmdlet. /// </summary> protected abstract void ProcessRecordCore(); void ILogger.Log(MessageLevel level, string message, params object[] args) { string formattedMessage = String.Format(CultureInfo.CurrentCulture, message, args); Log(level, formattedMessage); } internal void Execute() { BeginProcessing(); ProcessRecord(); EndProcessing(); } protected override void BeginProcessing() { if (_httpClientEvents != null) { _httpClientEvents.SendingRequest += OnSendingRequest; } } protected override void EndProcessing() { if (_httpClientEvents != null) { _httpClientEvents.SendingRequest -= OnSendingRequest; } } protected void SubscribeToProgressEvents() { if (!IsSyncMode && _httpClientEvents != null) { _httpClientEvents.ProgressAvailable += OnProgressAvailable; } } protected void UnsubscribeFromProgressEvents() { if (_httpClientEvents != null) { _httpClientEvents.ProgressAvailable -= OnProgressAvailable; } } protected virtual void Log(MessageLevel level, string formattedMessage) { switch (level) { case MessageLevel.Debug: WriteVerbose(formattedMessage); break; case MessageLevel.Warning: WriteWarning(formattedMessage); break; case MessageLevel.Info: WriteLine(formattedMessage); break; } } protected virtual IVsPackageManager CreatePackageManager() { if (!SolutionManager.IsSolutionOpen) { return null; } return PackageManagerFactory.CreatePackageManager(); } /// <summary> /// Return all projects in the solution matching the provided names. Wildcards are supported. /// This method will automatically generate error records for non-wildcarded project names that /// are not found. /// </summary> /// <param name="projectNames">An array of project names that may or may not include wildcards.</param> /// <returns>Projects matching the project name(s) provided.</returns> protected IEnumerable<Project> GetProjectsByName(string[] projectNames) { var allValidProjectNames = GetAllValidProjectNames().ToList(); foreach (string projectName in projectNames) { // if ctrl+c hit, leave immediately if (Stopping) { break; } // Treat every name as a wildcard; results in simpler code var pattern = new WildcardPattern(projectName, WildcardOptions.IgnoreCase); var matches = from s in allValidProjectNames where pattern.IsMatch(s) select _solutionManager.GetProject(s); int count = 0; foreach (var project in matches) { count++; yield return project; } // We only emit non-terminating error record if a non-wildcarded name was not found. // This is consistent with built-in cmdlets that support wildcarded search. // A search with a wildcard that returns nothing should not be considered an error. if ((count == 0) && !WildcardPattern.ContainsWildcardCharacters(projectName)) { ErrorHandler.WriteProjectNotFoundError(projectName, terminating: false); } } } /// <summary> /// Return all possibly valid project names in the current solution. This includes all /// unique names and safe names. /// </summary> /// <returns></returns> private IEnumerable<string> GetAllValidProjectNames() { var safeNames = _solutionManager.GetProjects().Select(p => _solutionManager.GetProjectSafeName(p)); var uniqueNames = _solutionManager.GetProjects().Select(p => p.GetCustomUniqueName()); return uniqueNames.Concat(safeNames).Distinct(); } /// <summary> /// Translate a PSPath into a System.IO.* friendly Win32 path. /// Does not resolve/glob wildcards. /// </summary> /// <param name="psPath">The PowerShell PSPath to translate which may reference PSDrives or have provider-qualified paths which are syntactically invalid for .NET APIs.</param> /// <param name="path">The translated PSPath in a format understandable to .NET APIs.</param> /// <param name="exists">Returns null if not tested, or a bool representing path existence.</param> /// <param name="errorMessage">If translation failed, contains the reason.</param> /// <returns>True if successfully translated, false if not.</returns> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "Following TryParse pattern in BCL", Target = "path")] [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "Following TryParse pattern in BCL", Target = "exists")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "ps", Justification = "ps is a common powershell prefix")] protected bool TryTranslatePSPath(string psPath, out string path, out bool? exists, out string errorMessage) { return PSPathUtility.TryTranslatePSPath(SessionState, psPath, out path, out exists, out errorMessage); } [SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes", Justification = "This exception is passed to PowerShell. We really don't care about the type of exception here.")] protected void WriteError(string message) { if (!String.IsNullOrEmpty(message)) { WriteError(new Exception(message)); } } protected void WriteError(Exception exception) { ErrorHandler.HandleException(exception, terminating: false); } void IErrorHandler.WriteProjectNotFoundError(string projectName, bool terminating) { var notFoundException = new ItemNotFoundException( String.Format( CultureInfo.CurrentCulture, Resources.Cmdlet_ProjectNotFound, projectName)); ErrorHandler.HandleError( new ErrorRecord( notFoundException, NuGetErrorId.ProjectNotFound, // This is your locale-agnostic error id. ErrorCategory.ObjectNotFound, projectName), terminating: terminating); } void IErrorHandler.ThrowSolutionNotOpenTerminatingError() { ErrorHandler.HandleException( new InvalidOperationException(Resources.Cmdlet_NoSolution), terminating: true, errorId: NuGetErrorId.NoActiveSolution, category: ErrorCategory.InvalidOperation); } void IErrorHandler.ThrowNoCompatibleProjectsTerminatingError() { ErrorHandler.HandleException( new InvalidOperationException(Resources.Cmdlet_NoCompatibleProjects), terminating: true, errorId: NuGetErrorId.NoCompatibleProjects, category: ErrorCategory.InvalidOperation); } void IErrorHandler.HandleError(ErrorRecord errorRecord, bool terminating) { if (terminating) { ThrowTerminatingError(errorRecord); } else { WriteError(errorRecord); } } void IErrorHandler.HandleException(Exception exception, bool terminating, string errorId, ErrorCategory category, object target) { // Only unwrap target invocation exceptions if (exception is TargetInvocationException) { exception = exception.InnerException; } var error = new ErrorRecord(exception, errorId, category, target); ErrorHandler.HandleError(error, terminating: terminating); } protected void WriteLine(string message = null) { if (Host == null) { // Host is null when running unit tests. Simply return in this case return; } if (message == null) { Host.UI.WriteLine(); } else { Host.UI.WriteLine(message); } } protected void WriteProgress(int activityId, string operation, int percentComplete) { if (IsSyncMode) { // don't bother to show progress if we are in synchronous mode return; } ProgressRecord progressRecord; // retrieve the ProgressRecord object for this particular activity id from the cache. if (ProgressRecordCache.Contains(activityId)) { progressRecord = ProgressRecordCache[activityId]; } else { progressRecord = new ProgressRecord(activityId, operation, operation); ProgressRecordCache.Add(progressRecord); } progressRecord.CurrentOperation = operation; progressRecord.PercentComplete = percentComplete; WriteProgress(progressRecord); } private void OnProgressAvailable(object sender, ProgressEventArgs e) { WriteProgress(ProgressActivityIds.DownloadPackageId, e.Operation, e.PercentComplete); } private class ProgressRecordCollection : KeyedCollection<int, ProgressRecord> { protected override int GetKeyForItem(ProgressRecord item) { return item.ActivityId; } } private void OnSendingRequest(object sender, WebRequestEventArgs e) { HttpUtility.SetUserAgent(e.Request, _psCommandsUserAgent.Value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Text; using System.Threading; using System.Collections.Generic; using Xunit; namespace System.Diagnostics.Tests { public class ProcessStreamReadTests : ProcessTestBase { [Fact] public void TestSyncErrorStream() { Process p = CreateProcess(ErrorProcessBody); p.StartInfo.RedirectStandardError = true; p.Start(); string expected = TestConsoleApp + " started error stream" + Environment.NewLine + TestConsoleApp + " closed error stream" + Environment.NewLine; Assert.Equal(expected, p.StandardError.ReadToEnd()); Assert.True(p.WaitForExit(WaitInMS)); } [Fact] public void TestAsyncErrorStream() { for (int i = 0; i < 2; ++i) { StringBuilder sb = new StringBuilder(); Process p = CreateProcess(ErrorProcessBody); p.StartInfo.RedirectStandardError = true; p.ErrorDataReceived += (s, e) => { sb.Append(e.Data); if (i == 1) { ((Process)s).CancelErrorRead(); } }; p.Start(); p.BeginErrorReadLine(); Assert.True(p.WaitForExit(WaitInMS)); p.WaitForExit(); // This ensures async event handlers are finished processing. string expected = TestConsoleApp + " started error stream" + (i == 1 ? "" : TestConsoleApp + " closed error stream"); Assert.Equal(expected, sb.ToString()); } } private static int ErrorProcessBody() { Console.Error.WriteLine(TestConsoleApp + " started error stream"); Console.Error.WriteLine(TestConsoleApp + " closed error stream"); return SuccessExitCode; } [Fact] public void TestSyncOutputStream() { Process p = CreateProcess(StreamBody); p.StartInfo.RedirectStandardOutput = true; p.Start(); string s = p.StandardOutput.ReadToEnd(); Assert.True(p.WaitForExit(WaitInMS)); Assert.Equal(TestConsoleApp + " started" + Environment.NewLine + TestConsoleApp + " closed" + Environment.NewLine, s); } [Fact] public void TestAsyncOutputStream() { for (int i = 0; i < 2; ++i) { StringBuilder sb = new StringBuilder(); Process p = CreateProcess(StreamBody); p.StartInfo.RedirectStandardOutput = true; p.OutputDataReceived += (s, e) => { sb.Append(e.Data); if (i == 1) { ((Process)s).CancelOutputRead(); } }; p.Start(); p.BeginOutputReadLine(); Assert.True(p.WaitForExit(WaitInMS)); p.WaitForExit(); // This ensures async event handlers are finished processing. string expected = TestConsoleApp + " started" + (i == 1 ? "" : TestConsoleApp + " closed"); Assert.Equal(expected, sb.ToString()); } } private static int StreamBody() { Console.WriteLine(TestConsoleApp + " started"); Console.WriteLine(TestConsoleApp + " closed"); return SuccessExitCode; } [Fact] public void TestSyncStreams() { const string expected = "This string should come as output"; Process p = CreateProcess(() => { Console.ReadLine(); return SuccessExitCode; }); p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.OutputDataReceived += (s, e) => { Assert.Equal(expected, e.Data); }; p.Start(); using (StreamWriter writer = p.StandardInput) { writer.WriteLine(expected); } Assert.True(p.WaitForExit(WaitInMS)); } [Fact] public void TestEOFReceivedWhenStdInClosed() { // This is the test for the fix of dotnet/corefx issue #13447. // // Summary of the issue: // When an application starts more than one child processes with their standard inputs redirected on Unix, // closing the standard input stream of the first child process won't unblock the 'Console.ReadLine()' call // in the first child process (it's expected to receive EOF). // // Root cause of the issue: // The file descriptor for the write end of the first child process standard input redirection pipe gets // inherited by the second child process, which makes the reference count of the pipe write end become 2. // When closing the standard input stream of the first child process, the file descriptor held by the parent // process is released, but the one inherited by the second child process is still referencing the pipe // write end, which cause the 'Console.ReadLine()' continue to be blocked in the first child process. // // Fix: // Set the O_CLOEXEC flag when creating the redirection pipes. So that no child process would inherit the // file descriptors referencing those pipes. const string ExpectedLine = "NULL"; Process p1 = CreateProcess(() => { string line = Console.ReadLine(); Console.WriteLine(line == null ? ExpectedLine : "NOT_" + ExpectedLine); return SuccessExitCode; }); Process p2 = CreateProcess(() => { Console.ReadLine(); return SuccessExitCode; }); // Start the first child process p1.StartInfo.RedirectStandardInput = true; p1.StartInfo.RedirectStandardOutput = true; p1.OutputDataReceived += (s, e) => Assert.Equal(ExpectedLine, e.Data); p1.Start(); // Start the second child process p2.StartInfo.RedirectStandardInput = true; p2.Start(); try { // Close the standard input stream of the first child process. // The first child process should be unblocked and write out 'NULL', and then exit. p1.StandardInput.Close(); Assert.True(p1.WaitForExit(WaitInMS)); } finally { // Cleanup: kill the second child process p2.Kill(); } // Cleanup Assert.True(p2.WaitForExit(WaitInMS)); p2.Dispose(); p1.Dispose(); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "There is 2 bugs in Desktop in this codepath, see: dotnet/corefx #18437 and #18436")] public void TestAsyncHalfCharacterAtATime() { var receivedOutput = false; var collectedExceptions = new List<Exception>(); Process p = CreateProcess(() => { var stdout = Console.OpenStandardOutput(); var bytes = new byte[] { 97, 0 }; //Encoding.Unicode.GetBytes("a"); for (int i = 0; i != bytes.Length; ++i) { stdout.WriteByte(bytes[i]); stdout.Flush(); Thread.Sleep(100); } return SuccessExitCode; }); p.StartInfo.RedirectStandardOutput = true; p.StartInfo.StandardOutputEncoding = Encoding.Unicode; p.OutputDataReceived += (s, e) => { try { if (!receivedOutput) { receivedOutput = true; Assert.Equal(e.Data, "a"); } } catch (Exception ex) { // This ensures that the exception in event handlers does not break // the whole unittest collectedExceptions.Add(ex); } }; p.Start(); p.BeginOutputReadLine(); Assert.True(p.WaitForExit(WaitInMS)); p.WaitForExit(); // This ensures async event handlers are finished processing. Assert.True(receivedOutput); if (collectedExceptions.Count > 0) { // Re-throw collected exceptions throw new AggregateException(collectedExceptions); } } [Fact] public void TestManyOutputLines() { const int ExpectedLineCount = 144; int nonWhitespaceLinesReceived = 0; int totalLinesReceived = 0; Process p = CreateProcess(() => { for (int i = 0; i < ExpectedLineCount; i++) { Console.WriteLine("This is line #" + i + "."); } return SuccessExitCode; }); p.StartInfo.RedirectStandardOutput = true; p.OutputDataReceived += (s, e) => { if (!string.IsNullOrWhiteSpace(e.Data)) { nonWhitespaceLinesReceived++; } totalLinesReceived++; }; p.Start(); p.BeginOutputReadLine(); Assert.True(p.WaitForExit(WaitInMS)); p.WaitForExit(); // This ensures async event handlers are finished processing. Assert.Equal(ExpectedLineCount, nonWhitespaceLinesReceived); Assert.Equal(ExpectedLineCount + 1, totalLinesReceived); } [Fact] public void TestStreamNegativeTests() { { Process p = new Process(); Assert.Throws<InvalidOperationException>(() => p.StandardOutput); Assert.Throws<InvalidOperationException>(() => p.StandardError); Assert.Throws<InvalidOperationException>(() => p.BeginOutputReadLine()); Assert.Throws<InvalidOperationException>(() => p.BeginErrorReadLine()); Assert.Throws<InvalidOperationException>(() => p.CancelOutputRead()); Assert.Throws<InvalidOperationException>(() => p.CancelErrorRead()); } { Process p = CreateProcess(StreamBody); p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.OutputDataReceived += (s, e) => {}; p.ErrorDataReceived += (s, e) => {}; p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); Assert.Throws<InvalidOperationException>(() => p.StandardOutput); Assert.Throws<InvalidOperationException>(() => p.StandardError); Assert.True(p.WaitForExit(WaitInMS)); } { Process p = CreateProcess(StreamBody); p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.OutputDataReceived += (s, e) => {}; p.ErrorDataReceived += (s, e) => {}; p.Start(); StreamReader output = p.StandardOutput; StreamReader error = p.StandardError; Assert.Throws<InvalidOperationException>(() => p.BeginOutputReadLine()); Assert.Throws<InvalidOperationException>(() => p.BeginErrorReadLine()); Assert.True(p.WaitForExit(WaitInMS)); } } } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Diagnostics; using System.Linq; using System.Text; using Microsoft.Extensions.Logging; namespace Cassandra { /// <summary> /// Represents a driver Logger /// </summary> public class Logger { // Implementation information: the Logger API has been leaked into the public API. // To avoid introducing a breaking change, we will keep the Logger as a wrapper and factory of the // actual logger private readonly ILoggerHandler _loggerHandler; public Logger(Type type) { if (Diagnostics.UseLoggerFactory) { _loggerHandler = new FactoryBasedLoggerHandler(type); } else { _loggerHandler = new TraceBasedLoggerHandler(type); } } internal Logger(ILoggerHandler handler) { _loggerHandler = handler; } public void Error(Exception ex) { _loggerHandler.Error(ex); } public void Error(string message, Exception ex = null) { _loggerHandler.Error(message, ex); } public void Error(string message, params object[] args) { _loggerHandler.Error(message, args); } public void Warning(string message, params object[] args) { _loggerHandler.Warning(message, args); } public void Info(string message, params object[] args) { _loggerHandler.Info(message, args); } public void Verbose(string message, params object[] args) { _loggerHandler.Verbose(message, args); } /// <summary> /// Represents the actual logger /// </summary> internal interface ILoggerHandler { void Error(Exception ex); void Error(string message, Exception ex = null); void Error(string message, params object[] args); void Verbose(string message, params object[] args); void Info(string message, params object[] args); void Warning(string message, params object[] args); } internal class FactoryBasedLoggerHandler : ILoggerHandler { private readonly ILogger _logger; public FactoryBasedLoggerHandler(Type type) { _logger = Diagnostics.LoggerFactory.CreateLogger(type.FullName); } public void Error(Exception ex) { _logger.LogError(0, ex, ""); } public void Error(string message, Exception ex = null) { _logger.LogError(0, ex, message); } public void Error(string message, params object[] args) { _logger.LogError(message, args); } public void Verbose(string message, params object[] args) { _logger.LogDebug(message, args); } public void Info(string message, params object[] args) { _logger.LogInformation(message, args); } public void Warning(string message, params object[] args) { _logger.LogWarning(message, args); } } internal class TraceBasedLoggerHandler : ILoggerHandler { private const string DateFormat = "MM/dd/yyyy H:mm:ss.fff zzz"; private readonly string _category; public TraceBasedLoggerHandler(Type type) { _category = type.Name; } private static string PrintStackTrace(Exception ex) { var sb = new StringBuilder(); // ReSharper disable once AssignNullToNotNullAttribute foreach (StackFrame frame in new StackTrace(ex, true).GetFrames().Skip(3)) { sb.Append(frame); } return sb.ToString(); } private static string GetExceptionAndAllInnerEx(Exception ex, StringBuilder sb = null) { var recursive = true; if (sb == null) { recursive = false; sb = new StringBuilder(); } sb.Append(string.Format("( Exception! Source {0} \n Message: {1} \n StackTrace:\n {2} ", ex.Source, ex.Message, (Diagnostics.CassandraStackTraceIncluded ? (recursive ? ex.StackTrace : PrintStackTrace(ex)) : "To display StackTrace, change Debugging.StackTraceIncluded property value to true."))); if (ex.InnerException != null) { GetExceptionAndAllInnerEx(ex.InnerException, sb); } sb.Append(")"); return sb.ToString(); } public void Error(Exception ex) { if (!Diagnostics.CassandraTraceSwitch.TraceError) { return; } if (ex == null) { return; } Trace.WriteLine( string.Format("{0} #ERROR: {1}", DateTimeOffset.Now.DateTime.ToString(DateFormat), GetExceptionAndAllInnerEx(ex)), _category); } public void Error(string msg, Exception ex = null) { if (!Diagnostics.CassandraTraceSwitch.TraceError) { return; } Trace.WriteLine( string.Format("{0} #ERROR: {1}", DateTimeOffset.Now.DateTime.ToString(DateFormat), msg + (ex != null ? "\nEXCEPTION:\n " + GetExceptionAndAllInnerEx(ex) : string.Empty)), _category); } public void Error(string message, params object[] args) { if (!Diagnostics.CassandraTraceSwitch.TraceError) { return; } if (args != null && args.Length > 0) { message = string.Format(message, args); } Trace.WriteLine(string.Format("{0} #ERROR: {1}", DateTimeOffset.Now.DateTime.ToString(DateFormat), message), _category); } public void Warning(string message, params object[] args) { if (!Diagnostics.CassandraTraceSwitch.TraceWarning) { return; } if (args != null && args.Length > 0) { message = string.Format(message, args); } Trace.WriteLine(string.Format("{0} #WARNING: {1}", DateTimeOffset.Now.DateTime.ToString(DateFormat), message), _category); } public void Info(string message, params object[] args) { if (!Diagnostics.CassandraTraceSwitch.TraceInfo) { return; } if (args != null && args.Length > 0) { message = string.Format(message, args); } Trace.WriteLine(string.Format("{0} : {1}", DateTimeOffset.Now.DateTime.ToString(DateFormat), message), _category); } public void Verbose(string message, params object[] args) { if (!Diagnostics.CassandraTraceSwitch.TraceVerbose) { return; } if (args != null && args.Length > 0) { message = string.Format(message, args); } Trace.WriteLine(string.Format("{0} {1}", DateTimeOffset.Now.DateTime.ToString(DateFormat), message), _category); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace FujiSan.WebAPI.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// 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.Globalization; namespace System.ComponentModel.DataAnnotations { /// <summary> /// DisplayAttribute is a general-purpose attribute to specify user-visible globalizable strings for types and members. /// The string properties of this class can be used either as literals or as resource identifiers into a specified /// <see cref="ResourceType" /> /// </summary> [AttributeUsage( AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Method, AllowMultiple = false)] public sealed class DisplayAttribute : Attribute { #region Member Fields private readonly LocalizableString _description = new LocalizableString("Description"); private readonly LocalizableString _groupName = new LocalizableString("GroupName"); private readonly LocalizableString _name = new LocalizableString("Name"); private readonly LocalizableString _prompt = new LocalizableString("Prompt"); private readonly LocalizableString _shortName = new LocalizableString("ShortName"); private bool? _autoGenerateField; private bool? _autoGenerateFilter; private int? _order; private Type _resourceType; #endregion #region All Constructors #endregion #region Properties /// <summary> /// Gets or sets the ShortName attribute property, which may be a resource key string. /// <para> /// Consumers must use the <see cref="GetShortName" /> method to retrieve the UI display string. /// </para> /// </summary> /// <remarks> /// The property contains either the literal, non-localized string or the resource key /// to be used in conjunction with <see cref="ResourceType" /> to configure a localized /// short name for display. /// <para> /// The <see cref="GetShortName" /> method will return either the literal, non-localized /// string or the localized string when <see cref="ResourceType" /> has been specified. /// </para> /// </remarks> /// <value> /// The short name is generally used as the grid column label for a UI element bound to the member /// bearing this attribute. A <c>null</c> or empty string is legal, and consumers must allow for that. /// </value> public string ShortName { get => _shortName.Value; set => _shortName.Value = value; } /// <summary> /// Gets or sets the Name attribute property, which may be a resource key string. /// <para> /// Consumers must use the <see cref="GetName" /> method to retrieve the UI display string. /// </para> /// </summary> /// <remarks> /// The property contains either the literal, non-localized string or the resource key /// to be used in conjunction with <see cref="ResourceType" /> to configure a localized /// name for display. /// <para> /// The <see cref="GetName" /> method will return either the literal, non-localized /// string or the localized string when <see cref="ResourceType" /> has been specified. /// </para> /// </remarks> /// <value> /// The name is generally used as the field label for a UI element bound to the member /// bearing this attribute. A <c>null</c> or empty string is legal, and consumers must allow for that. /// </value> public string Name { get => _name.Value; set => _name.Value = value; } /// <summary> /// Gets or sets the Description attribute property, which may be a resource key string. /// <para> /// Consumers must use the <see cref="GetDescription" /> method to retrieve the UI display string. /// </para> /// </summary> /// <remarks> /// The property contains either the literal, non-localized string or the resource key /// to be used in conjunction with <see cref="ResourceType" /> to configure a localized /// description for display. /// <para> /// The <see cref="GetDescription" /> method will return either the literal, non-localized /// string or the localized string when <see cref="ResourceType" /> has been specified. /// </para> /// </remarks> /// <value> /// Description is generally used as a tool tip or description a UI element bound to the member /// bearing this attribute. A <c>null</c> or empty string is legal, and consumers must allow for that. /// </value> public string Description { get => _description.Value; set => _description.Value = value; } /// <summary> /// Gets or sets the Prompt attribute property, which may be a resource key string. /// <para> /// Consumers must use the <see cref="GetPrompt" /> method to retrieve the UI display string. /// </para> /// </summary> /// <remarks> /// The property contains either the literal, non-localized string or the resource key /// to be used in conjunction with <see cref="ResourceType" /> to configure a localized /// prompt for display. /// <para> /// The <see cref="GetPrompt" /> method will return either the literal, non-localized /// string or the localized string when <see cref="ResourceType" /> has been specified. /// </para> /// </remarks> /// <value> /// A prompt is generally used as a prompt or watermark for a UI element bound to the member /// bearing this attribute. A <c>null</c> or empty string is legal, and consumers must allow for that. /// </value> public string Prompt { get => _prompt.Value; set => _prompt.Value = value; } /// <summary> /// Gets or sets the GroupName attribute property, which may be a resource key string. /// <para> /// Consumers must use the <see cref="GetGroupName" /> method to retrieve the UI display string. /// </para> /// </summary> /// <remarks> /// The property contains either the literal, non-localized string or the resource key /// to be used in conjunction with <see cref="ResourceType" /> to configure a localized /// group name for display. /// <para> /// The <see cref="GetGroupName" /> method will return either the literal, non-localized /// string or the localized string when <see cref="ResourceType" /> has been specified. /// </para> /// </remarks> /// <value> /// A group name is used for grouping fields into the UI. A <c>null</c> or empty string is legal, /// and consumers must allow for that. /// </value> public string GroupName { get => _groupName.Value; set => _groupName.Value = value; } /// <summary> /// Gets or sets the <see cref="System.Type" /> that contains the resources for <see cref="ShortName" />, /// <see cref="Name" />, <see cref="Description" />, <see cref="Prompt" />, and <see cref="GroupName" />. /// Using <see cref="ResourceType" /> along with these Key properties, allows the <see cref="GetShortName" />, /// <see cref="GetName" />, <see cref="GetDescription" />, <see cref="GetPrompt" />, and <see cref="GetGroupName" /> /// methods to return localized values. /// </summary> public Type ResourceType { get => _resourceType; set { if (_resourceType != value) { _resourceType = value; _shortName.ResourceType = value; _name.ResourceType = value; _description.ResourceType = value; _prompt.ResourceType = value; _groupName.ResourceType = value; } } } /// <summary> /// Gets or sets whether UI should be generated automatically to display this field. If this property is not /// set then the presentation layer will automatically determine whether UI should be generated. Setting this /// property allows an override of the default behavior of the presentation layer. /// <para> /// Consumers must use the <see cref="GetAutoGenerateField" /> method to retrieve the value, as this property /// getter will throw /// an exception if the value has not been set. /// </para> /// </summary> /// <exception cref="System.InvalidOperationException"> /// If the getter of this property is invoked when the value has not been explicitly set using the setter. /// </exception> public bool AutoGenerateField { get { if (!_autoGenerateField.HasValue) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.DisplayAttribute_PropertyNotSet, "AutoGenerateField", "GetAutoGenerateField")); } return _autoGenerateField.GetValueOrDefault(); } set => _autoGenerateField = value; } /// <summary> /// Gets or sets whether UI should be generated automatically to display filtering for this field. If this property is /// not /// set then the presentation layer will automatically determine whether filtering UI should be generated. Setting this /// property allows an override of the default behavior of the presentation layer. /// <para> /// Consumers must use the <see cref="GetAutoGenerateFilter" /> method to retrieve the value, as this property /// getter will throw /// an exception if the value has not been set. /// </para> /// </summary> /// <exception cref="System.InvalidOperationException"> /// If the getter of this property is invoked when the value has not been explicitly set using the setter. /// </exception> public bool AutoGenerateFilter { get { if (!_autoGenerateFilter.HasValue) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.DisplayAttribute_PropertyNotSet, "AutoGenerateFilter", "GetAutoGenerateFilter")); } return _autoGenerateFilter.GetValueOrDefault(); } set => _autoGenerateFilter = value; } /// <summary> /// Gets or sets the order in which this field should be displayed. If this property is not set then /// the presentation layer will automatically determine the order. Setting this property explicitly /// allows an override of the default behavior of the presentation layer. /// <para> /// Consumers must use the <see cref="GetOrder" /> method to retrieve the value, as this property getter will throw /// an exception if the value has not been set. /// </para> /// </summary> /// <exception cref="System.InvalidOperationException"> /// If the getter of this property is invoked when the value has not been explicitly set using the setter. /// </exception> public int Order { get { if (!_order.HasValue) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.DisplayAttribute_PropertyNotSet, "Order", "GetOrder")); } return _order.GetValueOrDefault(); } set => _order = value; } #endregion #region Methods /// <summary> /// Gets the UI display string for ShortName. /// <para> /// This can be either a literal, non-localized string provided to <see cref="ShortName" /> or the /// localized string found when <see cref="ResourceType" /> has been specified and <see cref="ShortName" /> /// represents a resource key within that resource type. /// </para> /// </summary> /// <returns> /// When <see cref="ResourceType" /> has not been specified, the value of /// <see cref="ShortName" /> will be returned. /// <para> /// When <see cref="ResourceType" /> has been specified and <see cref="ShortName" /> /// represents a resource key within that resource type, then the localized value will be returned. /// </para> /// <para> /// If <see cref="ShortName" /> is <c>null</c>, the value from <see cref="GetName" /> will be returned. /// </para> /// </returns> /// <exception cref="System.InvalidOperationException"> /// After setting both the <see cref="ResourceType" /> property and the <see cref="ShortName" /> property, /// but a public static property with a name matching the <see cref="ShortName" /> value couldn't be found /// on the <see cref="ResourceType" />. /// </exception> public string GetShortName() => _shortName.GetLocalizableValue() ?? GetName(); /// <summary> /// Gets the UI display string for Name. /// <para> /// This can be either a literal, non-localized string provided to <see cref="Name" /> or the /// localized string found when <see cref="ResourceType" /> has been specified and <see cref="Name" /> /// represents a resource key within that resource type. /// </para> /// </summary> /// <returns> /// When <see cref="ResourceType" /> has not been specified, the value of /// <see cref="Name" /> will be returned. /// <para> /// When <see cref="ResourceType" /> has been specified and <see cref="Name" /> /// represents a resource key within that resource type, then the localized value will be returned. /// </para> /// <para> /// Can return <c>null</c> and will not fall back onto other values, as it's more likely for the /// consumer to want to fall back onto the property name. /// </para> /// </returns> /// <exception cref="System.InvalidOperationException"> /// After setting both the <see cref="ResourceType" /> property and the <see cref="Name" /> property, /// but a public static property with a name matching the <see cref="Name" /> value couldn't be found /// on the <see cref="ResourceType" />. /// </exception> public string GetName() => _name.GetLocalizableValue(); /// <summary> /// Gets the UI display string for Description. /// <para> /// This can be either a literal, non-localized string provided to <see cref="Description" /> or the /// localized string found when <see cref="ResourceType" /> has been specified and <see cref="Description" /> /// represents a resource key within that resource type. /// </para> /// </summary> /// <returns> /// When <see cref="ResourceType" /> has not been specified, the value of /// <see cref="Description" /> will be returned. /// <para> /// When <see cref="ResourceType" /> has been specified and <see cref="Description" /> /// represents a resource key within that resource type, then the localized value will be returned. /// </para> /// </returns> /// <exception cref="System.InvalidOperationException"> /// After setting both the <see cref="ResourceType" /> property and the <see cref="Description" /> property, /// but a public static property with a name matching the <see cref="Description" /> value couldn't be found /// on the <see cref="ResourceType" />. /// </exception> public string GetDescription() => _description.GetLocalizableValue(); /// <summary> /// Gets the UI display string for Prompt. /// <para> /// This can be either a literal, non-localized string provided to <see cref="Prompt" /> or the /// localized string found when <see cref="ResourceType" /> has been specified and <see cref="Prompt" /> /// represents a resource key within that resource type. /// </para> /// </summary> /// <returns> /// When <see cref="ResourceType" /> has not been specified, the value of /// <see cref="Prompt" /> will be returned. /// <para> /// When <see cref="ResourceType" /> has been specified and <see cref="Prompt" /> /// represents a resource key within that resource type, then the localized value will be returned. /// </para> /// </returns> /// <exception cref="System.InvalidOperationException"> /// After setting both the <see cref="ResourceType" /> property and the <see cref="Prompt" /> property, /// but a public static property with a name matching the <see cref="Prompt" /> value couldn't be found /// on the <see cref="ResourceType" />. /// </exception> public string GetPrompt() => _prompt.GetLocalizableValue(); /// <summary> /// Gets the UI display string for GroupName. /// <para> /// This can be either a literal, non-localized string provided to <see cref="GroupName" /> or the /// localized string found when <see cref="ResourceType" /> has been specified and <see cref="GroupName" /> /// represents a resource key within that resource type. /// </para> /// </summary> /// <returns> /// When <see cref="ResourceType" /> has not been specified, the value of /// <see cref="GroupName" /> will be returned. /// <para> /// When <see cref="ResourceType" /> has been specified and <see cref="GroupName" /> /// represents a resource key within that resource type, then the localized value will be returned. /// </para> /// </returns> /// <exception cref="System.InvalidOperationException"> /// After setting both the <see cref="ResourceType" /> property and the <see cref="GroupName" /> property, /// but a public static property with a name matching the <see cref="GroupName" /> value couldn't be found /// on the <see cref="ResourceType" />. /// </exception> public string GetGroupName() => _groupName.GetLocalizableValue(); /// <summary> /// Gets the value of <see cref="AutoGenerateField" /> if it has been set, or <c>null</c>. /// </summary> /// <returns> /// When <see cref="AutoGenerateField" /> has been set returns the value of that property. /// <para> /// When <see cref="AutoGenerateField" /> has not been set returns <c>null</c>. /// </para> /// </returns> public bool? GetAutoGenerateField() => _autoGenerateField; /// <summary> /// Gets the value of <see cref="AutoGenerateFilter" /> if it has been set, or <c>null</c>. /// </summary> /// <returns> /// When <see cref="AutoGenerateFilter" /> has been set returns the value of that property. /// <para> /// When <see cref="AutoGenerateFilter" /> has not been set returns <c>null</c>. /// </para> /// </returns> public bool? GetAutoGenerateFilter() => _autoGenerateFilter; /// <summary> /// Gets the value of <see cref="Order" /> if it has been set, or <c>null</c>. /// </summary> /// <returns> /// When <see cref="Order" /> has been set returns the value of that property. /// <para> /// When <see cref="Order" /> has not been set returns <c>null</c>. /// </para> /// </returns> /// <remarks> /// When an order is not specified, presentation layers should consider using the value /// of 10000. This value allows for explicitly-ordered fields to be displayed before /// and after the fields that don't specify an order. /// </remarks> public int? GetOrder() => _order; #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 System; using System.Runtime.InteropServices; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Completion; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { [ComVisible(true)] public class AutomationObject { private readonly Workspace _workspace; internal AutomationObject(Workspace workspace) { _workspace = workspace; } public int AutoComment { get { return GetBooleanOption(FeatureOnOffOptions.AutoXmlDocCommentGeneration); } set { SetBooleanOption(FeatureOnOffOptions.AutoXmlDocCommentGeneration, value); } } public int AutoInsertAsteriskForNewLinesOfBlockComments { get { return GetBooleanOption(FeatureOnOffOptions.AutoInsertBlockCommentStartString); } set { SetBooleanOption(FeatureOnOffOptions.AutoInsertBlockCommentStartString, value); } } public int BringUpOnIdentifier { get { return GetBooleanOption(CompletionOptions.TriggerOnTypingLetters); } set { SetBooleanOption(CompletionOptions.TriggerOnTypingLetters, value); } } [Obsolete("This SettingStore option has now been deprecated in favor of CSharpClosedFileDiagnostics")] public int ClosedFileDiagnostics { get { return GetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic); } set { // Even though this option has been deprecated, we want to respect the setting if the user has explicitly turned off closed file diagnostics (which is the non-default value for 'ClosedFileDiagnostics'). // So, we invoke the setter only for value = 0. if (value == 0) { SetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, value); } } } public int CSharpClosedFileDiagnostics { get { return GetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic); } set { SetBooleanOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, value); } } public int DisplayLineSeparators { get { return GetBooleanOption(FeatureOnOffOptions.LineSeparator); } set { SetBooleanOption(FeatureOnOffOptions.LineSeparator, value); } } public int EnableHighlightRelatedKeywords { get { return GetBooleanOption(FeatureOnOffOptions.KeywordHighlighting); } set { SetBooleanOption(FeatureOnOffOptions.KeywordHighlighting, value); } } public int EnterOutliningModeOnOpen { get { return GetBooleanOption(FeatureOnOffOptions.Outlining); } set { SetBooleanOption(FeatureOnOffOptions.Outlining, value); } } public int ExtractMethod_AllowMovingDeclaration { get { return GetBooleanOption(ExtractMethodOptions.AllowMovingDeclaration); } set { SetBooleanOption(ExtractMethodOptions.AllowMovingDeclaration, value); } } public int ExtractMethod_DoNotPutOutOrRefOnStruct { get { return GetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct); } set { SetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, value); } } public int Formatting_TriggerOnBlockCompletion { get { return GetBooleanOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace); } set { SetBooleanOption(FeatureOnOffOptions.AutoFormattingOnCloseBrace, value); } } public int Formatting_TriggerOnPaste { get { return GetBooleanOption(FeatureOnOffOptions.FormatOnPaste); } set { SetBooleanOption(FeatureOnOffOptions.FormatOnPaste, value); } } public int Formatting_TriggerOnStatementCompletion { get { return GetBooleanOption(FeatureOnOffOptions.AutoFormattingOnSemicolon); } set { SetBooleanOption(FeatureOnOffOptions.AutoFormattingOnSemicolon, value); } } public int HighlightReferences { get { return GetBooleanOption(FeatureOnOffOptions.ReferenceHighlighting); } set { SetBooleanOption(FeatureOnOffOptions.ReferenceHighlighting, value); } } public int Indent_BlockContents { get { return GetBooleanOption(CSharpFormattingOptions.IndentBlock); } set { SetBooleanOption(CSharpFormattingOptions.IndentBlock, value); } } public int Indent_Braces { get { return GetBooleanOption(CSharpFormattingOptions.IndentBraces); } set { SetBooleanOption(CSharpFormattingOptions.IndentBraces, value); } } public int Indent_CaseContents { get { return GetBooleanOption(CSharpFormattingOptions.IndentSwitchCaseSection); } set { SetBooleanOption(CSharpFormattingOptions.IndentSwitchCaseSection, value); } } public int Indent_CaseLabels { get { return GetBooleanOption(CSharpFormattingOptions.IndentSwitchSection); } set { SetBooleanOption(CSharpFormattingOptions.IndentSwitchSection, value); } } public int Indent_FlushLabelsLeft { get { var option = _workspace.Options.GetOption(CSharpFormattingOptions.LabelPositioning); return option == LabelPositionOptions.LeftMost ? 1 : 0; } set { _workspace.Options = _workspace.Options.WithChangedOption(CSharpFormattingOptions.LabelPositioning, value == 1 ? LabelPositionOptions.LeftMost : LabelPositionOptions.NoIndent); } } public int Indent_UnindentLabels { get { return (int)_workspace.Options.GetOption(CSharpFormattingOptions.LabelPositioning); } set { _workspace.Options = _workspace.Options.WithChangedOption(CSharpFormattingOptions.LabelPositioning, value); } } public int InsertNewlineOnEnterWithWholeWord { get { return GetBooleanOption(CSharpCompletionOptions.AddNewLineOnEnterAfterFullyTypedWord); } set { SetBooleanOption(CSharpCompletionOptions.AddNewLineOnEnterAfterFullyTypedWord, value); } } public int NewLines_AnonymousTypeInitializer_EachMember { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForMembersInAnonymousTypes); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForMembersInAnonymousTypes, value); } } public int NewLines_Braces_AnonymousMethod { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods, value); } } public int NewLines_Braces_AnonymousTypeInitializer { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes, value); } } public int NewLines_Braces_ControlFlow { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks, value); } } public int NewLines_Braces_LambdaExpressionBody { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody, value); } } public int NewLines_Braces_Method { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInMethods); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInMethods, value); } } public int NewLines_Braces_Property { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInProperties); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInProperties, value); } } public int NewLines_Braces_Accessor { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAccessors); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInAccessors, value); } } public int NewLines_Braces_ObjectInitializer { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, value); } } public int NewLines_Braces_Type { get { return GetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInTypes); } set { SetBooleanOption(CSharpFormattingOptions.NewLinesForBracesInTypes, value); } } public int NewLines_Keywords_Catch { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForCatch); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForCatch, value); } } public int NewLines_Keywords_Else { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForElse); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForElse, value); } } public int NewLines_Keywords_Finally { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForFinally); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForFinally, value); } } public int NewLines_ObjectInitializer_EachMember { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForMembersInObjectInit); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForMembersInObjectInit, value); } } public int NewLines_QueryExpression_EachClause { get { return GetBooleanOption(CSharpFormattingOptions.NewLineForClausesInQuery); } set { SetBooleanOption(CSharpFormattingOptions.NewLineForClausesInQuery, value); } } public int Refactoring_Verification_Enabled { get { return GetBooleanOption(FeatureOnOffOptions.RefactoringVerification); } set { SetBooleanOption(FeatureOnOffOptions.RefactoringVerification, value); } } public int RenameSmartTagEnabled { get { return GetBooleanOption(FeatureOnOffOptions.RenameTracking); } set { SetBooleanOption(FeatureOnOffOptions.RenameTracking, value); } } public int RenameTrackingPreview { get { return GetBooleanOption(FeatureOnOffOptions.RenameTrackingPreview); } set { SetBooleanOption(FeatureOnOffOptions.RenameTrackingPreview, value); } } public int ShowKeywords { get { return GetBooleanOption(CompletionOptions.IncludeKeywords); } set { SetBooleanOption(CompletionOptions.IncludeKeywords, value); } } public int ShowSnippets { get { return GetBooleanOption(CSharpCompletionOptions.IncludeSnippets); } set { SetBooleanOption(CSharpCompletionOptions.IncludeSnippets, value); } } public int SortUsings_PlaceSystemFirst { get { return GetBooleanOption(OrganizerOptions.PlaceSystemNamespaceFirst); } set { SetBooleanOption(OrganizerOptions.PlaceSystemNamespaceFirst, value); } } public int AddImport_SuggestForTypesInReferenceAssemblies { get { return GetBooleanOption(AddImportOptions.SuggestForTypesInReferenceAssemblies); } set { SetBooleanOption(AddImportOptions.SuggestForTypesInReferenceAssemblies, value); } } public int AddImport_SuggestForTypesInNuGetPackages { get { return GetBooleanOption(AddImportOptions.SuggestForTypesInNuGetPackages); } set { SetBooleanOption(AddImportOptions.SuggestForTypesInNuGetPackages, value); } } public int Space_AfterBasesColon { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration, value); } } public int Space_AfterCast { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterCast); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterCast, value); } } public int Space_AfterComma { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterComma); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterComma, value); } } public int Space_AfterDot { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterDot); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterDot, value); } } public int Space_AfterMethodCallName { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterMethodCallName); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterMethodCallName, value); } } public int Space_AfterMethodDeclarationName { get { return GetBooleanOption(CSharpFormattingOptions.SpacingAfterMethodDeclarationName); } set { SetBooleanOption(CSharpFormattingOptions.SpacingAfterMethodDeclarationName, value); } } public int Space_AfterSemicolonsInForStatement { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement, value); } } public int Space_AroundBinaryOperator { get { var option = _workspace.Options.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator); return option == BinaryOperatorSpacingOptions.Single ? 1 : 0; } set { var option = value == 1 ? BinaryOperatorSpacingOptions.Single : BinaryOperatorSpacingOptions.Ignore; _workspace.Options = _workspace.Options.WithChangedOption(CSharpFormattingOptions.SpacingAroundBinaryOperator, option); } } public int Space_BeforeBasesColon { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration, value); } } public int Space_BeforeComma { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeComma); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeComma, value); } } public int Space_BeforeDot { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeDot); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeDot, value); } } public int Space_BeforeOpenSquare { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeOpenSquareBracket); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeOpenSquareBracket, value); } } public int Space_BeforeSemicolonsInForStatement { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement, value); } } public int Space_BetweenEmptyMethodCallParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses, value); } } public int Space_BetweenEmptyMethodDeclarationParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses, value); } } public int Space_BetweenEmptySquares { get { return GetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets); } set { SetBooleanOption(CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets, value); } } public int Space_InControlFlowConstruct { get { return GetBooleanOption(CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword); } set { SetBooleanOption(CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword, value); } } public int Space_WithinCastParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinCastParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinCastParentheses, value); } } public int Space_WithinExpressionParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinExpressionParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinExpressionParentheses, value); } } public int Space_WithinMethodCallParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodCallParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodCallParentheses, value); } } public int Space_WithinMethodDeclarationParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis, value); } } public int Space_WithinOtherParentheses { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinOtherParentheses); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinOtherParentheses, value); } } public int Space_WithinSquares { get { return GetBooleanOption(CSharpFormattingOptions.SpaceWithinSquareBrackets); } set { SetBooleanOption(CSharpFormattingOptions.SpaceWithinSquareBrackets, value); } } public int Style_PreferIntrinsicPredefinedTypeKeywordInDeclaration { get { return GetBooleanOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration); } set { SetBooleanOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, value); } } public int Style_PreferIntrinsicPredefinedTypeKeywordInMemberAccess { get { return GetBooleanOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess); } set { SetBooleanOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, value); } } public string Style_NamingPreferences { get { return _workspace.Options.GetOption(SimplificationOptions.NamingPreferences, LanguageNames.CSharp); } set { _workspace.Options = _workspace.Options.WithChangedOption(SimplificationOptions.NamingPreferences, LanguageNames.CSharp, value); } } public string Style_QualifyFieldAccess { get { return GetXmlOption(CodeStyleOptions.QualifyFieldAccess); } set { SetXmlOption(CodeStyleOptions.QualifyFieldAccess, value); } } public string Style_QualifyPropertyAccess { get { return GetXmlOption(CodeStyleOptions.QualifyPropertyAccess); } set { SetXmlOption(CodeStyleOptions.QualifyPropertyAccess, value); } } public string Style_QualifyMethodAccess { get { return GetXmlOption(CodeStyleOptions.QualifyMethodAccess); } set { SetXmlOption(CodeStyleOptions.QualifyMethodAccess, value); } } public string Style_QualifyEventAccess { get { return GetXmlOption(CodeStyleOptions.QualifyEventAccess); } set { SetXmlOption(CodeStyleOptions.QualifyEventAccess, value); } } public int Style_UseVarWhenDeclaringLocals { get { return GetBooleanOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals); } set { SetBooleanOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals, value); } } public string Style_UseImplicitTypeWherePossible { get { return GetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeWherePossible); } set { SetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeWherePossible, value); } } public string Style_UseImplicitTypeWhereApparent { get { return GetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent); } set { SetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, value); } } public string Style_UseImplicitTypeForIntrinsicTypes { get { return GetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes); } set { SetXmlOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, value); } } public int Wrapping_IgnoreSpacesAroundBinaryOperators { get { return (int)_workspace.Options.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator); } set { _workspace.Options = _workspace.Options.WithChangedOption(CSharpFormattingOptions.SpacingAroundBinaryOperator, value); } } public int Wrapping_IgnoreSpacesAroundVariableDeclaration { get { return GetBooleanOption(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration); } set { SetBooleanOption(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration, value); } } public int Wrapping_KeepStatementsOnSingleLine { get { return GetBooleanOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine); } set { SetBooleanOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, value); } } public int Wrapping_PreserveSingleLine { get { return GetBooleanOption(CSharpFormattingOptions.WrappingPreserveSingleLine); } set { SetBooleanOption(CSharpFormattingOptions.WrappingPreserveSingleLine, value); } } private int GetBooleanOption(Option<bool> key) { return _workspace.Options.GetOption(key) ? 1 : 0; } private int GetBooleanOption(PerLanguageOption<bool> key) { return _workspace.Options.GetOption(key, LanguageNames.CSharp) ? 1 : 0; } private void SetBooleanOption(Option<bool> key, int value) { _workspace.Options = _workspace.Options.WithChangedOption(key, value != 0); } private void SetBooleanOption(PerLanguageOption<bool> key, int value) { _workspace.Options = _workspace.Options.WithChangedOption(key, LanguageNames.CSharp, value != 0); } private int GetBooleanOption(PerLanguageOption<bool?> key) { var option = _workspace.Options.GetOption(key, LanguageNames.CSharp); if (!option.HasValue) { return -1; } return option.Value ? 1 : 0; } private string GetXmlOption(Option<CodeStyleOption<bool>> option) { return _workspace.Options.GetOption(option).ToXElement().ToString(); } private void SetBooleanOption(PerLanguageOption<bool?> key, int value) { bool? boolValue = (value < 0) ? (bool?)null : (value > 0); _workspace.Options = _workspace.Options.WithChangedOption(key, LanguageNames.CSharp, boolValue); } private string GetXmlOption(PerLanguageOption<CodeStyleOption<bool>> option) { return _workspace.Options.GetOption(option, LanguageNames.CSharp).ToXElement().ToString(); } private void SetXmlOption(Option<CodeStyleOption<bool>> option, string value) { var convertedValue = CodeStyleOption<bool>.FromXElement(XElement.Parse(value)); _workspace.Options = _workspace.Options.WithChangedOption(option, convertedValue); } private void SetXmlOption(PerLanguageOption<CodeStyleOption<bool>> option, string value) { var convertedValue = CodeStyleOption<bool>.FromXElement(XElement.Parse(value)); _workspace.Options = _workspace.Options.WithChangedOption(option, LanguageNames.CSharp, convertedValue); } } }
using System; using System.Linq; using System.Reflection; using System.Collections.Generic; using System.Collections.ObjectModel; using UnityEngine.Rendering; namespace UnityEngine.Experimental.Rendering.HDPipeline { [Serializable] public enum SkyResolution { SkyResolution128 = 128, SkyResolution256 = 256, SkyResolution512 = 512, SkyResolution1024 = 1024, SkyResolution2048 = 2048, SkyResolution4096 = 4096 } public enum EnvironementUpdateMode { OnChanged = 0, OnDemand, Realtime } public class BuiltinSkyParameters { public Matrix4x4 pixelCoordToViewDirMatrix; public Vector4 screenSize; public CommandBuffer commandBuffer; public Light sunLight; public RTHandleSystem.RTHandle colorBuffer; public RTHandleSystem.RTHandle depthBuffer; public HDCamera hdCamera; public DebugDisplaySettings debugSettings; public static RenderTargetIdentifier nullRT = -1; } public class SkyManager { Material m_StandardSkyboxMaterial; // This is the Unity standard skybox material. Used to pass the correct cubemap to Enlighten. Material m_BlitCubemapMaterial; Material m_OpaqueAtmScatteringMaterial; SphericalHarmonicsL2 m_BlackAmbientProbe = new SphericalHarmonicsL2(); bool m_UpdateRequired = false; // This is the sky used for rendering in the main view. // It will also be used for lighting if no lighting override sky is setup. // Ambient Probe: Only used if Ambient Mode is set to dynamic in the Visual Environment component. Updated according to the Update Mode parameter. // Sky Reflection Probe : Always used and updated according to the Update Mode parameter. SkyUpdateContext m_VisualSky = new SkyUpdateContext(); // This is optional and is used only to compute ambient probe and sky reflection // Ambient Probe and Sky Reflection follow the same rule as visual sky SkyUpdateContext m_LightingOverrideSky = new SkyUpdateContext(); // We keep a separate context for preview so that it does not interfere with the main scene in editor context. SkyUpdateContext m_PreviewSky = new SkyUpdateContext(); SkyUpdateContext m_CurrentSky; // The sky rendering contexts holds the render textures used by the sky system. SkyRenderingContext m_SkyRenderingContext; // Sky used for static lighting. It will be used for ambient lighting if Ambient Mode is set to Static (even when realtime GI is enabled) // It will also be used for lightmap and light probe baking SkyUpdateContext m_StaticLightingSky = new SkyUpdateContext(); // We need to have a separate rendering context for the static lighting sky because we have to keep it alive regardless of the state of visual/override sky SkyRenderingContext m_StaticLightingSkyRenderingContext; // This interpolation volume stack is used to interpolate the lighting override separately from the visual sky. // If a sky setting is present in this volume then it will be used for lighting override. VolumeStack m_LightingOverrideVolumeStack; LayerMask m_LightingOverrideLayerMask = -1; static Dictionary<int, Type> m_SkyTypesDict = null; public static Dictionary<int, Type> skyTypesDict { get { if (m_SkyTypesDict == null) UpdateSkyTypes(); return m_SkyTypesDict; } } public Texture skyReflection { get { return m_SkyRenderingContext.reflectionTexture; } } // This list will hold the static lighting sky that should be used for baking ambient probe. // In practice we will always use the last one registered but we use a list to be able to roll back to the previous one once the user deletes the superfluous instances. private static List<StaticLightingSky> m_StaticLightingSkies = new List<StaticLightingSky>(); #if UNITY_EDITOR // For Preview windows we want to have a 'fixed' sky, so we can display chrome metal and have always the same look ProceduralSky m_DefaultPreviewSky; #endif public SkyManager() { #if UNITY_EDITOR #if UNITY_2019_2_OR_NEWER UnityEditor.Lightmapping.bakeStarted += OnBakeStarted; #else UnityEditor.Lightmapping.started += OnBakeStarted; #endif #endif } ~SkyManager() { #if UNITY_EDITOR #if UNITY_2019_2_OR_NEWER UnityEditor.Lightmapping.bakeStarted -= OnBakeStarted; #else UnityEditor.Lightmapping.started -= OnBakeStarted; #endif #endif } SkySettings GetSkySetting(VolumeStack stack) { var visualEnv = stack.GetComponent<VisualEnvironment>(); int skyID = visualEnv.skyType.value; Type skyType; if (skyTypesDict.TryGetValue(skyID, out skyType)) { return (SkySettings)stack.GetComponent(skyType); } else { return null; } } static void UpdateSkyTypes() { if (m_SkyTypesDict == null) { m_SkyTypesDict = new Dictionary<int, Type>(); var skyTypes = CoreUtils.GetAllTypesDerivedFrom<SkySettings>().Where(t => !t.IsAbstract); foreach (Type skyType in skyTypes) { var uniqueIDs = skyType.GetCustomAttributes(typeof(SkyUniqueID), false); if (uniqueIDs.Length == 0) { Debug.LogWarningFormat("Missing attribute SkyUniqueID on class {0}. Class won't be registered as an available sky.", skyType); } else { int uniqueID = ((SkyUniqueID)uniqueIDs[0]).uniqueID; if (uniqueID == 0) { Debug.LogWarningFormat("0 is a reserved SkyUniqueID and is used in class {0}. Class won't be registered as an available sky.", skyType); continue; } Type value; if (m_SkyTypesDict.TryGetValue(uniqueID, out value)) { Debug.LogWarningFormat("SkyUniqueID {0} used in class {1} is already used in class {2}. Class won't be registered as an available sky.", uniqueID, skyType, value); continue; } m_SkyTypesDict.Add(uniqueID, skyType); } } } } public void UpdateCurrentSkySettings(HDCamera hdCamera) { #if UNITY_EDITOR if (HDUtils.IsRegularPreviewCamera(hdCamera.camera)) { m_PreviewSky.skySettings = GetDefaultPreviewSkyInstance(); m_CurrentSky = m_PreviewSky; } else #endif { m_VisualSky.skySettings = GetSkySetting(VolumeManager.instance.stack); m_CurrentSky = m_VisualSky; } // Update needs to happen before testing if the component is active other internal data structure are not properly updated yet. VolumeManager.instance.Update(m_LightingOverrideVolumeStack, hdCamera.volumeAnchor, m_LightingOverrideLayerMask); if (VolumeManager.instance.IsComponentActiveInMask<VisualEnvironment>(m_LightingOverrideLayerMask)) { SkySettings newSkyOverride = GetSkySetting(m_LightingOverrideVolumeStack); if (m_LightingOverrideSky.skySettings != null && newSkyOverride == null) { // When we switch from override to no override, we need to make sure that the visual sky will actually be properly re-rendered. // Resetting the visual sky hash will ensure that. m_VisualSky.skyParametersHash = -1; } m_LightingOverrideSky.skySettings = newSkyOverride; m_CurrentSky = m_LightingOverrideSky; } else { m_LightingOverrideSky.skySettings = null; } } // Sets the global MIP-mapped cubemap '_SkyTexture' in the shader. // The texture being set is the sky (environment) map pre-convolved with GGX. public void SetGlobalSkyTexture(CommandBuffer cmd) { cmd.SetGlobalTexture(HDShaderIDs._SkyTexture, skyReflection); float mipCount = Mathf.Clamp(Mathf.Log((float)skyReflection.width, 2.0f) + 1, 0.0f, 6.0f); cmd.SetGlobalFloat(HDShaderIDs._SkyTextureMipCount, mipCount); } #if UNITY_EDITOR ProceduralSky GetDefaultPreviewSkyInstance() { if (m_DefaultPreviewSky == null) { m_DefaultPreviewSky = ScriptableObject.CreateInstance<ProceduralSky>(); } return m_DefaultPreviewSky; } #endif public void Build(HDRenderPipelineAsset hdAsset, IBLFilterBSDF[] iblFilterBSDFArray) { m_SkyRenderingContext = new SkyRenderingContext(iblFilterBSDFArray, (int)hdAsset.currentPlatformRenderPipelineSettings.lightLoopSettings.skyReflectionSize, true); m_StandardSkyboxMaterial = CoreUtils.CreateEngineMaterial(hdAsset.renderPipelineResources.shaders.skyboxCubemapPS); m_BlitCubemapMaterial = CoreUtils.CreateEngineMaterial(hdAsset.renderPipelineResources.shaders.blitCubemapPS); m_OpaqueAtmScatteringMaterial = CoreUtils.CreateEngineMaterial(hdAsset.renderPipelineResources.shaders.opaqueAtmosphericScatteringPS); m_LightingOverrideVolumeStack = VolumeManager.instance.CreateStack(); m_LightingOverrideLayerMask = hdAsset.currentPlatformRenderPipelineSettings.lightLoopSettings.skyLightingOverrideLayerMask; m_StaticLightingSkyRenderingContext = new SkyRenderingContext(iblFilterBSDFArray, (int)hdAsset.currentPlatformRenderPipelineSettings.lightLoopSettings.skyReflectionSize, false); } public void Cleanup() { CoreUtils.Destroy(m_StandardSkyboxMaterial); CoreUtils.Destroy(m_BlitCubemapMaterial); CoreUtils.Destroy(m_OpaqueAtmScatteringMaterial); m_VisualSky.Cleanup(); m_PreviewSky.Cleanup(); m_LightingOverrideSky.Cleanup(); m_SkyRenderingContext.Cleanup(); #if UNITY_EDITOR CoreUtils.Destroy(m_DefaultPreviewSky); m_StaticLightingSky.Cleanup(); m_StaticLightingSkyRenderingContext.Cleanup(); #endif } public bool IsLightingSkyValid() { return m_CurrentSky.IsValid(); } public bool IsVisualSkyValid() { return m_VisualSky.IsValid(); } Texture GetStaticLightingTexture() { StaticLightingSky staticLightingSky = GetStaticLightingSky(); if (staticLightingSky != null) { return m_StaticLightingSky.IsValid() ? (Texture)m_StaticLightingSkyRenderingContext.cubemapRT : CoreUtils.blackCubeTexture; } else { return CoreUtils.blackCubeTexture; } } SphericalHarmonicsL2 GetStaticLightingAmbientProbe() { StaticLightingSky staticLightingSky = GetStaticLightingSky(); if (staticLightingSky != null) { return m_StaticLightingSky.IsValid() ? m_StaticLightingSkyRenderingContext.ambientProbe : m_BlackAmbientProbe; } else { return m_BlackAmbientProbe; } } void BlitCubemap(CommandBuffer cmd, Cubemap source, RenderTexture dest) { var propertyBlock = new MaterialPropertyBlock(); for (int i = 0; i < 6; ++i) { CoreUtils.SetRenderTarget(cmd, dest, ClearFlag.None, 0, (CubemapFace)i); propertyBlock.SetTexture("_MainTex", source); propertyBlock.SetFloat("_faceIndex", (float)i); cmd.DrawProcedural(Matrix4x4.identity, m_BlitCubemapMaterial, 0, MeshTopology.Triangles, 3, 1, propertyBlock); } // Generate mipmap for our cubemap Debug.Assert(dest.autoGenerateMips == false); cmd.GenerateMips(dest); } public void RequestEnvironmentUpdate() { m_UpdateRequired = true; } public void UpdateEnvironment(HDCamera hdCamera, Light sunLight, CommandBuffer cmd) { // WORKAROUND for building the player. // When building the player, for some reason we end up in a state where frameCount is not updated but all currently setup shader texture are reset to null // resulting in a rendering error (compute shader property not bound) that makes the player building fails... // So we just check if the texture is bound here so that we can setup a pink one to avoid the error without breaking half the world. if (Shader.GetGlobalTexture(HDShaderIDs._SkyTexture) == null) cmd.SetGlobalTexture(HDShaderIDs._SkyTexture, CoreUtils.magentaCubeTexture); bool isRegularPreview = HDUtils.IsRegularPreviewCamera(hdCamera.camera); SkyAmbientMode ambientMode = VolumeManager.instance.stack.GetComponent<VisualEnvironment>().skyAmbientMode.value; // Preview should never use dynamic ambient or they will conflict with main view (async readback of sky texture will update ambient probe for main view one frame later) if (isRegularPreview) ambientMode = SkyAmbientMode.Static; m_SkyRenderingContext.UpdateEnvironment(m_CurrentSky, hdCamera, sunLight, m_UpdateRequired, ambientMode == SkyAmbientMode.Dynamic, cmd); StaticLightingSky staticLightingSky = GetStaticLightingSky(); // We don't want to update the static sky during preview because it contains custom lights that may change the result. // The consequence is that previews will use main scene static lighting but we consider this to be acceptable. if (staticLightingSky != null && !isRegularPreview) { m_StaticLightingSky.skySettings = staticLightingSky.skySettings; m_StaticLightingSkyRenderingContext.UpdateEnvironment(m_StaticLightingSky, hdCamera, sunLight, false, true, cmd); } bool useRealtimeGI = true; #if UNITY_EDITOR useRealtimeGI = UnityEditor.Lightmapping.realtimeGI; #endif // Working around GI current system // When using baked lighting, setting up the ambient probe should be sufficient => We only need to update RenderSettings.ambientProbe with either the static or visual sky ambient probe (computed from GPU) // When using real time GI. Enlighten will pull sky information from Skybox material. So in order for dynamic GI to work, we update the skybox material texture and then set the ambient mode to SkyBox // Problem: We can't check at runtime if realtime GI is enabled so we need to take extra care (see useRealtimeGI usage below) RenderSettings.ambientMode = AmbientMode.Custom; // Needed to specify ourselves the ambient probe (this will update internal ambient probe data passed to shaders) if (ambientMode == SkyAmbientMode.Static) { RenderSettings.ambientProbe = GetStaticLightingAmbientProbe(); m_StandardSkyboxMaterial.SetTexture("_Tex", GetStaticLightingTexture()); } else { RenderSettings.ambientProbe = m_SkyRenderingContext.ambientProbe; // Workaround in the editor: // When in the editor, if we use baked lighting, we need to setup the skybox material with the static lighting texture otherwise when baking, the dynamic texture will be used if (useRealtimeGI) { m_StandardSkyboxMaterial.SetTexture("_Tex", m_CurrentSky.IsValid() ? (Texture)m_SkyRenderingContext.cubemapRT : CoreUtils.blackCubeTexture); } else { m_StandardSkyboxMaterial.SetTexture("_Tex", GetStaticLightingTexture()); } } // This is only needed if we use realtime GI otherwise enlighten won't get the right sky information RenderSettings.skybox = m_StandardSkyboxMaterial; // Setup this material as the default to be use in RenderSettings RenderSettings.ambientIntensity = 1.0f; RenderSettings.ambientMode = AmbientMode.Skybox; // Force skybox for our HDRI RenderSettings.reflectionIntensity = 1.0f; RenderSettings.customReflection = null; m_UpdateRequired = false; SetGlobalSkyTexture(cmd); if (IsLightingSkyValid()) { cmd.SetGlobalInt(HDShaderIDs._EnvLightSkyEnabled, 1); } else { cmd.SetGlobalInt(HDShaderIDs._EnvLightSkyEnabled, 0); } } public void RenderSky(HDCamera camera, Light sunLight, RTHandleSystem.RTHandle colorBuffer, RTHandleSystem.RTHandle depthBuffer, DebugDisplaySettings debugSettings, CommandBuffer cmd) { m_SkyRenderingContext.RenderSky(m_VisualSky, camera, sunLight, colorBuffer, depthBuffer, debugSettings, cmd); } public void RenderOpaqueAtmosphericScattering(CommandBuffer cmd, HDCamera hdCamera, RTHandleSystem.RTHandle colorBuffer, RTHandleSystem.RTHandle depthBuffer, Matrix4x4 pixelCoordToViewDirWS, bool isMSAA) { using (new ProfilingSample(cmd, "Opaque Atmospheric Scattering")) { // FIXME: 24B GC pressure var propertyBlock = new MaterialPropertyBlock(); propertyBlock.SetMatrix(HDShaderIDs._PixelCoordToViewDirWS, pixelCoordToViewDirWS); HDUtils.DrawFullScreen(cmd, m_OpaqueAtmScatteringMaterial, colorBuffer, depthBuffer, propertyBlock, isMSAA? 1 : 0); } } static public StaticLightingSky GetStaticLightingSky() { if (m_StaticLightingSkies.Count == 0) return null; else return m_StaticLightingSkies[m_StaticLightingSkies.Count - 1]; } static public void RegisterStaticLightingSky(StaticLightingSky staticLightingSky) { if (!m_StaticLightingSkies.Contains(staticLightingSky)) { if (m_StaticLightingSkies.Count != 0) { Debug.LogWarning("One Static Lighting Sky component was already set for baking, only the latest one will be used."); } m_StaticLightingSkies.Add(staticLightingSky); } } static public void UnRegisterStaticLightingSky(StaticLightingSky staticLightingSky) { m_StaticLightingSkies.Remove(staticLightingSky); } public Texture2D ExportSkyToTexture() { if (!m_VisualSky.IsValid()) { Debug.LogError("Cannot export sky to a texture, no Sky is setup."); return null; } RenderTexture skyCubemap = m_SkyRenderingContext.cubemapRT; int resolution = skyCubemap.width; var tempRT = new RenderTexture(resolution * 6, resolution, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear) { dimension = TextureDimension.Tex2D, useMipMap = false, autoGenerateMips = false, filterMode = FilterMode.Trilinear }; tempRT.Create(); var temp = new Texture2D(resolution * 6, resolution, TextureFormat.RGBAFloat, false); var result = new Texture2D(resolution * 6, resolution, TextureFormat.RGBAFloat, false); // Note: We need to invert in Y the cubemap faces because the current sky cubemap is inverted (because it's a RT) // So to invert it again so that it's a proper cubemap image we need to do it in several steps because ReadPixels does not have scale parameters: // - Convert the cubemap into a 2D texture // - Blit and invert it to a temporary target. // - Read this target again into the result texture. int offset = 0; for (int i = 0; i < 6; ++i) { UnityEngine.Graphics.SetRenderTarget(skyCubemap, 0, (CubemapFace)i); temp.ReadPixels(new Rect(0, 0, resolution, resolution), offset, 0); temp.Apply(); offset += resolution; } // Flip texture. UnityEngine.Graphics.Blit(temp, tempRT, new Vector2(1.0f, -1.0f), new Vector2(0.0f, 0.0f)); result.ReadPixels(new Rect(0, 0, resolution * 6, resolution), 0, 0); result.Apply(); UnityEngine.Graphics.SetRenderTarget(null); CoreUtils.Destroy(temp); CoreUtils.Destroy(tempRT); return result; } #if UNITY_EDITOR void OnBakeStarted() { var hdrp = RenderPipelineManager.currentPipeline as HDRenderPipeline; if (hdrp == null) return; // Happens sometime in the tests. if (m_StandardSkyboxMaterial == null) m_StandardSkyboxMaterial = CoreUtils.CreateEngineMaterial(hdrp.asset.renderPipelineResources.shaders.skyboxCubemapPS); // At the start of baking we need to update the GI system with the static lighting sky in order for lightmaps and probes to be baked with it. var staticLightingSky = GetStaticLightingSky(); if (staticLightingSky != null) { m_StandardSkyboxMaterial.SetTexture("_Tex", m_StaticLightingSky.IsValid() ? (Texture)m_StaticLightingSkyRenderingContext.cubemapRT : CoreUtils.blackCubeTexture); } else { m_StandardSkyboxMaterial.SetTexture("_Tex", CoreUtils.blackCubeTexture); } RenderSettings.skybox = m_StandardSkyboxMaterial; // Setup this material as the default to be use in RenderSettings RenderSettings.ambientIntensity = 1.0f; RenderSettings.ambientMode = AmbientMode.Skybox; // Force skybox for our HDRI RenderSettings.reflectionIntensity = 1.0f; RenderSettings.customReflection = null; DynamicGI.UpdateEnvironment(); } #endif } }
/* Copyright (c) Citrix Systems Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Windows.Forms; using XenAdmin.Actions; using XenAPI; using XenAdmin.Core; namespace XenAdmin.Dialogs { public partial class ResolvingSubjectsDialog : XenDialogBase { private Pool pool; private AddRemoveSubjectsAction resolveAction; private ResolvingSubjectsDialog() { InitializeComponent(); } /// <summary> /// /// </summary> /// <param name="pool">The pool or pool-of-one we are adding users to</param> public ResolvingSubjectsDialog(Pool pool) { InitializeComponent(); this.pool = pool; labelTopBlurb.Text = string.Format(labelTopBlurb.Text, Helpers.GetName(pool).Ellipsise(80)); } private void BeginResolve() { if (textBoxUserNames.Text.Trim().Length == 0) return; entryListView.Visible = true; progressBar1.Visible = true; textBoxUserNames.Enabled = false; buttonGrantAccess.Enabled = false; LabelStatus.Visible = true; textBoxUserNames.Dock = DockStyle.Fill; List<string> lookup = new List<string>(); string[] firstSplit = textBoxUserNames.Text.Split(','); foreach (string s in firstSplit) { lookup.AddRange(s.Split(';')); } Dictionary<string, object> nameDict = new Dictionary<string, object>(); foreach (string name in lookup) { string cleanName = name.Trim(); if (cleanName.Length == 0) continue; if (!nameDict.ContainsKey(cleanName)) nameDict.Add(cleanName, null); } List<String> nameList = new List<string>(); foreach (string s in nameDict.Keys) nameList.Add(s); // start the resolve foreach (string name in nameList) { ListViewItemSubjectWrapper i = new ListViewItemSubjectWrapper(name); entryListView.Items.Add(i); } resolveAction = new AddRemoveSubjectsAction(pool, nameList, new List<Subject>()); resolveAction.NameResolveComplete += new AddRemoveSubjectsAction.NameResolvedEventHandler(resolveAction_NameResolveComplete); resolveAction.AllResolveComplete += new AddRemoveSubjectsAction.AllNamesResolvedEventHandler(resolveAction_AllResolveComplete); resolveAction.SubjectAddComplete += new AddRemoveSubjectsAction.SubjectAddedEventHandler(resolveAction_SubjectAddComplete); resolveAction.Completed += addAction_Completed; resolveAction.RunAsync(); } private void updateProgress() { progressBar1.Value = resolveAction.PercentComplete; } void resolveAction_NameResolveComplete(object sender, string enteredName, string resolvedName, string sid, Exception exception) { Program.Invoke(this, delegate { foreach (ListViewItemSubjectWrapper i in entryListView.Items) { if (i.EnteredName == enteredName) { i.ResolveException = exception; i.ResolvedName = resolvedName; i.sid = sid; i.Update(); break; } } updateProgress(); }); } void resolveAction_AllResolveComplete() { Program.Invoke(this, delegate { LabelStatus.Text = Messages.ADDING_RESOLVED_TO_ACCESS_LIST; }); } void resolveAction_SubjectAddComplete(object sender, Subject subject, Exception exception) { Program.Invoke(this, delegate { foreach (ListViewItemSubjectWrapper i in entryListView.Items) { if (i.sid == subject.subject_identifier) { i.AddException = exception; i.Subject = subject; i.Update(); break; } } updateProgress(); }); } private void addAction_Completed(ActionBase sender) { Program.Invoke(this, delegate { if (resolveAction.Cancelled) { LabelStatus.Text = Messages.CANCELLED_BY_USER; foreach (ListViewItemSubjectWrapper i in entryListView.Items) i.Cancel(); } else { LabelStatus.Text = anyFailures() ? Messages.COMPLETED_WITH_ERRORS : Messages.COMPLETED; } updateProgress(); SwitchCloseToCancel(); progressBar1.Value = progressBar1.Maximum; }); } private bool anyFailures() { foreach (ListViewItemSubjectWrapper i in entryListView.Items) { if (i.Failed) return true; } return false; } private void SwitchCloseToCancel() { Program.AssertOnEventThread(); AcceptButton = ButtonCancel; CancelButton = ButtonCancel; ButtonCancel.Text = Messages.CLOSE; } protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { if (resolveAction != null && (!resolveAction.Cancelled || !resolveAction.Cancelling)) resolveAction.Cancel(); base.OnClosing(e); } private class ListViewItemSubjectWrapper : ListViewItem { public Subject Subject; public string sid; public string ResolvedName; private string enteredName; public string EnteredName { get { return enteredName; } } private Exception resolveException; public Exception ResolveException { get { return resolveException; } set { resolveException = value; } } private Exception addException; public Exception AddException { get { return addException; } set { addException = value; } } private bool IsResolved { get { return !String.IsNullOrEmpty(sid); } } public bool Failed { get { return addException != null || resolveException != null; } } public ListViewItemSubjectWrapper(string EnteredName) : base(EnteredName) { enteredName = EnteredName; // Resolve status column SubItems.Add(resolveStatus()); // Grant status column SubItems.Add(""); } private string resolveStatus() { if (IsResolved) { // Resolved return String.Format(Messages.RESOLVED_AS, ResolvedName ?? Messages.UNKNOWN_AD_USER); } else if (resolveException != null) { // Resolve Failed return Messages.AD_COULD_NOT_RESOLVE_SUFFIX; } // Resolving return Messages.AD_RESOLVING_SUFFIX; } private string grantStatus() { if (addException != null || resolveException != null) return Messages.FAILED_TO_ADD_TO_ACCESS_LIST; // If we haven't resolved yet and there are no exceptions we show a blank status - hasn't reached grant stage yet if (!IsResolved) return ""; return Subject == null ? Messages.ADDING_TO_ACCESS_LIST : Messages.ADDED_TO_ACCESS_LIST; } public void Update() { SubItems[1].Text = resolveStatus(); SubItems[2].Text = grantStatus(); } public void Cancel() { if (!IsResolved && resolveException == null) resolveException = new CancelledException(); if (Subject == null && addException == null) addException = new CancelledException(); Update(); } } private void buttonGrantAccess_Click(object sender, EventArgs e) { BeginResolve(); } private void setResolveEnable() { buttonGrantAccess.Enabled = textBoxUserNames.Text != ""; } private void textBoxUserNames_TextChanged(object sender, EventArgs e) { Program.AssertOnEventThread(); setResolveEnable(); } private void textBoxUserNames_KeyUp(object sender, KeyEventArgs e) { //if (e.KeyCode == Keys.Enter && buttonGrantAccess.Enabled) //buttonGrantAccess_Click(null, null); } } }
/* * Copyright 2018 Coati Software KG * * 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 CoatiSoftware.SourcetrailExtension.Utility; using EnvDTE; using EnvDTE80; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using VCProjectEngineWrapper; namespace CoatiSoftware.SourcetrailExtension.SolutionParser { public class SolutionParser { static private List<Guid> _reloadedProjectGuids = new List<Guid>(); static private List<string> _compatibilityFlags = new List<string>() { "-fms-extensions", "-fms-compatibility" }; static private string _compatibilityVersionFlagBase = "-fms-compatibility-version="; // We want to get the exact version at runtime for this flag, therefore keeping it seperate from the others makes things easier static private List<string> _cFileExtensions = new List<string>() { "c" }; static private List<string> _cppFileExtensions = new List<string>() { "cc", "cpp", "cxx" }; static private List<string> _sourceExtensionWhiteList = new List<string>(_cFileExtensions.Concat(_cppFileExtensions)); static private List<string> _headerExtensionWhiteList = new List<string>() { "h", "hpp" }; private string _compatibilityVersionFlag = _compatibilityVersionFlagBase + "19"; // This default version would correspond to VS2015 private IPathResolver _pathResolver = null; public SolutionParser(IPathResolver pathResolver) { _pathResolver = pathResolver; } public void CreateCompileCommands(Project project, string solutionConfigurationName, string solutionPlatformName, string cStandard, string additionalClangOptions, bool nonSystemIncludesUseAngleBrackets, Action<CompileCommand> lambda) { Logging.Logging.LogInfo("Creating command objects for project \"" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.Name) + "\"."); DTE dte = project.DTE; Guid projectGuid = Utility.ProjectUtility.ReloadProject(project); IVCProjectWrapper vcProject = VCProjectEngineWrapper.VCProjectWrapperFactory.create(project.Object); if (vcProject != null && vcProject.isValid()) { Logging.Logging.LogInfo("Project \"" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.Name) + "\" has been converted to VCProject " + vcProject.GetWrappedVersion() + "."); } else { Logging.Logging.LogWarning("Project \"" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.Name) + "\" could not be converted to VCProject, skipping."); return; } string projectConfigurationName = ""; string projectPlatformName = ""; foreach (SolutionConfiguration2 solutionConfiguration in SolutionUtility.GetSolutionBuild2(dte).SolutionConfigurations) { if (solutionConfiguration.Name == solutionConfigurationName && solutionConfiguration.PlatformName == solutionPlatformName) { foreach (SolutionContext solutionContext in solutionConfiguration.SolutionContexts) { if (vcProject.GetProjectFile().EndsWith(solutionContext.ProjectName)) { projectConfigurationName = solutionContext.ConfigurationName; projectPlatformName = solutionContext.PlatformName; } } } } if (projectConfigurationName.Length == 0 || projectPlatformName.Length == 0) { Logging.Logging.LogWarning("No project configuration found for solution configuration, trying to use solution configuration on project."); projectConfigurationName = solutionConfigurationName; projectPlatformName = solutionPlatformName; } string cppStandard = ""; IVCConfigurationWrapper vcProjectConfiguration = vcProject.getConfiguration(projectConfigurationName, projectPlatformName); if (vcProjectConfiguration != null && vcProjectConfiguration.isValid()) { SetCompatibilityVersionFlag(vcProject, vcProjectConfiguration); string commandFlags = ""; { // gather include paths and preprocessor definitions of the project List<string> projectIncludeDirectories = ProjectUtility.GetProjectIncludeDirectories(vcProject, vcProjectConfiguration, _pathResolver); List<string> systemIncludeDirectories = ProjectUtility.GetSystemIncludeDirectories(vcProject, vcProjectConfiguration, _pathResolver); List<string> preprocessorDefinitions = ProjectUtility.GetPreprocessorDefinitions(vcProject, vcProjectConfiguration); List<string> forcedIncludeFiles = ProjectUtility.GetForcedIncludeFiles(vcProject, vcProjectConfiguration, _pathResolver); foreach (string flag in _compatibilityFlags) { commandFlags += flag + " "; } commandFlags += _compatibilityVersionFlag + " "; if (!string.IsNullOrWhiteSpace(additionalClangOptions)) { commandFlags += additionalClangOptions; } if (nonSystemIncludesUseAngleBrackets) { systemIncludeDirectories.InsertRange(0, projectIncludeDirectories); projectIncludeDirectories.Clear(); } foreach (string dir in projectIncludeDirectories) { commandFlags += " -I \"" + dir + "\" "; } foreach (string dir in systemIncludeDirectories) { commandFlags += " -isystem \"" + dir + "\" "; } foreach (string prepDef in preprocessorDefinitions) { commandFlags += " -D " + prepDef + " "; } foreach (string file in forcedIncludeFiles) { commandFlags += " -include \"" + file + "\" "; } if (vcProjectConfiguration.GetCLCompilerTool() != null && vcProjectConfiguration.GetCLCompilerTool().isValid()) { cppStandard = vcProjectConfiguration.GetCLCompilerTool().GetLanguageStandard(); } } if (cppStandard.Length == 0) { cppStandard = Utility.ProjectUtility.GetCppStandardForProject(vcProject); } Logging.Logging.LogInfo("Found C++ standard \"" + cppStandard + "\"."); bool isMakefileProject = vcProjectConfiguration.isMakefileConfiguration(); // create command objects for all applicable project items { foreach (ProjectItem item in Utility.ProjectUtility.GetProjectItems(project)) { CompileCommand command = CreateCompileCommand(item, commandFlags, cppStandard, cStandard, isMakefileProject); if (command == null) { continue; } lambda(command); } } if (projectGuid != Guid.Empty) { Utility.ProjectUtility.UnloadProject(projectGuid, dte); } } else { Logging.Logging.LogError("No project configuration found. Skipping this project"); } } private CompileCommand CreateCompileCommand(ProjectItem item, string commandFlags, string vcStandard, string cStandard, bool isMakefileProject) { Logging.Logging.LogInfo("Starting to create Command Object from item \"" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(item.Name) + "\""); try { DTE dte = item.DTE; if (dte == null) { Logging.Logging.LogError("Failed to retrieve DTE object. Abort creating command object."); } IVCFileWrapper vcFile = VCFileWrapperFactory.create(item.Object); IVCCLCompilerToolWrapper compilerTool = null; if (!isMakefileProject) { List<IVCFileConfigurationWrapper> vcFileConfigurations = vcFile.GetFileConfigurations(); foreach (IVCFileConfigurationWrapper vcFileConfiguration in vcFileConfigurations) { if (vcFileConfiguration != null && vcFileConfiguration.isValid()) { if (vcFileConfiguration.GetExcludedFromBuild()) { Logging.Logging.LogInfo("Discarding item because it is excluded from build."); return null; } compilerTool = vcFileConfiguration.GetCLCompilerTool(); if (compilerTool != null && compilerTool.isValid()) { break; } } } } if (CheckIsSourceFile(item)) { string additionalOptions = ""; if (compilerTool != null && compilerTool.isValid()) { additionalOptions = compilerTool.GetAdditionalOptions(); additionalOptions = additionalOptions.Replace("$(NOINHERIT)", ""); additionalOptions = additionalOptions.Replace("$(INHERIT)", ""); additionalOptions = additionalOptions.Trim(); } additionalOptions = additionalOptions.Replace("-std:", "-std="); string languageStandardOption; if (additionalOptions.Contains("-std=")) { // if a language standard was defined in the additional options we do not need to set the language standard again. languageStandardOption = ""; } else { if (compilerTool != null && compilerTool.isValid() && compilerTool.GetCompilesAsC()) { languageStandardOption = "-std=" + cStandard; } else if (compilerTool != null && compilerTool.isValid() && compilerTool.GetCompilesAsCPlusPlus()) { languageStandardOption = "-std=" + vcStandard; } else { // we cannot derive the language from the compiler tool, so we need to check the file extension if (ProjectUtility.HasProperty(item.Properties, "Extension") && _cFileExtensions.Contains(item.Properties.Item("Extension").Value.ToString().Substring(1)) // extension property starts with "." ) { languageStandardOption = "-std=" + cStandard; } else { languageStandardOption = "-std=" + vcStandard; } } } CompileCommand command = new CompileCommand(); string relativeFilePath = item.Properties.Item("RelativePath").Value.ToString(); relativeFilePath = relativeFilePath.Replace("\\\"", ""); relativeFilePath = relativeFilePath.Replace("\"", ""); command.File = _pathResolver.GetAsAbsoluteCanonicalPath(relativeFilePath, vcFile.GetProject()); command.File = command.File.Replace('\\', '/'); command.Directory = _pathResolver.GetCompilationDatabaseFilePath(); command.Command = "clang-tool " + commandFlags; command.Command += languageStandardOption + " "; command.Command += additionalOptions + " "; command.Command += "\"" + command.File + "\""; return command; } } catch (Exception e) { Logging.Logging.LogError("Exception occurred while creating command object: " + e.Message); } return null; } static private bool CheckIsSourceFile(ProjectItem item) { try { string itemType = ""; if (ProjectUtility.HasProperty(item.Properties, "ItemType")) { itemType = item.Properties.Item("ItemType").Value.ToString(); } if (itemType == "ClCompile") { Logging.Logging.LogInfo("Accepting item because of its \"ItemType\" property"); return true; } if (itemType == "None") { Logging.Logging.LogInfo("Discarding item because \"ItemType\" has been set to \"Does not participate in build\""); return false; } string contentType = ""; if (ProjectUtility.HasProperty(item.Properties, "ContentType")) { contentType = item.Properties.Item("ContentType").Value.ToString(); } if (contentType == "CppCode") { Logging.Logging.LogInfo("Accepting item because of its \"ContentType\" property"); return true; } } catch (Exception e) { Logging.Logging.LogError("Exception: " + e.Message); } if (_sourceExtensionWhiteList.Contains(GetFileExtension(item).ToLower())) { Logging.Logging.LogInfo("Accepting item because of its file extension"); return true; } Logging.Logging.LogInfo("Discarding item because of wrong code model"); return false; } static private void ReloadAll(DTE dte) { if (dte == null) { return; } EnvDTE.Solution solution = dte.Solution; List<EnvDTE.Project> projects = Utility.SolutionUtility.GetSolutionProjectList(dte); foreach (EnvDTE.Project project in projects) { _reloadedProjectGuids.Add(Utility.ProjectUtility.ReloadProject(project)); } } static private void UnloadReloadedProjects(DTE dte) { foreach (Guid guid in _reloadedProjectGuids) { Utility.ProjectUtility.UnloadProject(guid, dte); } } private void SetCompatibilityVersionFlag(IVCProjectWrapper project, IVCConfigurationWrapper vcProjectConfiguration) { Logging.Logging.LogInfo("Determining CL.exe (C++ compiler) version"); int majorCompilerVersion = -1; { IVCCLCompilerToolWrapper compilerTool = vcProjectConfiguration.GetCLCompilerTool(); if (compilerTool != null && compilerTool.isValid()) { majorCompilerVersion = GetCLMajorVersion(compilerTool, vcProjectConfiguration); } } if (majorCompilerVersion > -1) { Logging.Logging.LogInfo("Found compiler version " + majorCompilerVersion.ToString()); _compatibilityVersionFlag = _compatibilityVersionFlagBase + majorCompilerVersion.ToString(); return; } } static private int GetCLMajorVersion(IVCCLCompilerToolWrapper compilerTool, IVCConfigurationWrapper vcProjectConfig) { Logging.Logging.LogInfo("Looking up CL.exe (C++ compiler)"); if (compilerTool == null || !compilerTool.isValid() || vcProjectConfig == null || !vcProjectConfig.isValid()) { return -1; } try { IVCPlatformWrapper platform = vcProjectConfig.GetPlatform(); List<string> finalDirectories = new List<string>(); foreach (string directory in platform.GetExecutableDirectories().SplitPaths()) { IPathResolver resolver = new VsPathResolver(""); finalDirectories.AddRange(resolver.ResolveVsMacroInPath(directory, vcProjectConfig)); } string toolPath = compilerTool.GetToolPath(); Logging.Logging.LogInfo("Found " + finalDirectories.Count.ToString() + " possible compiler directories."); foreach (string fd in finalDirectories) { string path = fd + "\\" + toolPath; if (File.Exists(path)) { FileVersionInfo info = FileVersionInfo.GetVersionInfo(path); int version = info.FileMajorPart; Logging.Logging.LogInfo("Found compiler location. Compiler tool version is " + version.ToString()); return version; } } } catch (Exception e) { Logging.Logging.LogError("Exception: " + e.Message); } Logging.Logging.LogWarning("Failed to find C++ compiler tool."); return -1; } static private string GetFileExtension(ProjectItem item) { if (item == null) { return ""; } string name = item.Name; int idx = name.LastIndexOf("."); if (idx > -1 && idx < name.Length - 1) { return name.Substring(idx + 1); } else { return ""; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Newtonsoft.Json; using NuGet.ContentModel; using NuGet.Frameworks; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Microsoft.DotNet.Build.Tasks.Packaging { public class HarvestPackage : PackagingTask { /// <summary> /// Package ID to harvest /// </summary> [Required] public string PackageId { get; set; } /// <summary> /// Current package version. /// </summary> [Required] public string PackageVersion { get; set; } /// <summary> /// Folder where packages have been restored /// </summary> [Required] public string PackagesFolder { get; set; } /// <summary> /// Path to runtime.json that contains the runtime graph. /// </summary> [Required] public string RuntimeFile { get; set; } /// <summary> /// Additional packages to consider for evaluating support but not harvesting assets. /// Identity: Package ID /// Version: Package version. /// </summary> public ITaskItem[] RuntimePackages { get; set; } /// <summary> /// Set to false to suppress harvesting of files and only harvest supported framework information. /// </summary> public bool HarvestAssets { get; set; } /// <summary> /// Set to partial paths to exclude from file harvesting. /// </summary> public string[] PathsToExclude { get; set; } /// <summary> /// Set to partial paths to suppress from both file and support harvesting. /// </summary> public string[] PathsToSuppress { get; set; } /// <summary> /// Frameworks to consider for support evaluation. /// Identity: Framework /// RuntimeIDs: Semi-colon seperated list of runtime IDs /// </summary> public ITaskItem[] Frameworks { get; set; } /// <summary> /// Files already in the package. /// Identity: path to file /// AssemblyVersion: version of assembly /// TargetFramework: target framework moniker to use for harvesting file's dependencies /// TargetPath: path of file in package /// IsReferenceAsset: true for files in Ref. /// </summary> public ITaskItem[] Files { get; set; } /// <summary> /// Frameworks that were supported by previous package version. /// Identity: Framework /// Version: Assembly version if supported /// </summary> [Output] public ITaskItem[] SupportedFrameworks { get; set; } /// <summary> /// Files harvested from previous package version. /// Identity: path to file /// AssemblyVersion: version of assembly /// TargetFramework: target framework moniker to use for harvesting file's dependencies /// TargetPath: path of file in package /// IsReferenceAsset: true for files in Ref. /// </summary> [Output] public ITaskItem[] HarvestedFiles { get; set; } /// <summary> /// When Files are specified, contains the updated set of files, with removals. /// </summary> [Output] public ITaskItem[] UpdatedFiles { get; set; } /// <summary> /// Generates a table in markdown that lists the API version supported by /// various packages at all levels of NETStandard. /// </summary> /// <returns></returns> public override bool Execute() { if (!Directory.Exists(PackagesFolder)) { Log.LogError($"PackagesFolder {PackagesFolder} does not exist."); } if (HasPackagesToHarvest()) { if (HarvestAssets) { HarvestFilesFromPackage(); } if (Frameworks != null && Frameworks.Length > 0) { HarvestSupportedFrameworks(); } } return !Log.HasLoggedErrors; } private bool HasPackagesToHarvest() { bool result = true; IEnumerable<string> packageDirs = new[] { Path.Combine(PackageId, PackageVersion) }; if (RuntimePackages != null) { packageDirs = packageDirs.Concat( RuntimePackages.Select(p => Path.Combine(p.ItemSpec, p.GetMetadata("Version")))); } foreach (var packageDir in packageDirs) { var pathToPackage = Path.Combine(PackagesFolder, packageDir); if (!Directory.Exists(pathToPackage)) { Log.LogMessage(LogImportance.Low, $"Will not harvest files & support from package {packageDir} because {pathToPackage} does not exist."); result = false; } } return result; } private void HarvestSupportedFrameworks() { List<ITaskItem> supportedFrameworks = new List<ITaskItem>(); AggregateNuGetAssetResolver resolver = new AggregateNuGetAssetResolver(RuntimeFile); string packagePath = Path.Combine(PackagesFolder, PackageId, PackageVersion); // add the primary package resolver.AddPackageItems(PackageId, GetPackageItems(packagePath)); if (RuntimePackages != null) { // add any split runtime packages foreach (var runtimePackage in RuntimePackages) { var runtimePackageId = runtimePackage.ItemSpec; var runtimePackageVersion = runtimePackage.GetMetadata("Version"); resolver.AddPackageItems(runtimePackageId, GetPackageItems(PackagesFolder, runtimePackageId, runtimePackageVersion)); } } // create a resolver that can be used to determine the API version for inbox assemblies // since inbox assemblies are represented with placeholders we can remove the placeholders // and use the netstandard reference assembly to determine the API version var filesWithoutPlaceholders = GetPackageItems(packagePath) .Where(f => !NuGetAssetResolver.IsPlaceholder(f)); NuGetAssetResolver resolverWithoutPlaceholders = new NuGetAssetResolver(RuntimeFile, filesWithoutPlaceholders); string package = $"{PackageId}/{PackageVersion}"; foreach (var framework in Frameworks) { var runtimeIds = framework.GetMetadata("RuntimeIDs")?.Split(';'); NuGetFramework fx; try { fx = FrameworkUtilities.ParseNormalized(framework.ItemSpec); } catch (Exception ex) { Log.LogError($"Could not parse Framework {framework.ItemSpec}. {ex}"); continue; } if (fx.Equals(NuGetFramework.UnsupportedFramework)) { Log.LogError($"Did not recognize {framework.ItemSpec} as valid Framework."); continue; } var compileAssets = resolver.ResolveCompileAssets(fx, PackageId); bool hasCompileAsset, hasCompilePlaceHolder; NuGetAssetResolver.ExamineAssets(Log, "Compile", package, fx.ToString(), compileAssets, out hasCompileAsset, out hasCompilePlaceHolder); // start by making sure it has some asset available for compile var isSupported = hasCompileAsset || hasCompilePlaceHolder; if (!isSupported) { Log.LogMessage(LogImportance.Low, $"Skipping {fx} because it is not supported."); continue; } foreach (var runtimeId in runtimeIds) { string target = String.IsNullOrEmpty(runtimeId) ? fx.ToString() : $"{fx}/{runtimeId}"; var runtimeAssets = resolver.ResolveRuntimeAssets(fx, runtimeId); bool hasRuntimeAsset, hasRuntimePlaceHolder; NuGetAssetResolver.ExamineAssets(Log, "Runtime", package, target, runtimeAssets, out hasRuntimeAsset, out hasRuntimePlaceHolder); isSupported &= hasCompileAsset == hasRuntimeAsset; isSupported &= hasCompilePlaceHolder == hasRuntimePlaceHolder; if (!isSupported) { Log.LogMessage(LogImportance.Low, $"Skipping {fx} because it is not supported on {target}."); break; } } if (isSupported) { var supportedFramework = new TaskItem(framework.ItemSpec); supportedFramework.SetMetadata("HarvestedFromPackage", package); // set version // first try the resolved compile asset for this package var refAssm = compileAssets.FirstOrDefault(r => !NuGetAssetResolver.IsPlaceholder(r))?.Substring(PackageId.Length + 1); if (refAssm == null) { // if we didn't have a compile asset it means this framework is supported inbox with a placeholder // resolve the assets without placeholders to pick up the netstandard reference assembly. compileAssets = resolverWithoutPlaceholders.ResolveCompileAssets(fx); refAssm = compileAssets.FirstOrDefault(r => !NuGetAssetResolver.IsPlaceholder(r)); } string version = "unknown"; if (refAssm != null) { version = VersionUtility.GetAssemblyVersion(Path.Combine(packagePath, refAssm))?.ToString() ?? version; } supportedFramework.SetMetadata("Version", version); Log.LogMessage(LogImportance.Low, $"Validating version {version} for {supportedFramework.ItemSpec} because it was supported by {PackageId}/{PackageVersion}."); supportedFrameworks.Add(supportedFramework); } } SupportedFrameworks = supportedFrameworks.ToArray(); } public void HarvestFilesFromPackage() { string pathToPackage = Path.Combine(PackagesFolder, PackageId, PackageVersion); if (!Directory.Exists(pathToPackage)) { Log.LogError($"Cannot harvest from package {PackageId}/{PackageVersion} because {pathToPackage} does not exist."); return; } var livePackageItems = Files.NullAsEmpty() .Where(f => IsIncludedExtension(f.GetMetadata("Extension"))) .Select(f => new PackageItem(f)); var livePackageFiles = new Dictionary<string, PackageItem>(StringComparer.OrdinalIgnoreCase); foreach (var livePackageItem in livePackageItems) { PackageItem existingitem; if (livePackageFiles.TryGetValue(livePackageItem.TargetPath, out existingitem)) { Log.LogError($"Package contains two files with same targetpath: {livePackageItem.TargetPath}, items:{livePackageItem.SourcePath}, {existingitem.SourcePath}."); } else { livePackageFiles.Add(livePackageItem.TargetPath, livePackageItem); } } var harvestedFiles = new List<ITaskItem>(); var removeFiles = new List<ITaskItem>(); // make sure we preserve refs that match desktop assemblies var liveDesktopDlls = livePackageFiles.Values.Where(pi => pi.IsDll && pi.TargetFramework?.Framework == FrameworkConstants.FrameworkIdentifiers.Net); var desktopRefVersions = liveDesktopDlls.Where(d => d.IsRef && d.Version != null).Select(d => d.Version); var desktopLibVersions = liveDesktopDlls.Where(d => !d.IsRef && d.Version != null).Select(d => d.Version); // find destkop assemblies with no matching lib. var preserveRefVersion = new HashSet<Version>(desktopLibVersions); preserveRefVersion.ExceptWith(desktopRefVersions); foreach (var extension in s_includedExtensions) { foreach (var packageFile in Directory.EnumerateFiles(pathToPackage, $"*{extension}", SearchOption.AllDirectories)) { string packagePath = packageFile.Substring(pathToPackage.Length + 1).Replace('\\', '/'); // determine if we should include this file from the harvested package // exclude if its specifically set for exclusion if (ShouldExclude(packagePath)) { Log.LogMessage(LogImportance.Low, $"Excluding package path {packagePath}."); continue; } var assemblyVersion = extension == s_dll ? VersionUtility.GetAssemblyVersion(packageFile) : null; PackageItem liveFile = null; // determine if the harvested file clashes with a live built file // we'll prefer the harvested reference assembly so long as it's the same API // version and not required to match implementation 1:1 as is the case for desktop if (livePackageFiles.TryGetValue(packagePath, out liveFile)) { // Not a dll, not a ref, or not a versioned assembly: prefer live built file. if (extension != s_dll || !liveFile.IsRef || assemblyVersion == null || liveFile.Version == null) { Log.LogMessage(LogImportance.Low, $"Preferring live build of package path {packagePath} over the asset from last stable package."); continue; } // preserve desktop references to ensure bindingRedirects will work. if (liveFile.TargetFramework.Framework == FrameworkConstants.FrameworkIdentifiers.Net) { Log.LogMessage(LogImportance.Low, $"Preferring live build of package path {packagePath} over the asset from last stable package for desktop framework."); continue; } // as above but handle the case where a netstandard ref may be used for a desktop impl. if (preserveRefVersion.Contains(liveFile.Version)) { Log.LogMessage(LogImportance.Low, $"Preferring live build of package path {packagePath} over the asset from last stable package for desktop framework."); continue; } // preserve references with a different major.minor version if (assemblyVersion.Major != liveFile.Version.Major || assemblyVersion.Minor != liveFile.Version.Minor) { Log.LogMessage(LogImportance.Low, $"Preferring live build of reference {packagePath} over the asset from last stable package since the live build is a different API version."); continue; } // preserve references that specifically set the preserve metadata. bool preserve = false; bool.TryParse(liveFile.OriginalItem.GetMetadata("Preserve"), out preserve); if (preserve) { Log.LogMessage(LogImportance.Low, $"Preferring live build of reference {packagePath} over the asset from last stable package since Preserve was set to true."); continue; } // replace the live file with the harvested one, removing both the live file and PDB from the // file list. Log.LogMessage($"Using reference {packagePath} from last stable package {PackageId}/{PackageVersion} rather than the built reference {liveFile.SourcePath} since it is the same API version. Set <Preserve>true</Preserve> on {liveFile.SourceProject} if you'd like to avoid this.."); removeFiles.Add(liveFile.OriginalItem); PackageItem livePdbFile; if (livePackageFiles.TryGetValue(Path.ChangeExtension(packagePath, ".pdb"), out livePdbFile)) { removeFiles.Add(livePdbFile.OriginalItem); } } else { Log.LogMessage(LogImportance.Low, $"Including {packagePath} from last stable package {PackageId}/{PackageVersion}."); } var item = new TaskItem(packageFile); if (liveFile?.OriginalItem != null) { // preserve all the meta-data from the live file that was replaced. liveFile.OriginalItem.CopyMetadataTo(item); } else { var targetPath = Path.GetDirectoryName(packagePath).Replace('\\', '/'); item.SetMetadata("TargetPath", targetPath); string targetFramework = GetTargetFrameworkFromPackagePath(targetPath); item.SetMetadata("TargetFramework", targetFramework); // only harvest for non-portable frameworks, matches logic in packaging.targets. bool harvestDependencies = !targetFramework.StartsWith("portable-"); item.SetMetadata("HarvestDependencies", harvestDependencies.ToString()); item.SetMetadata("IsReferenceAsset", IsReferencePackagePath(targetPath).ToString()); } if (assemblyVersion != null) { // overwrite whatever metadata may have been copied from the live file. item.SetMetadata("AssemblyVersion", assemblyVersion.ToString()); } item.SetMetadata("HarvestedFrom", $"{PackageId}/{PackageVersion}/{packagePath}"); harvestedFiles.Add(item); } } HarvestedFiles = harvestedFiles.ToArray(); if (Files != null) { UpdatedFiles = Files.Except(removeFiles).ToArray(); } } private string[] _pathsToExclude = null; private bool ShouldExclude(string packagePath) { if (_pathsToExclude == null) { _pathsToExclude = PathsToExclude.NullAsEmpty().Select(EnsureDirectory).ToArray(); } return ShouldSuppress(packagePath) || _pathsToExclude.Any(p => packagePath.StartsWith(p, StringComparison.OrdinalIgnoreCase)); } private string[] _pathsToSuppress = null; private bool ShouldSuppress(string packagePath) { if (_pathsToSuppress == null) { _pathsToSuppress = PathsToSuppress.NullAsEmpty().Select(EnsureDirectory).ToArray(); } return _pathsToSuppress.Any(p => packagePath.StartsWith(p, StringComparison.OrdinalIgnoreCase)); } private static string EnsureDirectory(string source) { string result; if (source.Length < 1 || source[source.Length - 1] == '\\' || source[source.Length - 1] == '/') { // already have a directory result = source; } else { // could be a directory or file var extension = Path.GetExtension(source); if (IsIncludedExtension(extension)) { // it's a file, find the directory portion var fileName = Path.GetFileName(source); if (fileName.Length != source.Length) { result = source.Substring(0, source.Length - fileName.Length); } else { // no directory portion, just return as-is result = source; } } else { // it's a directory, add the slash result = source + '/'; } } return result; } private static string GetTargetFrameworkFromPackagePath(string path) { var parts = path.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); if (parts.Length >= 2) { if (parts[0].Equals("lib", StringComparison.OrdinalIgnoreCase) || parts[0].Equals("ref", StringComparison.OrdinalIgnoreCase)) { return parts[1]; } if (parts.Length >= 4 && parts[0].Equals("runtimes", StringComparison.OrdinalIgnoreCase) && parts[2].Equals("lib", StringComparison.OrdinalIgnoreCase)) { return parts[3]; } } return null; } private static string s_dll = ".dll"; private static string[] s_includedExtensions = new[] { s_dll, ".pdb", ".xml", "._" }; private static bool IsIncludedExtension(string extension) { return extension != null && extension.Length > 0 && s_includedExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase); } private static bool IsReferencePackagePath(string path) { return path.StartsWith("ref", StringComparison.OrdinalIgnoreCase); } private IEnumerable<string> GetPackageItems(string packagesFolder, string packageId, string packageVersion) { string packageFolder = Path.Combine(packagesFolder, packageId, packageVersion); return GetPackageItems(packageFolder); } private IEnumerable<string> GetPackageItems(string packageFolder) { return Directory.EnumerateFiles(packageFolder, "*", SearchOption.AllDirectories) .Select(f => f.Substring(packageFolder.Length + 1).Replace('\\', '/')) .Where(f => !ShouldSuppress(f)); } } }
// *********************************************************************** // Copyright (c) 2008-2015 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.Collections.Generic; using System.Globalization; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; namespace NUnit.Framework { /// <summary> /// RandomAttribute is used to supply a set of random _values /// to a single parameter of a parameterized test. /// </summary> public class RandomAttribute : DataAttribute, IParameterDataSource { private RandomDataSource _source; private int _count; #region Constructors /// <summary> /// Construct a random set of values appropriate for the Type of the /// parameter on which the attribute appears, specifying only the count. /// </summary> /// <param name="count"></param> public RandomAttribute(int count) { _count = count; } /// <summary> /// Construct a set of ints within a specified range /// </summary> public RandomAttribute(int min, int max, int count) { _source = new IntDataSource(min, max, count); } /// <summary> /// Construct a set of unsigned ints within a specified range /// </summary> [CLSCompliant(false)] public RandomAttribute(uint min, uint max, int count) { _source = new UIntDataSource(min, max, count); } /// <summary> /// Construct a set of longs within a specified range /// </summary> public RandomAttribute(long min, long max, int count) { _source = new LongDataSource(min, max, count); } /// <summary> /// Construct a set of unsigned longs within a specified range /// </summary> [CLSCompliant(false)] public RandomAttribute(ulong min, ulong max, int count) { _source = new ULongDataSource(min, max, count); } /// <summary> /// Construct a set of shorts within a specified range /// </summary> public RandomAttribute(short min, short max, int count) { _source = new ShortDataSource(min, max, count); } /// <summary> /// Construct a set of unsigned shorts within a specified range /// </summary> [CLSCompliant(false)] public RandomAttribute(ushort min, ushort max, int count) { _source = new UShortDataSource(min, max, count); } /// <summary> /// Construct a set of doubles within a specified range /// </summary> public RandomAttribute(double min, double max, int count) { _source = new DoubleDataSource(min, max, count); } /// <summary> /// Construct a set of floats within a specified range /// </summary> public RandomAttribute(float min, float max, int count) { _source = new FloatDataSource(min, max, count); } /// <summary> /// Construct a set of bytes within a specified range /// </summary> public RandomAttribute(byte min, byte max, int count) { _source = new ByteDataSource(min, max, count); } /// <summary> /// Construct a set of sbytes within a specified range /// </summary> [CLSCompliant(false)] public RandomAttribute(sbyte min, sbyte max, int count) { _source = new SByteDataSource(min, max, count); } #endregion #region IParameterDataSource Interface /// <summary> /// Get the collection of _values to be used as arguments. /// </summary> public IEnumerable GetData(IParameterInfo parameter) { // Since a separate Randomizer is used for each parameter, // we can't fill in the data in the constructor of the // attribute. Only now, when GetData is called, do we have // sufficient information to create the values in a // repeatable manner. Type parmType = parameter.ParameterType; if (_source == null) { if (parmType == typeof(int)) _source = new IntDataSource(_count); else if (parmType == typeof(uint)) _source = new UIntDataSource(_count); else if (parmType == typeof(long)) _source = new LongDataSource(_count); else if (parmType == typeof(ulong)) _source = new ULongDataSource(_count); else if (parmType == typeof(short)) _source = new ShortDataSource(_count); else if (parmType == typeof(ushort)) _source = new UShortDataSource(_count); else if (parmType == typeof(double)) _source = new DoubleDataSource(_count); else if (parmType == typeof(float)) _source = new FloatDataSource(_count); else if (parmType == typeof(byte)) _source = new ByteDataSource(_count); else if (parmType == typeof(sbyte)) _source = new SByteDataSource(_count); else if (parmType == typeof(decimal)) _source = new DecimalDataSource(_count); else if (parmType.IsEnum) _source = new EnumDataSource(_count); else // Default _source = new IntDataSource(_count); } else if (_source.DataType != parmType && WeConvert(_source.DataType, parmType)) { _source = new RandomDataConverter(_source); } return _source.GetData(parameter); //// Copy the random _values into the data array //// and call the base class which may need to //// convert them to another type. //this.data = new object[values.Count]; //for (int i = 0; i < values.Count; i++) // this.data[i] = values[i]; //return base.GetData(parameter); } private bool WeConvert(Type sourceType, Type targetType) { if (targetType == typeof(short) || targetType == typeof(ushort) || targetType == typeof(byte) || targetType == typeof(sbyte)) return sourceType == typeof(int); if (targetType == typeof(decimal)) return sourceType == typeof(int) || sourceType == typeof(double); return false; } #endregion #region Nested DataSource Classes #region RandomDataSource abstract class RandomDataSource : IParameterDataSource { public Type DataType { get; protected set; } public abstract IEnumerable GetData(IParameterInfo parameter); } abstract class RandomDataSource<T> : RandomDataSource { private T _min; private T _max; private int _count; private bool _inRange; protected Randomizer _randomizer; protected RandomDataSource(int count) { _count = count; _inRange = false; DataType = typeof(T); } protected RandomDataSource(T min, T max, int count) { _min = min; _max = max; _count = count; _inRange = true; DataType = typeof(T); } public override IEnumerable GetData(IParameterInfo parameter) { //Guard.ArgumentValid(parameter.ParameterType == typeof(T), "Parameter type must be " + typeof(T).Name, "parameter"); _randomizer = Randomizer.GetRandomizer(parameter.ParameterInfo); for (int i = 0; i < _count; i++) yield return _inRange ? GetNext(_min, _max) : GetNext(); } protected abstract T GetNext(); protected abstract T GetNext(T min, T max); } #endregion #region RandomDataConverter class RandomDataConverter : RandomDataSource { IParameterDataSource _source; public RandomDataConverter(IParameterDataSource source) { _source = source; } public override IEnumerable GetData(IParameterInfo parameter) { Type parmType = parameter.ParameterType; foreach (object obj in _source.GetData(parameter)) { if (obj is int) { int ival = (int)obj; // unbox first if (parmType == typeof(short)) yield return (short)ival; else if (parmType == typeof(ushort)) yield return (ushort)ival; else if (parmType == typeof(byte)) yield return (byte)ival; else if (parmType == typeof(sbyte)) yield return (sbyte)ival; else if (parmType == typeof(decimal)) yield return (decimal)ival; } else if (obj is double) { double d = (double)obj; // unbox first if (parmType == typeof(decimal)) yield return (decimal)d; } } } } #endregion #region IntDataSource class IntDataSource : RandomDataSource<int> { public IntDataSource(int count) : base(count) { } public IntDataSource(int min, int max, int count) : base(min, max, count) { } protected override int GetNext() { return _randomizer.Next(); } protected override int GetNext(int min, int max) { return _randomizer.Next(min, max); } } #endregion #region UIntDataSource class UIntDataSource : RandomDataSource<uint> { public UIntDataSource(int count) : base(count) { } public UIntDataSource(uint min, uint max, int count) : base(min, max, count) { } protected override uint GetNext() { return _randomizer.NextUInt(); } protected override uint GetNext(uint min, uint max) { return _randomizer.NextUInt(min, max); } } #endregion #region LongDataSource class LongDataSource : RandomDataSource<long> { public LongDataSource(int count) : base(count) { } public LongDataSource(long min, long max, int count) : base(min, max, count) { } protected override long GetNext() { return _randomizer.NextLong(); } protected override long GetNext(long min, long max) { return _randomizer.NextLong(min, max); } } #endregion #region ULongDataSource class ULongDataSource : RandomDataSource<ulong> { public ULongDataSource(int count) : base(count) { } public ULongDataSource(ulong min, ulong max, int count) : base(min, max, count) { } protected override ulong GetNext() { return _randomizer.NextULong(); } protected override ulong GetNext(ulong min, ulong max) { return _randomizer.NextULong(min, max); } } #endregion #region ShortDataSource class ShortDataSource : RandomDataSource<short> { public ShortDataSource(int count) : base(count) { } public ShortDataSource(short min, short max, int count) : base(min, max, count) { } protected override short GetNext() { return _randomizer.NextShort(); } protected override short GetNext(short min, short max) { return _randomizer.NextShort(min, max); } } #endregion #region UShortDataSource class UShortDataSource : RandomDataSource<ushort> { public UShortDataSource(int count) : base(count) { } public UShortDataSource(ushort min, ushort max, int count) : base(min, max, count) { } protected override ushort GetNext() { return _randomizer.NextUShort(); } protected override ushort GetNext(ushort min, ushort max) { return _randomizer.NextUShort(min, max); } } #endregion #region DoubleDataSource class DoubleDataSource : RandomDataSource<double> { public DoubleDataSource(int count) : base(count) { } public DoubleDataSource(double min, double max, int count) : base(min, max, count) { } protected override double GetNext() { return _randomizer.NextDouble(); } protected override double GetNext(double min, double max) { return _randomizer.NextDouble(min, max); } } #endregion #region FloatDataSource class FloatDataSource : RandomDataSource<float> { public FloatDataSource(int count) : base(count) { } public FloatDataSource(float min, float max, int count) : base(min, max, count) { } protected override float GetNext() { return _randomizer.NextFloat(); } protected override float GetNext(float min, float max) { return _randomizer.NextFloat(min, max); } } #endregion #region ByteDataSource class ByteDataSource : RandomDataSource<byte> { public ByteDataSource(int count) : base(count) { } public ByteDataSource(byte min, byte max, int count) : base(min, max, count) { } protected override byte GetNext() { return _randomizer.NextByte(); } protected override byte GetNext(byte min, byte max) { return _randomizer.NextByte(min, max); } } #endregion #region SByteDataSource class SByteDataSource : RandomDataSource<sbyte> { public SByteDataSource(int count) : base(count) { } public SByteDataSource(sbyte min, sbyte max, int count) : base(min, max, count) { } protected override sbyte GetNext() { return _randomizer.NextSByte(); } protected override sbyte GetNext(sbyte min, sbyte max) { return _randomizer.NextSByte(min, max); } } #endregion #region EnumDataSource class EnumDataSource : RandomDataSource { private int _count; public EnumDataSource(int count) { _count = count; DataType = typeof(Enum); } public override IEnumerable GetData(IParameterInfo parameter) { Guard.ArgumentValid(parameter.ParameterType.IsEnum, "EnumDataSource requires an enum parameter", "parameter"); Randomizer randomizer = Randomizer.GetRandomizer(parameter.ParameterInfo); DataType = parameter.ParameterType; for (int i = 0; i < _count; i++ ) yield return randomizer.NextEnum(parameter.ParameterType); } } #endregion #region DecimalDataSource // Currently, Randomizer doesn't implement methods for decimal // so we use random Ulongs and convert them. This doesn't cover // the full range of decimal, so it's temporary. class DecimalDataSource : RandomDataSource<decimal> { public DecimalDataSource(int count) : base(count) { } public DecimalDataSource(decimal min, decimal max, int count) : base(min, max, count) { } protected override decimal GetNext() { return _randomizer.NextDecimal(); } protected override decimal GetNext(decimal min, decimal max) { return _randomizer.NextDecimal(min, max); } } #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. using System; using System.Collections; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; namespace System.Collections.Specialized { /// <summary> /// This enum describes the action that caused a CollectionChanged event. /// </summary> public enum NotifyCollectionChangedAction { /// <summary> One or more items were added to the collection. </summary> Add, /// <summary> One or more items were removed from the collection. </summary> Remove, /// <summary> One or more items were replaced in the collection. </summary> Replace, /// <summary> One or more items were moved within the collection. </summary> Move, /// <summary> The contents of the collection changed dramatically. </summary> Reset, } /// <summary> /// Arguments for the CollectionChanged event. /// A collection that supports INotifyCollectionChangedThis raises this event /// whenever an item is added or removed, or when the contents of the collection /// changes dramatically. /// </summary> public class NotifyCollectionChangedEventArgs : EventArgs { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a reset change. /// </summary> /// <param name="action">The action that caused the event (must be Reset).</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action) { if (action != NotifyCollectionChangedAction.Reset) throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Reset), "action"); InitializeAdd(action, null, -1); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item change. /// </summary> /// <param name="action">The action that caused the event; can only be Reset, Add or Remove action.</param> /// <param name="changedItem">The item affected by the change.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object changedItem) { if ((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove) && (action != NotifyCollectionChangedAction.Reset)) throw new ArgumentException(SR.MustBeResetAddOrRemoveActionForCtor, "action"); if (action == NotifyCollectionChangedAction.Reset) { if (changedItem != null) throw new ArgumentException(SR.ResetActionRequiresNullItem, "action"); InitializeAdd(action, null, -1); } else { InitializeAddOrRemove(action, new object[] { changedItem }, -1); } } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item change. /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItem">The item affected by the change.</param> /// <param name="index">The index where the change occurred.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object changedItem, int index) { if ((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove) && (action != NotifyCollectionChangedAction.Reset)) throw new ArgumentException(SR.MustBeResetAddOrRemoveActionForCtor, "action"); if (action == NotifyCollectionChangedAction.Reset) { if (changedItem != null) throw new ArgumentException(SR.ResetActionRequiresNullItem, "action"); if (index != -1) throw new ArgumentException(SR.ResetActionRequiresIndexMinus1, "action"); InitializeAdd(action, null, -1); } else { InitializeAddOrRemove(action, new object[] { changedItem }, index); } } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item change. /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItems">The items affected by the change.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList changedItems) { if ((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove) && (action != NotifyCollectionChangedAction.Reset)) throw new ArgumentException(SR.MustBeResetAddOrRemoveActionForCtor, "action"); if (action == NotifyCollectionChangedAction.Reset) { if (changedItems != null) throw new ArgumentException(SR.ResetActionRequiresNullItem, "action"); InitializeAdd(action, null, -1); } else { if (changedItems == null) throw new ArgumentNullException("changedItems"); InitializeAddOrRemove(action, changedItems, -1); } } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item change (or a reset). /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItems">The items affected by the change.</param> /// <param name="startingIndex">The index where the change occurred.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList changedItems, int startingIndex) { if ((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove) && (action != NotifyCollectionChangedAction.Reset)) throw new ArgumentException(SR.MustBeResetAddOrRemoveActionForCtor, "action"); if (action == NotifyCollectionChangedAction.Reset) { if (changedItems != null) throw new ArgumentException(SR.ResetActionRequiresNullItem, "action"); if (startingIndex != -1) throw new ArgumentException(SR.ResetActionRequiresIndexMinus1, "action"); InitializeAdd(action, null, -1); } else { if (changedItems == null) throw new ArgumentNullException("changedItems"); if (startingIndex < -1) throw new ArgumentException(SR.IndexCannotBeNegative, "startingIndex"); InitializeAddOrRemove(action, changedItems, startingIndex); } } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItem">The new item replacing the original item.</param> /// <param name="oldItem">The original item that is replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object newItem, object oldItem) { if (action != NotifyCollectionChangedAction.Replace) throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Replace), "action"); InitializeMoveOrReplace(action, new object[] { newItem }, new object[] { oldItem }, -1, -1); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItem">The new item replacing the original item.</param> /// <param name="oldItem">The original item that is replaced.</param> /// <param name="index">The index of the item being replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object newItem, object oldItem, int index) { if (action != NotifyCollectionChangedAction.Replace) throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Replace), "action"); InitializeMoveOrReplace(action, new object[] { newItem }, new object[] { oldItem }, index, index); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItems">The new items replacing the original items.</param> /// <param name="oldItems">The original items that are replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList newItems, IList oldItems) { if (action != NotifyCollectionChangedAction.Replace) throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Replace), "action"); if (newItems == null) throw new ArgumentNullException("newItems"); if (oldItems == null) throw new ArgumentNullException("oldItems"); InitializeMoveOrReplace(action, newItems, oldItems, -1, -1); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItems">The new items replacing the original items.</param> /// <param name="oldItems">The original items that are replaced.</param> /// <param name="startingIndex">The starting index of the items being replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList newItems, IList oldItems, int startingIndex) { if (action != NotifyCollectionChangedAction.Replace) throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Replace), "action"); if (newItems == null) throw new ArgumentNullException("newItems"); if (oldItems == null) throw new ArgumentNullException("oldItems"); InitializeMoveOrReplace(action, newItems, oldItems, startingIndex, startingIndex); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item Move event. /// </summary> /// <param name="action">Can only be a Move action.</param> /// <param name="changedItem">The item affected by the change.</param> /// <param name="index">The new index for the changed item.</param> /// <param name="oldIndex">The old index for the changed item.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object changedItem, int index, int oldIndex) { if (action != NotifyCollectionChangedAction.Move) throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Move), "action"); if (index < 0) throw new ArgumentException(SR.IndexCannotBeNegative, "index"); object[] changedItems = new object[] { changedItem }; InitializeMoveOrReplace(action, changedItems, changedItems, index, oldIndex); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item Move event. /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItems">The items affected by the change.</param> /// <param name="index">The new index for the changed items.</param> /// <param name="oldIndex">The old index for the changed items.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList changedItems, int index, int oldIndex) { if (action != NotifyCollectionChangedAction.Move) throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Move), "action"); if (index < 0) throw new ArgumentException(SR.IndexCannotBeNegative, "index"); InitializeMoveOrReplace(action, changedItems, changedItems, index, oldIndex); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs with given fields (no validation). Used by WinRT marshaling. /// </summary> internal NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList newItems, IList oldItems, int newIndex, int oldIndex) { _action = action; _newItems = (newItems == null) ? null : new ReadOnlyList(newItems); _oldItems = (oldItems == null) ? null : new ReadOnlyList(oldItems); _newStartingIndex = newIndex; _oldStartingIndex = oldIndex; } private void InitializeAddOrRemove(NotifyCollectionChangedAction action, IList changedItems, int startingIndex) { if (action == NotifyCollectionChangedAction.Add) InitializeAdd(action, changedItems, startingIndex); else if (action == NotifyCollectionChangedAction.Remove) InitializeRemove(action, changedItems, startingIndex); else Debug.Assert(false, String.Format("Unsupported action: {0}", action.ToString())); } private void InitializeAdd(NotifyCollectionChangedAction action, IList newItems, int newStartingIndex) { _action = action; _newItems = (newItems == null) ? null : new ReadOnlyList(newItems); _newStartingIndex = newStartingIndex; } private void InitializeRemove(NotifyCollectionChangedAction action, IList oldItems, int oldStartingIndex) { _action = action; _oldItems = (oldItems == null) ? null : new ReadOnlyList(oldItems); _oldStartingIndex = oldStartingIndex; } private void InitializeMoveOrReplace(NotifyCollectionChangedAction action, IList newItems, IList oldItems, int startingIndex, int oldStartingIndex) { InitializeAdd(action, newItems, startingIndex); InitializeRemove(action, oldItems, oldStartingIndex); } //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ /// <summary> /// The action that caused the event. /// </summary> public NotifyCollectionChangedAction Action { get { return _action; } } /// <summary> /// The items affected by the change. /// </summary> public IList NewItems { get { return _newItems; } } /// <summary> /// The old items affected by the change (for Replace events). /// </summary> public IList OldItems { get { return _oldItems; } } /// <summary> /// The index where the change occurred. /// </summary> public int NewStartingIndex { get { return _newStartingIndex; } } /// <summary> /// The old index where the change occurred (for Move events). /// </summary> public int OldStartingIndex { get { return _oldStartingIndex; } } //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ private NotifyCollectionChangedAction _action; private IList _newItems, _oldItems; private int _newStartingIndex = -1; private int _oldStartingIndex = -1; } /// <summary> /// The delegate to use for handlers that receive the CollectionChanged event. /// </summary> public delegate void NotifyCollectionChangedEventHandler(object sender, NotifyCollectionChangedEventArgs e); internal sealed class ReadOnlyList : IList { private readonly IList _list; internal ReadOnlyList(IList list) { Debug.Assert(list != null); _list = list; } public int Count { get { return _list.Count; } } public bool IsReadOnly { get { return true; } } public bool IsFixedSize { get { return true; } } public bool IsSynchronized { get { return _list.IsSynchronized; } } public object this[int index] { get { return _list[index]; } set { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } public object SyncRoot { get { return _list.SyncRoot; } } public int Add(object value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public void Clear() { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public bool Contains(object value) { return _list.Contains(value); } public void CopyTo(Array array, int index) { _list.CopyTo(array, index); } public IEnumerator GetEnumerator() { return _list.GetEnumerator(); } public int IndexOf(object value) { return _list.IndexOf(value); } public void Insert(int index, object value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public void Remove(object value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public void RemoveAt(int index) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } }
using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using NSubstitute; using Xunit; namespace Octokit.Tests.Clients { /// <summary> /// Client tests mostly just need to make sure they call the IApiConnection with the correct /// relative Uri. No need to fake up the response. All *those* tests are in ApiConnectionTests.cs. /// </summary> public class RepositoryBranchesClientTests { public class TheCtor { [Fact] public void EnsuresNonNullArguments() { Assert.Throws<ArgumentNullException>(() => new RepositoryBranchesClient(null)); } } public class TheGetAllMethod { [Fact] public async Task RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); await client.GetAll("owner", "name"); connection.Received() .GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/branches"), null, "application/vnd.github.luke-cage-preview+json", Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); await client.GetAll(1); connection.Received() .GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches"), null, "application/vnd.github.luke-cage-preview+json", Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithApiOptions() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; await client.GetAll("owner", "name", options); connection.Received() .GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/branches"), null, "application/vnd.github.luke-cage-preview+json", options); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryIdWithApiOptions() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; await client.GetAll(1, options); connection.Received() .GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches"), null, "application/vnd.github.luke-cage-preview+json", options); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll(null, "name")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll(null, "name", ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", null, ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", "name", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("", "name")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("owner", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("", "name", ApiOptions.None)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("owner", "", ApiOptions.None)); } } public class TheGetMethod { [Fact] public async Task RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); await client.Get("owner", "repo", "branch"); connection.Received() .Get<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch"), null, "application/vnd.github.luke-cage-preview+json"); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); await client.Get(1, "branch"); connection.Received() .Get<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch"), null, "application/vnd.github.luke-cage-preview+json"); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(null, "repo", "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", null, "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.Get("", "repo", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "repo", "")); } } public class TheGetBranchProtectectionMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.GetBranchProtection("owner", "repo", "branch"); connection.Received() .Get<BranchProtectionSettings>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection"), null, previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.GetBranchProtection(1, "branch"); connection.Received() .Get<BranchProtectionSettings>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection"), null, previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranchProtection(null, "repo", "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranchProtection("owner", null, "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranchProtection("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranchProtection(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranchProtection("", "repo", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranchProtection("owner", "", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranchProtection("owner", "repo", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranchProtection(1, "")); } } public class TheUpdateBranchProtectionMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var update = new BranchProtectionSettingsUpdate( new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" })); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.UpdateBranchProtection("owner", "repo", "branch", update); connection.Received() .Put<BranchProtectionSettings>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection"), Arg.Any<BranchProtectionSettingsUpdate>(), null, previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var update = new BranchProtectionSettingsUpdate( new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" })); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.UpdateBranchProtection(1, "branch", update); connection.Received() .Put<BranchProtectionSettings>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection"), Arg.Any<BranchProtectionSettingsUpdate>(), null, previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); var update = new BranchProtectionSettingsUpdate( new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" })); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection(null, "repo", "branch", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection("owner", null, "branch", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection("owner", "repo", null, update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection("owner", "repo", "branch", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection(1, null, update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection(1, "branch", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateBranchProtection("", "repo", "branch", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateBranchProtection("owner", "", "branch", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateBranchProtection("owner", "repo", "", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateBranchProtection(1, "", update)); } } public class TheDeleteBranchProtectectionMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.DeleteBranchProtection("owner", "repo", "branch"); connection.Connection.Received() .Delete(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection"), Arg.Any<object>(), previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.DeleteBranchProtection(1, "branch"); connection.Connection.Received() .Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection"), Arg.Any<object>(), previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteBranchProtection(null, "repo", "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteBranchProtection("owner", null, "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteBranchProtection("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteBranchProtection(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteBranchProtection("", "repo", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteBranchProtection("owner", "", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteBranchProtection("owner", "repo", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteBranchProtection(1, "")); } } public class TheGetRequiredStatusChecksMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.GetRequiredStatusChecks("owner", "repo", "branch"); connection.Received() .Get<BranchProtectionRequiredStatusChecks>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks"), null, previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.GetRequiredStatusChecks(1, "branch"); connection.Received() .Get<BranchProtectionRequiredStatusChecks>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks"), null, previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetRequiredStatusChecks(null, "repo", "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetRequiredStatusChecks("owner", null, "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetRequiredStatusChecks("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetRequiredStatusChecks(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetRequiredStatusChecks("", "repo", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetRequiredStatusChecks("owner", "", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetRequiredStatusChecks("owner", "repo", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetRequiredStatusChecks(1, "")); } } public class TheUpdateRequiredStatusChecksMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var update = new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" }); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.UpdateRequiredStatusChecks("owner", "repo", "branch", update); connection.Received() .Patch<BranchProtectionRequiredStatusChecks>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks"), Arg.Any<BranchProtectionRequiredStatusChecksUpdate>(), previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var update = new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" }); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.UpdateRequiredStatusChecks(1, "branch", update); connection.Received() .Patch<BranchProtectionRequiredStatusChecks>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks"), Arg.Any<BranchProtectionRequiredStatusChecksUpdate>(), previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); var update = new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" }); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks(null, "repo", "branch", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks("owner", null, "branch", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks("owner", "repo", null, update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks("owner", "repo", "branch", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks(1, null, update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks(1, "branch", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecks("", "repo", "branch", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecks("owner", "", "branch", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecks("owner", "repo", "", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecks(1, "", update)); } } public class TheDeleteRequiredStatusChecksMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.DeleteRequiredStatusChecks("owner", "repo", "branch"); connection.Connection.Received() .Delete(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks"), Arg.Any<object>(), previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.DeleteRequiredStatusChecks(1, "branch"); connection.Connection.Received() .Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks"), Arg.Any<object>(), previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecks(null, "repo", "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecks("owner", null, "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecks("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecks(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecks("", "repo", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecks("owner", "", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecks("owner", "repo", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecks(1, "")); } } public class TheGetAllRequiredStatusChecksContextsMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.GetAllRequiredStatusChecksContexts("owner", "repo", "branch"); connection.Received() .Get<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks/contexts"), null, previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.GetAllRequiredStatusChecksContexts(1, "branch"); connection.Received() .Get<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks/contexts"), null, previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllRequiredStatusChecksContexts(null, "repo", "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllRequiredStatusChecksContexts("owner", null, "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllRequiredStatusChecksContexts("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllRequiredStatusChecksContexts(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllRequiredStatusChecksContexts("", "repo", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllRequiredStatusChecksContexts("owner", "", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllRequiredStatusChecksContexts("owner", "repo", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllRequiredStatusChecksContexts(1, "")); } } public class TheUpdateRequiredStatusChecksContextsMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var update = new List<string>() { "test" }; const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.UpdateRequiredStatusChecksContexts("owner", "repo", "branch", update); connection.Received() .Put<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), null, previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var update = new List<string>() { "test" }; const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.UpdateRequiredStatusChecksContexts(1, "branch", update); connection.Received() .Put<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), null, previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); var update = new List<string>() { "test" }; await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts(null, "repo", "branch", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts("owner", null, "branch", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts("owner", "repo", null, update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts("owner", "repo", "branch", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts(1, null, update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts(1, "branch", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecksContexts("", "repo", "branch", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecksContexts("owner", "", "branch", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecksContexts("owner", "repo", "", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecksContexts(1, "", update)); } } public class TheAddRequiredStatusChecksContextsMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var newContexts = new List<string>() { "test" }; const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.AddRequiredStatusChecksContexts("owner", "repo", "branch", newContexts); connection.Received() .Post<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var newContexts = new List<string>() { "test" }; const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.AddRequiredStatusChecksContexts(1, "branch", newContexts); connection.Received() .Post<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); var newContexts = new List<string>() { "test" }; await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts(null, "repo", "branch", newContexts)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts("owner", null, "branch", newContexts)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts("owner", "repo", null, newContexts)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts("owner", "repo", "branch", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts(1, null, newContexts)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts(1, "branch", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.AddRequiredStatusChecksContexts("", "repo", "branch", newContexts)); await Assert.ThrowsAsync<ArgumentException>(() => client.AddRequiredStatusChecksContexts("owner", "", "branch", newContexts)); await Assert.ThrowsAsync<ArgumentException>(() => client.AddRequiredStatusChecksContexts("owner", "repo", "", newContexts)); await Assert.ThrowsAsync<ArgumentException>(() => client.AddRequiredStatusChecksContexts(1, "", newContexts)); } } public class TheDeleteRequiredStatusChecksContextsMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var contextsToRemove = new List<string>() { "test" }; const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.DeleteRequiredStatusChecksContexts("owner", "repo", "branch", contextsToRemove); connection.Received() .Delete<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var contextsToRemove = new List<string>() { "test" }; const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.DeleteRequiredStatusChecksContexts(1, "branch", contextsToRemove); connection.Received() .Delete<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); var contextsToRemove = new List<string>() { "test" }; await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts(null, "repo", "branch", contextsToRemove)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts("owner", null, "branch", contextsToRemove)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts("owner", "repo", null, contextsToRemove)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts("owner", "repo", "branch", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts(1, null, contextsToRemove)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts(1, "branch", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecksContexts("", "repo", "branch", contextsToRemove)); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecksContexts("owner", "", "branch", contextsToRemove)); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecksContexts("owner", "repo", "", contextsToRemove)); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecksContexts(1, "", contextsToRemove)); } } public class TheGetReviewEnforcementMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.GetReviewEnforcement("owner", "repo", "branch"); connection.Received() .Get<BranchProtectionRequiredReviews>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_pull_request_reviews"), null, previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.GetReviewEnforcement(1, "branch"); connection.Received() .Get<BranchProtectionRequiredReviews>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_pull_request_reviews"), null, previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetReviewEnforcement(null, "repo", "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetReviewEnforcement("owner", null, "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetReviewEnforcement("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetReviewEnforcement(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetReviewEnforcement("", "repo", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetReviewEnforcement("owner", "", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetReviewEnforcement("owner", "repo", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetReviewEnforcement(1, "")); } } public class TheUpdateReviewEnforcementMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var update = new BranchProtectionRequiredReviewsUpdate(false, false, 2); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.UpdateReviewEnforcement("owner", "repo", "branch", update); connection.Received() .Patch<BranchProtectionRequiredReviews>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_pull_request_reviews"), Arg.Any<BranchProtectionRequiredReviewsUpdate>(), previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var update = new BranchProtectionRequiredReviewsUpdate(false, false, 2); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.UpdateReviewEnforcement(1, "branch", update); connection.Received() .Patch<BranchProtectionRequiredReviews>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_pull_request_reviews"), Arg.Any<BranchProtectionRequiredReviewsUpdate>(), previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); var update = new BranchProtectionRequiredReviewsUpdate(false, false, 2); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateReviewEnforcement(null, "repo", "branch", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateReviewEnforcement("owner", null, "branch", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateReviewEnforcement("owner", "repo", null, update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateReviewEnforcement("owner", "repo", "branch", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateReviewEnforcement(1, null, update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateReviewEnforcement(1, "branch", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateReviewEnforcement("", "repo", "branch", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateReviewEnforcement("owner", "", "branch", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateReviewEnforcement("owner", "repo", "", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateReviewEnforcement(1, "", update)); } } public class TheRemoveReviewEnforcementMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.RemoveReviewEnforcement("owner", "repo", "branch"); connection.Connection.Received() .Delete(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_pull_request_reviews"), Arg.Any<object>(), previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.RemoveReviewEnforcement(1, "branch"); connection.Connection.Received() .Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_pull_request_reviews"), Arg.Any<object>(), previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveReviewEnforcement(null, "repo", "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveReviewEnforcement("owner", null, "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveReviewEnforcement("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveReviewEnforcement(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveReviewEnforcement("", "repo", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveReviewEnforcement("owner", "", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveReviewEnforcement("owner", "repo", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveReviewEnforcement(1, "")); } } public class TheGetAdminEnforcementMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.GetAdminEnforcement("owner", "repo", "branch"); connection.Received() .Get<EnforceAdmins>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/enforce_admins"), null, previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.GetAdminEnforcement(1, "branch"); connection.Received() .Get<EnforceAdmins>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/enforce_admins"), null, previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAdminEnforcement(null, "repo", "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAdminEnforcement("owner", null, "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAdminEnforcement("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAdminEnforcement(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAdminEnforcement("", "repo", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAdminEnforcement("owner", "", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAdminEnforcement("owner", "repo", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAdminEnforcement(1, "")); } } public class TheAddAdminEnforcementMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.AddAdminEnforcement("owner", "repo", "branch"); connection.Received() .Post<EnforceAdmins>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/enforce_admins"), Arg.Any<object>(), previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.AddAdminEnforcement(1, "branch"); connection.Received() .Post<EnforceAdmins>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/enforce_admins"), Arg.Any<object>(), previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddAdminEnforcement(null, "repo", "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddAdminEnforcement("owner", null, "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddAdminEnforcement("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddAdminEnforcement(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.AddAdminEnforcement("", "repo", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.AddAdminEnforcement("owner", "", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.AddAdminEnforcement("owner", "repo", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.AddAdminEnforcement(1, "")); } } public class TheRemoveAdminEnforcementMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.RemoveAdminEnforcement("owner", "repo", "branch"); connection.Connection.Received() .Delete(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/enforce_admins"), Arg.Any<object>(), previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.RemoveAdminEnforcement(1, "branch"); connection.Connection.Received() .Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/enforce_admins"), Arg.Any<object>(), previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveAdminEnforcement(null, "repo", "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveAdminEnforcement("owner", null, "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveAdminEnforcement("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveAdminEnforcement(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveAdminEnforcement("", "repo", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveAdminEnforcement("owner", "", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveAdminEnforcement("owner", "repo", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveAdminEnforcement(1, "")); } } public class TheGetProtectedBranchRestrictionsMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.GetProtectedBranchRestrictions("owner", "repo", "branch"); connection.Received() .Get<BranchProtectionPushRestrictions>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions"), null, previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.GetProtectedBranchRestrictions(1, "branch"); connection.Received() .Get<BranchProtectionPushRestrictions>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions"), null, previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchRestrictions(null, "repo", "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchRestrictions("owner", null, "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchRestrictions("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchRestrictions(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchRestrictions("", "repo", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchRestrictions("owner", "", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchRestrictions("owner", "repo", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchRestrictions(1, "")); } } public class TheDeleteProtectedBranchRestrictionsMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.DeleteProtectedBranchRestrictions("owner", "repo", "branch"); connection.Connection.Received() .Delete(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions"), Arg.Any<object>(), previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.DeleteProtectedBranchRestrictions(1, "branch"); connection.Connection.Received() .Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions"), Arg.Any<object>(), previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchRestrictions(null, "repo", "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchRestrictions("owner", null, "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchRestrictions("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchRestrictions(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchRestrictions("", "repo", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchRestrictions("owner", "", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchRestrictions("owner", "repo", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchRestrictions(1, "")); } } public class TheGetAllProtectedBranchTeamRestrictionsMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); client.GetAllProtectedBranchTeamRestrictions("owner", "repo", "branch"); connection.Received() .Get<IReadOnlyList<Team>>( Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/teams"), null, "application/vnd.github.luke-cage-preview+json"); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); client.GetAllProtectedBranchTeamRestrictions(1, "branch"); connection.Received() .Get<IReadOnlyList<Team>>( Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/teams"), null, "application/vnd.github.luke-cage-preview+json"); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchTeamRestrictions(null, "repo", "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchTeamRestrictions("owner", null, "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchTeamRestrictions("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchTeamRestrictions(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchTeamRestrictions("", "repo", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchTeamRestrictions("owner", "", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchTeamRestrictions("owner", "repo", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchTeamRestrictions(1, "")); } } public class TheSetProtectedBranchTeamRestrictionsMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var newTeams = new BranchProtectionTeamCollection() { "test" }; client.UpdateProtectedBranchTeamRestrictions("owner", "repo", "branch", newTeams); connection.Received() .Put<IReadOnlyList<Team>>( Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/teams"), Arg.Any<IReadOnlyList<string>>(), null, "application/vnd.github.luke-cage-preview+json"); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var newTeams = new BranchProtectionTeamCollection() { "test" }; client.UpdateProtectedBranchTeamRestrictions(1, "branch", newTeams); connection.Received() .Put<IReadOnlyList<Team>>( Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/teams"), Arg.Any<IReadOnlyList<string>>(), null, "application/vnd.github.luke-cage-preview+json"); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); var newTeams = new BranchProtectionTeamCollection() { "test" }; await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions(null, "repo", "branch", newTeams)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions("owner", null, "branch", newTeams)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions("owner", "repo", null, newTeams)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions("owner", "repo", "branch", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions(1, null, newTeams)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions(1, "branch", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchTeamRestrictions("", "repo", "branch", newTeams)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchTeamRestrictions("owner", "", "branch", newTeams)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchTeamRestrictions("owner", "repo", "", newTeams)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchTeamRestrictions(1, "", newTeams)); } } public class TheAddProtectedBranchTeamRestrictionsMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var newTeams = new BranchProtectionTeamCollection() { "test" }; client.AddProtectedBranchTeamRestrictions("owner", "repo", "branch", newTeams); connection.Received() .Post<IReadOnlyList<Team>>( Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/teams"), Arg.Any<IReadOnlyList<string>>(), "application/vnd.github.luke-cage-preview+json"); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var newTeams = new BranchProtectionTeamCollection() { "test" }; client.AddProtectedBranchTeamRestrictions(1, "branch", newTeams); connection.Received() .Post<IReadOnlyList<Team>>( Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/teams"), Arg.Any<IReadOnlyList<string>>(), "application/vnd.github.luke-cage-preview+json"); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); var newTeams = new BranchProtectionTeamCollection() { "test" }; await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions(null, "repo", "branch", newTeams)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions("owner", null, "branch", newTeams)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions("owner", "repo", null, newTeams)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions("owner", "repo", "branch", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions(1, null, newTeams)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions(1, "branch", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchTeamRestrictions("", "repo", "branch", newTeams)); await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchTeamRestrictions("owner", "", "branch", newTeams)); await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchTeamRestrictions("owner", "repo", "", newTeams)); await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchTeamRestrictions(1, "", newTeams)); } } public class TheDeleteProtectedBranchTeamRestrictions { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var teamsToRemove = new BranchProtectionTeamCollection() { "test" }; client.DeleteProtectedBranchTeamRestrictions("owner", "repo", "branch", teamsToRemove); connection.Received() .Delete<IReadOnlyList<Team>>( Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/teams"), Arg.Any<BranchProtectionTeamCollection>(), "application/vnd.github.luke-cage-preview+json"); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var teamsToRemove = new BranchProtectionTeamCollection() { "test" }; client.DeleteProtectedBranchTeamRestrictions(1, "branch", teamsToRemove); connection.Received() .Delete<IReadOnlyList<Team>>( Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/teams"), Arg.Any<IReadOnlyList<string>>(), "application/vnd.github.luke-cage-preview+json"); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); var teamsToRemove = new BranchProtectionTeamCollection() { "test" }; await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions(null, "repo", "branch", teamsToRemove)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions("owner", null, "branch", teamsToRemove)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions("owner", "repo", null, teamsToRemove)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions("owner", "repo", "branch", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions(1, null, teamsToRemove)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions(1, "branch", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchTeamRestrictions("", "repo", "branch", teamsToRemove)); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchTeamRestrictions("owner", "", "branch", teamsToRemove)); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchTeamRestrictions("owner", "repo", "", teamsToRemove)); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchTeamRestrictions(1, "", teamsToRemove)); } } public class TheGetAllProtectedBranchUserRestrictionsMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.GetAllProtectedBranchUserRestrictions("owner", "repo", "branch"); connection.Received() .Get<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/users"), null, previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.GetAllProtectedBranchUserRestrictions(1, "branch"); connection.Received() .Get<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/users"), null, previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchUserRestrictions(null, "repo", "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchUserRestrictions("owner", null, "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchUserRestrictions("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchUserRestrictions(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchUserRestrictions("", "repo", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchUserRestrictions("owner", "", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchUserRestrictions("owner", "repo", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchUserRestrictions(1, "")); } } public class TheSetProtectedBranchUserRestrictionsMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var newUsers = new BranchProtectionUserCollection() { "test" }; const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.UpdateProtectedBranchUserRestrictions("owner", "repo", "branch", newUsers); connection.Received() .Put<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), null, previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var newUsers = new BranchProtectionUserCollection() { "test" }; const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.UpdateProtectedBranchUserRestrictions(1, "branch", newUsers); connection.Received() .Put<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), null, previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); var newUsers = new BranchProtectionUserCollection() { "test" }; await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions(null, "repo", "branch", newUsers)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions("owner", null, "branch", newUsers)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions("owner", "repo", null, newUsers)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions("owner", "repo", "branch", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions(1, null, newUsers)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions(1, "branch", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchUserRestrictions("", "repo", "branch", newUsers)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchUserRestrictions("owner", "", "branch", newUsers)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchUserRestrictions("owner", "repo", "", newUsers)); await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchUserRestrictions(1, "", newUsers)); } } public class TheAddProtectedBranchUserRestrictionsMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var newUsers = new BranchProtectionUserCollection() { "test" }; const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.AddProtectedBranchUserRestrictions("owner", "repo", "branch", newUsers); connection.Received() .Post<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var newUsers = new BranchProtectionUserCollection() { "test" }; const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.AddProtectedBranchUserRestrictions(1, "branch", newUsers); connection.Received() .Post<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); var newUsers = new BranchProtectionUserCollection() { "test" }; await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions(null, "repo", "branch", newUsers)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions("owner", null, "branch", newUsers)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions("owner", "repo", null, newUsers)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions("owner", "repo", "branch", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions(1, null, newUsers)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions(1, "branch", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchUserRestrictions("", "repo", "branch", newUsers)); await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchUserRestrictions("owner", "", "branch", newUsers)); await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchUserRestrictions("owner", "repo", "", newUsers)); await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchUserRestrictions(1, "", newUsers)); } } public class TheDeleteProtectedBranchUserRestrictions { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var usersToRemove = new BranchProtectionUserCollection() { "test" }; const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.DeleteProtectedBranchUserRestrictions("owner", "repo", "branch", usersToRemove); connection.Received() .Delete<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryBranchesClient(connection); var usersToRemove = new BranchProtectionUserCollection() { "test" }; const string previewAcceptsHeader = "application/vnd.github.luke-cage-preview+json"; client.DeleteProtectedBranchUserRestrictions(1, "branch", usersToRemove); connection.Received() .Delete<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>()); var usersToRemove = new BranchProtectionUserCollection() { "test" }; await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions(null, "repo", "branch", usersToRemove)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions("owner", null, "branch", usersToRemove)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions("owner", "repo", null, usersToRemove)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions("owner", "repo", "branch", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions(1, null, usersToRemove)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions(1, "branch", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchUserRestrictions("", "repo", "branch", usersToRemove)); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchUserRestrictions("owner", "", "branch", usersToRemove)); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchUserRestrictions("owner", "repo", "", usersToRemove)); await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchUserRestrictions(1, "", usersToRemove)); } } } }
// 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. // // 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.Batch.Protocol { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for PoolOperations. /// </summary> public static partial class PoolOperationsExtensions { /// <summary> /// Lists the usage metrics, aggregated by pool across individual time /// intervals, for the specified account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolListPoolUsageMetricsOptions'> /// Additional parameters for the operation /// </param> public static IPage<PoolUsageMetrics> ListPoolUsageMetrics(this IPoolOperations operations, PoolListPoolUsageMetricsOptions poolListPoolUsageMetricsOptions = default(PoolListPoolUsageMetricsOptions)) { return Task.Factory.StartNew(s => ((IPoolOperations)s).ListPoolUsageMetricsAsync(poolListPoolUsageMetricsOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the usage metrics, aggregated by pool across individual time /// intervals, for the specified account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolListPoolUsageMetricsOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<PoolUsageMetrics>> ListPoolUsageMetricsAsync(this IPoolOperations operations, PoolListPoolUsageMetricsOptions poolListPoolUsageMetricsOptions = default(PoolListPoolUsageMetricsOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListPoolUsageMetricsWithHttpMessagesAsync(poolListPoolUsageMetricsOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets lifetime summary statistics for all of the pools in the specified /// account. /// </summary> /// <remarks> /// Statistics are aggregated across all pools that have ever existed in the /// account, from account creation to the last update time of the statistics. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolGetAllPoolsLifetimeStatisticsOptions'> /// Additional parameters for the operation /// </param> public static PoolStatistics GetAllPoolsLifetimeStatistics(this IPoolOperations operations, PoolGetAllPoolsLifetimeStatisticsOptions poolGetAllPoolsLifetimeStatisticsOptions = default(PoolGetAllPoolsLifetimeStatisticsOptions)) { return Task.Factory.StartNew(s => ((IPoolOperations)s).GetAllPoolsLifetimeStatisticsAsync(poolGetAllPoolsLifetimeStatisticsOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets lifetime summary statistics for all of the pools in the specified /// account. /// </summary> /// <remarks> /// Statistics are aggregated across all pools that have ever existed in the /// account, from account creation to the last update time of the statistics. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolGetAllPoolsLifetimeStatisticsOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PoolStatistics> GetAllPoolsLifetimeStatisticsAsync(this IPoolOperations operations, PoolGetAllPoolsLifetimeStatisticsOptions poolGetAllPoolsLifetimeStatisticsOptions = default(PoolGetAllPoolsLifetimeStatisticsOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetAllPoolsLifetimeStatisticsWithHttpMessagesAsync(poolGetAllPoolsLifetimeStatisticsOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Adds a pool to the specified account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='pool'> /// The pool to be added. /// </param> /// <param name='poolAddOptions'> /// Additional parameters for the operation /// </param> public static PoolAddHeaders Add(this IPoolOperations operations, PoolAddParameter pool, PoolAddOptions poolAddOptions = default(PoolAddOptions)) { return Task.Factory.StartNew(s => ((IPoolOperations)s).AddAsync(pool, poolAddOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Adds a pool to the specified account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='pool'> /// The pool to be added. /// </param> /// <param name='poolAddOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PoolAddHeaders> AddAsync(this IPoolOperations operations, PoolAddParameter pool, PoolAddOptions poolAddOptions = default(PoolAddOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.AddWithHttpMessagesAsync(pool, poolAddOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Lists all of the pools in the specified account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolListOptions'> /// Additional parameters for the operation /// </param> public static IPage<CloudPool> List(this IPoolOperations operations, PoolListOptions poolListOptions = default(PoolListOptions)) { return Task.Factory.StartNew(s => ((IPoolOperations)s).ListAsync(poolListOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all of the pools in the specified account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolListOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<CloudPool>> ListAsync(this IPoolOperations operations, PoolListOptions poolListOptions = default(PoolListOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(poolListOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a pool from the specified account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool to delete. /// </param> /// <param name='poolDeleteOptions'> /// Additional parameters for the operation /// </param> public static PoolDeleteHeaders Delete(this IPoolOperations operations, string poolId, PoolDeleteOptions poolDeleteOptions = default(PoolDeleteOptions)) { return Task.Factory.StartNew(s => ((IPoolOperations)s).DeleteAsync(poolId, poolDeleteOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a pool from the specified account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool to delete. /// </param> /// <param name='poolDeleteOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PoolDeleteHeaders> DeleteAsync(this IPoolOperations operations, string poolId, PoolDeleteOptions poolDeleteOptions = default(PoolDeleteOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeleteWithHttpMessagesAsync(poolId, poolDeleteOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Gets basic properties of a pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool to get. /// </param> /// <param name='poolExistsOptions'> /// Additional parameters for the operation /// </param> public static bool Exists(this IPoolOperations operations, string poolId, PoolExistsOptions poolExistsOptions = default(PoolExistsOptions)) { return Task.Factory.StartNew(s => ((IPoolOperations)s).ExistsAsync(poolId, poolExistsOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets basic properties of a pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool to get. /// </param> /// <param name='poolExistsOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<bool> ExistsAsync(this IPoolOperations operations, string poolId, PoolExistsOptions poolExistsOptions = default(PoolExistsOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ExistsWithHttpMessagesAsync(poolId, poolExistsOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets information about the specified pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool to get. /// </param> /// <param name='poolGetOptions'> /// Additional parameters for the operation /// </param> public static CloudPool Get(this IPoolOperations operations, string poolId, PoolGetOptions poolGetOptions = default(PoolGetOptions)) { return Task.Factory.StartNew(s => ((IPoolOperations)s).GetAsync(poolId, poolGetOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets information about the specified pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool to get. /// </param> /// <param name='poolGetOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CloudPool> GetAsync(this IPoolOperations operations, string poolId, PoolGetOptions poolGetOptions = default(PoolGetOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(poolId, poolGetOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the properties of a pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool to update. /// </param> /// <param name='poolPatchParameter'> /// The parameters for the request. /// </param> /// <param name='poolPatchOptions'> /// Additional parameters for the operation /// </param> public static PoolPatchHeaders Patch(this IPoolOperations operations, string poolId, PoolPatchParameter poolPatchParameter, PoolPatchOptions poolPatchOptions = default(PoolPatchOptions)) { return Task.Factory.StartNew(s => ((IPoolOperations)s).PatchAsync(poolId, poolPatchParameter, poolPatchOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates the properties of a pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool to update. /// </param> /// <param name='poolPatchParameter'> /// The parameters for the request. /// </param> /// <param name='poolPatchOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PoolPatchHeaders> PatchAsync(this IPoolOperations operations, string poolId, PoolPatchParameter poolPatchParameter, PoolPatchOptions poolPatchOptions = default(PoolPatchOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PatchWithHttpMessagesAsync(poolId, poolPatchParameter, poolPatchOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Disables automatic scaling for a pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool on which to disable automatic scaling. /// </param> /// <param name='poolDisableAutoScaleOptions'> /// Additional parameters for the operation /// </param> public static PoolDisableAutoScaleHeaders DisableAutoScale(this IPoolOperations operations, string poolId, PoolDisableAutoScaleOptions poolDisableAutoScaleOptions = default(PoolDisableAutoScaleOptions)) { return Task.Factory.StartNew(s => ((IPoolOperations)s).DisableAutoScaleAsync(poolId, poolDisableAutoScaleOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Disables automatic scaling for a pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool on which to disable automatic scaling. /// </param> /// <param name='poolDisableAutoScaleOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PoolDisableAutoScaleHeaders> DisableAutoScaleAsync(this IPoolOperations operations, string poolId, PoolDisableAutoScaleOptions poolDisableAutoScaleOptions = default(PoolDisableAutoScaleOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DisableAutoScaleWithHttpMessagesAsync(poolId, poolDisableAutoScaleOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Enables automatic scaling for a pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool on which to enable automatic scaling. /// </param> /// <param name='poolEnableAutoScaleParameter'> /// The parameters for the request. /// </param> /// <param name='poolEnableAutoScaleOptions'> /// Additional parameters for the operation /// </param> public static PoolEnableAutoScaleHeaders EnableAutoScale(this IPoolOperations operations, string poolId, PoolEnableAutoScaleParameter poolEnableAutoScaleParameter, PoolEnableAutoScaleOptions poolEnableAutoScaleOptions = default(PoolEnableAutoScaleOptions)) { return Task.Factory.StartNew(s => ((IPoolOperations)s).EnableAutoScaleAsync(poolId, poolEnableAutoScaleParameter, poolEnableAutoScaleOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Enables automatic scaling for a pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool on which to enable automatic scaling. /// </param> /// <param name='poolEnableAutoScaleParameter'> /// The parameters for the request. /// </param> /// <param name='poolEnableAutoScaleOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PoolEnableAutoScaleHeaders> EnableAutoScaleAsync(this IPoolOperations operations, string poolId, PoolEnableAutoScaleParameter poolEnableAutoScaleParameter, PoolEnableAutoScaleOptions poolEnableAutoScaleOptions = default(PoolEnableAutoScaleOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.EnableAutoScaleWithHttpMessagesAsync(poolId, poolEnableAutoScaleParameter, poolEnableAutoScaleOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Gets the result of evaluating an automatic scaling formula on the pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool on which to evaluate the automatic scaling formula. /// </param> /// <param name='autoScaleFormula'> /// A formula for the desired number of compute nodes in the pool. /// </param> /// <param name='poolEvaluateAutoScaleOptions'> /// Additional parameters for the operation /// </param> public static AutoScaleRun EvaluateAutoScale(this IPoolOperations operations, string poolId, string autoScaleFormula, PoolEvaluateAutoScaleOptions poolEvaluateAutoScaleOptions = default(PoolEvaluateAutoScaleOptions)) { return Task.Factory.StartNew(s => ((IPoolOperations)s).EvaluateAutoScaleAsync(poolId, autoScaleFormula, poolEvaluateAutoScaleOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the result of evaluating an automatic scaling formula on the pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool on which to evaluate the automatic scaling formula. /// </param> /// <param name='autoScaleFormula'> /// A formula for the desired number of compute nodes in the pool. /// </param> /// <param name='poolEvaluateAutoScaleOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AutoScaleRun> EvaluateAutoScaleAsync(this IPoolOperations operations, string poolId, string autoScaleFormula, PoolEvaluateAutoScaleOptions poolEvaluateAutoScaleOptions = default(PoolEvaluateAutoScaleOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.EvaluateAutoScaleWithHttpMessagesAsync(poolId, autoScaleFormula, poolEvaluateAutoScaleOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Changes the number of compute nodes that are assigned to a pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool to resize. /// </param> /// <param name='poolResizeParameter'> /// The parameters for the request. /// </param> /// <param name='poolResizeOptions'> /// Additional parameters for the operation /// </param> public static PoolResizeHeaders Resize(this IPoolOperations operations, string poolId, PoolResizeParameter poolResizeParameter, PoolResizeOptions poolResizeOptions = default(PoolResizeOptions)) { return Task.Factory.StartNew(s => ((IPoolOperations)s).ResizeAsync(poolId, poolResizeParameter, poolResizeOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Changes the number of compute nodes that are assigned to a pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool to resize. /// </param> /// <param name='poolResizeParameter'> /// The parameters for the request. /// </param> /// <param name='poolResizeOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PoolResizeHeaders> ResizeAsync(this IPoolOperations operations, string poolId, PoolResizeParameter poolResizeParameter, PoolResizeOptions poolResizeOptions = default(PoolResizeOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ResizeWithHttpMessagesAsync(poolId, poolResizeParameter, poolResizeOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Stops an ongoing resize operation on the pool. /// </summary> /// <remarks> /// This does not restore the pool to its previous state before the resize /// operation: it only stops any further changes being made, and the pool /// maintains its current state. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool whose resizing you want to stop. /// </param> /// <param name='poolStopResizeOptions'> /// Additional parameters for the operation /// </param> public static PoolStopResizeHeaders StopResize(this IPoolOperations operations, string poolId, PoolStopResizeOptions poolStopResizeOptions = default(PoolStopResizeOptions)) { return Task.Factory.StartNew(s => ((IPoolOperations)s).StopResizeAsync(poolId, poolStopResizeOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Stops an ongoing resize operation on the pool. /// </summary> /// <remarks> /// This does not restore the pool to its previous state before the resize /// operation: it only stops any further changes being made, and the pool /// maintains its current state. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool whose resizing you want to stop. /// </param> /// <param name='poolStopResizeOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PoolStopResizeHeaders> StopResizeAsync(this IPoolOperations operations, string poolId, PoolStopResizeOptions poolStopResizeOptions = default(PoolStopResizeOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.StopResizeWithHttpMessagesAsync(poolId, poolStopResizeOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Updates the properties of a pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool to update. /// </param> /// <param name='poolUpdatePropertiesParameter'> /// The parameters for the request. /// </param> /// <param name='poolUpdatePropertiesOptions'> /// Additional parameters for the operation /// </param> public static PoolUpdatePropertiesHeaders UpdateProperties(this IPoolOperations operations, string poolId, PoolUpdatePropertiesParameter poolUpdatePropertiesParameter, PoolUpdatePropertiesOptions poolUpdatePropertiesOptions = default(PoolUpdatePropertiesOptions)) { return Task.Factory.StartNew(s => ((IPoolOperations)s).UpdatePropertiesAsync(poolId, poolUpdatePropertiesParameter, poolUpdatePropertiesOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates the properties of a pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool to update. /// </param> /// <param name='poolUpdatePropertiesParameter'> /// The parameters for the request. /// </param> /// <param name='poolUpdatePropertiesOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PoolUpdatePropertiesHeaders> UpdatePropertiesAsync(this IPoolOperations operations, string poolId, PoolUpdatePropertiesParameter poolUpdatePropertiesParameter, PoolUpdatePropertiesOptions poolUpdatePropertiesOptions = default(PoolUpdatePropertiesOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdatePropertiesWithHttpMessagesAsync(poolId, poolUpdatePropertiesParameter, poolUpdatePropertiesOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Upgrades the operating system of the specified pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool to upgrade. /// </param> /// <param name='targetOSVersion'> /// The Azure Guest OS version to be installed on the virtual machines in the /// pool. /// </param> /// <param name='poolUpgradeOSOptions'> /// Additional parameters for the operation /// </param> public static PoolUpgradeOSHeaders UpgradeOS(this IPoolOperations operations, string poolId, string targetOSVersion, PoolUpgradeOSOptions poolUpgradeOSOptions = default(PoolUpgradeOSOptions)) { return Task.Factory.StartNew(s => ((IPoolOperations)s).UpgradeOSAsync(poolId, targetOSVersion, poolUpgradeOSOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Upgrades the operating system of the specified pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool to upgrade. /// </param> /// <param name='targetOSVersion'> /// The Azure Guest OS version to be installed on the virtual machines in the /// pool. /// </param> /// <param name='poolUpgradeOSOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PoolUpgradeOSHeaders> UpgradeOSAsync(this IPoolOperations operations, string poolId, string targetOSVersion, PoolUpgradeOSOptions poolUpgradeOSOptions = default(PoolUpgradeOSOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpgradeOSWithHttpMessagesAsync(poolId, targetOSVersion, poolUpgradeOSOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Removes compute nodes from the specified pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool from which you want to remove nodes. /// </param> /// <param name='nodeRemoveParameter'> /// The parameters for the request. /// </param> /// <param name='poolRemoveNodesOptions'> /// Additional parameters for the operation /// </param> public static PoolRemoveNodesHeaders RemoveNodes(this IPoolOperations operations, string poolId, NodeRemoveParameter nodeRemoveParameter, PoolRemoveNodesOptions poolRemoveNodesOptions = default(PoolRemoveNodesOptions)) { return Task.Factory.StartNew(s => ((IPoolOperations)s).RemoveNodesAsync(poolId, nodeRemoveParameter, poolRemoveNodesOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Removes compute nodes from the specified pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='poolId'> /// The id of the pool from which you want to remove nodes. /// </param> /// <param name='nodeRemoveParameter'> /// The parameters for the request. /// </param> /// <param name='poolRemoveNodesOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PoolRemoveNodesHeaders> RemoveNodesAsync(this IPoolOperations operations, string poolId, NodeRemoveParameter nodeRemoveParameter, PoolRemoveNodesOptions poolRemoveNodesOptions = default(PoolRemoveNodesOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RemoveNodesWithHttpMessagesAsync(poolId, nodeRemoveParameter, poolRemoveNodesOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Headers; } } /// <summary> /// Lists the usage metrics, aggregated by pool across individual time /// intervals, for the specified account. /// </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='poolListPoolUsageMetricsNextOptions'> /// Additional parameters for the operation /// </param> public static IPage<PoolUsageMetrics> ListPoolUsageMetricsNext(this IPoolOperations operations, string nextPageLink, PoolListPoolUsageMetricsNextOptions poolListPoolUsageMetricsNextOptions = default(PoolListPoolUsageMetricsNextOptions)) { return Task.Factory.StartNew(s => ((IPoolOperations)s).ListPoolUsageMetricsNextAsync(nextPageLink, poolListPoolUsageMetricsNextOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the usage metrics, aggregated by pool across individual time /// intervals, for the specified account. /// </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='poolListPoolUsageMetricsNextOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<PoolUsageMetrics>> ListPoolUsageMetricsNextAsync(this IPoolOperations operations, string nextPageLink, PoolListPoolUsageMetricsNextOptions poolListPoolUsageMetricsNextOptions = default(PoolListPoolUsageMetricsNextOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListPoolUsageMetricsNextWithHttpMessagesAsync(nextPageLink, poolListPoolUsageMetricsNextOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all of the pools in the specified account. /// </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='poolListNextOptions'> /// Additional parameters for the operation /// </param> public static IPage<CloudPool> ListNext(this IPoolOperations operations, string nextPageLink, PoolListNextOptions poolListNextOptions = default(PoolListNextOptions)) { return Task.Factory.StartNew(s => ((IPoolOperations)s).ListNextAsync(nextPageLink, poolListNextOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all of the pools in the specified account. /// </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='poolListNextOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<CloudPool>> ListNextAsync(this IPoolOperations operations, string nextPageLink, PoolListNextOptions poolListNextOptions = default(PoolListNextOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, poolListNextOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace adventofcode2017.days.day20 { public class Vector { public int X { get; set; } public int Y { get; set; } public int Z { get; set; } } public class Particle { public Vector Position { get; set; } public Vector Velocity { get; set; } public Vector Acceleration { get; set; } } public class Day20 { private IEnumerable<Particle> _particles; private Vector ParseVector (string input, int start) { var startIndex = input.IndexOf('<', start)+1; var endIndex = input.IndexOf('>', start); var coords = input.Substring(startIndex, endIndex - startIndex); var numbers = coords.Split(',') .Select(num => Int32.Parse(num)) .ToList(); return new Vector () { X = numbers[0], Y = numbers[1], Z = numbers[2] }; } private Vector ParsePosition (string input) { var start = input.IndexOf("p=")+2; return ParseVector(input, start); } private Vector ParseVelocity (string input) { var start = input.IndexOf("v=")+2; return ParseVector(input, start); } private Vector ParseAcceleration (string input) { var start = input.IndexOf("a=")+2; return ParseVector(input, start); } private List<int> GetLinearSolution (int b, int c) { var intersection = new List<int>(); if (c == 0) { intersection.Add(0); return intersection; } // Check whether evenly divisible if ((c % b) != 0) { return intersection; } if ((-c)/b > 0) { intersection.Add((-c)/b); } return intersection; } private List<int> GetQuadraticRoots (int a, int b, int c) { var discriminant = (b*b) - (4*a*c); var roots = new List<int>(); if (discriminant < 0) { return roots; } if (discriminant == 0) { // Check if evenly divisible. If not, // throw an exception. if (b % (2*a) != 0) { return roots; } roots.Add(-(b / (2*a))); } else { // Check whether discriminant is a perfect square. // If it isn't, then I'm not sure we'll find an // integer match? var sqrt = (int)Math.Floor(Math.Sqrt(discriminant)); if ((sqrt*sqrt) != discriminant) { return roots; } // Check whether we get an evenly divisible result var posRemainder = (-b + sqrt) % (2*a); var negRemainder = (-b - sqrt) % (2*a); if (posRemainder == 0) { roots.Add( (-b + sqrt) / (2*a) ); } if (negRemainder == 0) { roots.Add( (-b - sqrt) / (2*a) ); } } return roots .Where(r => r >= 0) .ToList(); } private int GetQuadraticResult (int a, int b, int c, int t) { return (a * (t * t)) + (2*b + a)*t + (2*c); } private bool AreQuadraticsEqual(int a1, int b1, int c1, int a2, int b2, int c2, int t) { // Check whether quadratics are equal at time t // (1/2)at^2 + abt + c // at^2 + 2abt + 2c var r1 = GetQuadraticResult(a1, b1, c1, t); var r2 = GetQuadraticResult(a2, b2, c2, t); return GetQuadraticResult(a1, b1, c1, t) == GetQuadraticResult(a2, b2, c2, t); } private bool DoParticlesIntersect(Particle a, Particle b) { /* First figure out whether and when they intersect along a singe dimension. This breaks down into a recurrence relation: p(t) = p(t-1) + v(t) p(0) = p0 Where v(t) = v(t-1) + a0 v(0) = v0 + a0 Bang your head against the wall for awhile and you wind up with: p(t) = p0 + (v0)t + (t(t+1)/2)a0 Combine terms and do some multiplication to get rid of the fracts: p(t) = 2p0 + (a0 + 2(v0))t + (a0)t^2 Now we have an equation that will give us the position of a particle at time t. To figure out whether 2 particles intersect, we can subtract one particle's position equation from another (along the same axis) and then solve for the roots (The inputs required to make the equation 0). */ var aX = a.Acceleration.X - b.Acceleration.X; var bX = (2*a.Velocity.X + a.Acceleration.X) - (2*b.Velocity.X + b.Acceleration.X); var cX = (2*a.Position.X) - (2*b.Position.X); var intersections = new List<int>(); if (aX == 0 && bX == 0) { intersections.Add(0); } else if (aX == 0) { intersections = GetLinearSolution(bX, cX); } else { intersections = GetQuadraticRoots(aX, bX, cX); } if (intersections.Count == 0) return false; // Try to see whether they intersect along the other dimensions // at the same time. foreach (var intersection in intersections) { var y1 = GetQuadraticResult(a.Acceleration.Y, a.Velocity.Y, a.Position.Y, intersection); var z1 = GetQuadraticResult(a.Acceleration.Z, a.Velocity.Z, a.Position.Z, intersection); var y2 = GetQuadraticResult(b.Acceleration.Y, b.Velocity.Y, b.Position.Y, intersection); var z2 = GetQuadraticResult(b.Acceleration.Z, b.Velocity.Z, b.Position.Z, intersection); if (y1 == y2 && z1 == z2) { return true; } } return false; } public Day20 () { _particles = File.ReadAllLines("inputs/day20/input.txt") .Select(line => new Particle() { Position = ParsePosition(line), Velocity = ParseVelocity(line), Acceleration = ParseAcceleration(line) }); } public int GetParticleThatStaysClosestToOrigin () { // As t heads towards infinity, don't I only care about // the smallest acceleration? return _particles .Select(particle => Math.Abs(particle.Acceleration.X) + Math.Abs(particle.Acceleration.Y) + Math.Abs(particle.Acceleration.Z)) .Select((sum,index) => new { Sum = sum, ParticleNum = index }) .OrderBy(s => s.Sum) .First() .ParticleNum; } public int GetNumParticlesAfterCollisions () { // I 'think' we can speed up this process by finding // the potential points of intersection between // each particle, rather than brute force iterating // through each time step. return _particles.Count() - _particles .Where((p1, i) => _particles .Where((p2, j) => i != j) .Any(p2 => DoParticlesIntersect(p1,p2))) .Count(); } } }
using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Design; namespace BrightIdeasSoftware { /// <summary> /// PenData represents the data required to create a pen. /// </summary> /// <remarks>Pens cannot be edited directly within the IDE (is this VCS EE only?) /// These objects allow pen characters to be edited within the IDE and then real /// Pen objects created.</remarks> [Editor(typeof(PenDataEditor), typeof(UITypeEditor)), TypeConverter(typeof(PenDataConverter))] public class PenData { public PenData() : this(new SolidBrushData()) { } public PenData(IBrushData brush) { this.Brush = brush; } public Pen GetPen() { Pen p = new Pen(this.Brush.GetBrush(), this.Width); p.SetLineCap(this.StartCap, this.EndCap, this.DashCap); p.DashStyle = this.DashStyle; p.LineJoin = this.LineJoin; return p; } [TypeConverter(typeof(ExpandableObjectConverter))] public IBrushData Brush { get { return brushData; } set { brushData = value; } } private IBrushData brushData; [DefaultValue(typeof(DashCap), "Round")] public DashCap DashCap { get { return dashCap; } set { dashCap = value; } } private DashCap dashCap = DashCap.Round; [DefaultValue(typeof(DashStyle), "Solid")] public DashStyle DashStyle { get { return dashStyle; } set { dashStyle = value; } } private DashStyle dashStyle = DashStyle.Solid; [DefaultValue(typeof(LineCap), "NoAnchor")] public LineCap EndCap { get { return endCap; } set { endCap = value; } } private LineCap endCap = LineCap.NoAnchor; [DefaultValue(typeof(LineJoin), "Round")] public LineJoin LineJoin { get { return lineJoin; } set { lineJoin = value; } } private LineJoin lineJoin = LineJoin.Round; [DefaultValue(typeof(LineCap), "NoAnchor")] public LineCap StartCap { get { return startCap; } set { startCap = value; } } private LineCap startCap = LineCap.NoAnchor; [DefaultValue(1.0f)] public float Width { get { return width; } set { width = value; } } private float width = 1.0f; } [Editor(typeof(BrushDataEditor), typeof(UITypeEditor)), TypeConverter(typeof(BrushDataConverter))] public interface IBrushData { Brush GetBrush(); } public class SolidBrushData : IBrushData { public Brush GetBrush() { if (this.Alpha < 255) return new SolidBrush(Color.FromArgb(this.Alpha, this.Color)); else return new SolidBrush(this.Color); } [DefaultValue(typeof(Color), "")] public Color Color { get { return color; } set { color = value; } } private Color color = Color.Empty; [DefaultValue(255)] public int Alpha { get { return alpha; } set { alpha = value; } } private int alpha = 255; } public class LinearGradientBrushData : IBrushData { public Brush GetBrush() { return new LinearGradientBrush(new Rectangle(0, 0, 100, 100), this.FromColor, this.ToColor, this.GradientMode); } public Color FromColor { get { return fromColor; } set { fromColor = value; } } private Color fromColor = Color.Aqua; public Color ToColor { get { return toColor; } set { toColor = value; } } private Color toColor = Color.Pink; public LinearGradientMode GradientMode { get { return gradientMode; } set { gradientMode = value; } } private LinearGradientMode gradientMode = LinearGradientMode.Horizontal; } public class HatchBrushData : IBrushData { public Brush GetBrush() { return new HatchBrush(this.HatchStyle, this.ForegroundColor, this.BackgroundColor); } public Color BackgroundColor { get { return backgroundColor; } set { backgroundColor = value; } } private Color backgroundColor = Color.AliceBlue; public Color ForegroundColor { get { return foregroundColor; } set { foregroundColor = value; } } private Color foregroundColor = Color.Aqua; public HatchStyle HatchStyle { get { return hatchStyle; } set { hatchStyle = value; } } private HatchStyle hatchStyle = HatchStyle.Cross; } public class TextureBrushData : IBrushData { public Brush GetBrush() { if (this.Image == null) return null; else return new TextureBrush(this.Image, this.WrapMode); } public Image Image { get { return image; } set { image = value; } } private Image image; public WrapMode WrapMode { get { return wrapMode; } set { wrapMode = value; } } private WrapMode wrapMode = WrapMode.Tile; } }
using System; using System.Linq; using IFramework.AspNet; using IFramework.Command; using IFramework.Config; using IFramework.DependencyInjection; using IFramework.DependencyInjection.Autofac; using IFramework.DependencyInjection.Unity; using IFramework.EntityFrameworkCore; using IFramework.JsonNet; using IFramework.Message; using IFramework.MessageQueue; using IFramework.MessageQueue.ConfluentKafka; using IFramework.MessageQueue.RabbitMQ; using IFramework.MessageQueue.InMemory; using IFramework.MessageStores.Relational; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Sample.Applications; using Sample.Command; using Sample.CommandServiceCore.Authorizations; using Sample.CommandServiceCore.CommandInputExtension; using Sample.CommandServiceCore.Controllers; using Sample.CommandServiceCore.ExceptionHandlers; using Sample.CommandServiceCore.Filters; using Sample.Domain; using Sample.Persistence; using Sample.Persistence.Repositories; using ApiResultWrapAttribute = Sample.CommandServiceCore.Filters.ApiResultWrapAttribute; using System.Collections.Generic; using IFramework.Infrastructure; using IFramework.Event; using IFramework.EventStore; using IFramework.Infrastructure.Mailboxes; using IFramework.Infrastructure.Mailboxes.Impl; using IFramework.Logging.Log4Net; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using Newtonsoft.Json.Serialization; using RabbitMQ.Client; using IFramework.Infrastructure.EventSourcing.Configurations; using IFramework.EventStore.Redis; using IFramework.Infrastructure.EventSourcing; using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; using IFramework.Infrastructure.EventSourcing.Stores; using IFramework.Logging.AliyunLog; using IFramework.Logging.Serilog; using Microsoft.EntityFrameworkCore.Diagnostics; using Sample.DomainEvents.Banks; using Sample.Command.Community; namespace Sample.CommandServiceCore { public class Startup { private static IMessagePublisher _messagePublisher; private static ICommandBus _commandBus; private static IMessageProcessor _commandConsumer1; private static IMessageProcessor _commandConsumer2; private static IMessageProcessor _commandConsumer3; private static IMessageProcessor _domainEventProcessor; private static IMessageProcessor _applicationEventProcessor; private static IMessageProcessor _eventSourcingCommandConsumer; private static IMessageProcessor _eventSourcingEventProcessor; public static string PathBase; private static string _app = "uat"; private static readonly string TopicPrefix = _app.Length == 0 ? string.Empty : $"{_app}."; private readonly IConfiguration _configuration; public Startup(IConfiguration configuration, IWebHostEnvironment env) { _configuration = configuration; } public void ConfigureServices(IServiceCollection services) { var rabbitConnectionFactory = new ConnectionFactory { Endpoint = new AmqpTcpEndpoint("10.100.7.46", 9012) }; services//.AddUnityContainer() .AddAutofacContainer(assemblyName => assemblyName.StartsWith("Sample")) .AddConfiguration(_configuration) //.AddLog4Net() .AddSerilog() //.AddAliyunLog() .AddCommonComponents(_app) .AddJsonNet() .AddEntityFrameworkComponents(typeof(RepositoryBase<>)) .AddRelationalMessageStore<SampleModelContext>() //.AddEQueue() .AddConfluentKafka(new MessageQueueOptions(false, false, false)) .AddInMemoryMessageQueue() //.AddRabbitMQ(rabbitConnectionFactory) .AddMessagePublisher("eventTopic") .AddCommandBus(Environment.MachineName, serialCommandManager: new SerialCommandManager()) .AddDbContextPool<SampleModelContext>(options => { var connectionString = Configuration.Instance.GetConnectionString($"{nameof(SampleModelContext)}.MySql"); //options.EnableSensitiveDataLogging(); //options.UseLazyLoadingProxies(); //options.UseSqlServer(Configuration.Instance.GetConnectionString(nameof(SampleModelContext))) // .ConfigureWarnings(w => w.Ignore(SqlServerEventId.SavepointsDisabledBecauseOfMARS)); //options.UseMySql(connectionString, // ServerVersion.AutoDetect(connectionString), // b => b.EnableRetryOnFailure()) // .AddInterceptors(new ReadCommittedTransactionInterceptor()) // .UseLazyLoadingProxies(); //options.UseMongoDb(Configuration.Instance.GetConnectionString($"{nameof(SampleModelContext)}.MongoDb")); options.UseInMemoryDatabase(nameof(SampleModelContext)); options.ConfigureWarnings(b => { b.Ignore(InMemoryEventId.TransactionIgnoredWarning); }); }, 5000) .AddEventSourcing() ; //services.AddLog4Net(new Log4NetProviderOptions {EnableScope = false}); services.AddCustomOptions<MailboxOption>(options => options.BatchCount = 1000); services.AddCustomOptions<FrameworkConfiguration>(); services.AddHealthChecks(); services.AddControllersWithViews(options => { options.InputFormatters.Insert(0, new CommandInputFormatter()); options.InputFormatters.Add(new FormDataInputFormatter()); options.Filters.Add<ExceptionFilter>(); }); services.AddRazorPages() .AddControllersAsServices() .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver()); services.AddHttpContextAccessor(); services.AddControllersWithViews(); services.AddRazorPages(); services.AddAuthorization(options => { options.AddPolicy("AppAuthorization", policyBuilder => { policyBuilder.Requirements.Add(new AppAuthorizationRequirement()); }); }); services.AddSingleton<IApiResultWrapAttribute, ApiResultWrapAttribute>(); services.AddScoped<HomeController, HomeController>(new VirtualMethodInterceptorInjection(), new InterceptionBehaviorInjection()); services.AddSingleton<IAuthorizationHandler, AppAuthorizationHandler>(); services.AddScoped<ICommunityRepository, CommunityRepository>(); services.AddScoped<ICommunityService, CommunityService>(new InterfaceInterceptorInjection(), new InterceptionBehaviorInjection()); services.RegisterMessageHandlers(new []{"CommandHandlers", "DomainEventSubscriber", "ApplicationEventSubscriber"}); //services.AddMiniProfiler() // .AddEntityFramework(); } //public void ConfigureContainer(IObjectProviderBuilder providerBuilder) //{ // var lifetime = ServiceLifetime.Scoped; // providerBuilder.Register<HomeController, HomeController>(lifetime, // new VirtualMethodInterceptorInjection(), // new InterceptionBehaviorInjection()); // } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostEnvironment env, ILoggerFactory loggerFactory, IMessageTypeProvider messageTypeProvider, IOptions<FrameworkConfiguration> frameworkConfigOptions, IMailboxProcessor mailboxProcessor, IHostApplicationLifetime applicationLifetime //IEventStore eventStore, //ISnapshotStore snapshotStore ) { //eventStore.Connect() // .GetAwaiter() // .GetResult(); //snapshotStore.Connect() // .GetAwaiter() // .GetResult(); //loggerFactory.AddLog4NetProvider(new Log4NetProviderOptions {EnableScope = true}); var logger = loggerFactory.CreateLogger<Startup>(); logger.SetMinLevel(LogLevel.Information); logger.LogInformation($"Startup configured env: {env.EnvironmentName}"); applicationLifetime.ApplicationStopping.Register(() => { _commandConsumer1?.Stop(); _commandConsumer2?.Stop(); _commandConsumer3?.Stop(); _domainEventProcessor?.Stop(); _applicationEventProcessor?.Stop(); _messagePublisher?.Stop(); _commandBus?.Stop(); _eventSourcingCommandConsumer?.Stop(); _eventSourcingEventProcessor?.Stop(); mailboxProcessor.Stop(); }); mailboxProcessor.Start(); messageTypeProvider.Register(new Dictionary<string, string> { ["Login"] = "Sample.Command.Login, Sample.Command" }) .Register("Modify", typeof(Modify)) .Register(nameof(CreateAccount), typeof(CreateAccount)) .Register(nameof(CommonCommand), typeof(CommonCommand)) .Register(nameof(AccountCreated), typeof(AccountCreated)); StartMessageQueueComponents(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler(new GlobalExceptionHandlerOptions(loggerFactory, env)); } //app.UseMiniProfiler(); PathBase = Configuration.Instance[nameof(PathBase)]; app.UsePathBase(PathBase); app.Use(next => context => { context.Request.Path = context.Request.Path.Value.Replace("//", "/"); return next(context); }); app.Use(next => context => { context.Request.EnableBuffering(); context.Response.EnableRewind(); return next(context); }); //app.Use(async (context, next) => //{ // await next(); // if (context.Response.StatusCode == StatusCodes.Status404NotFound) // { // context.Request.Path = "/Home/Error"; // await next(); // } //}); app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); app.UseStaticFiles(); //app.UseRouting(); app.UseCors("default"); //app.UseEndpoints(endpoints => //{ // endpoints.MapControllerRoute("default", // "{controller=Home}/{action=Index}/{id?}"); // endpoints.MapRazorPages(); //}); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapHealthChecks("/health"); endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); //app.UseMvc(routes => //{ // routes.MapRoute("default", // "{controller=Home}/{action=Index}/{id?}"); //}); app.UseLogLevelController(); app.UseMessageProcessorDashboardMiddleware(); } private void StartMessageQueueComponents() { #region Command Consuemrs init _eventSourcingCommandConsumer = EventSourcingFactory.CreateCommandConsumer($"{TopicPrefix}BankCommandQueue", "0", new[] { "BankAccountCommandHandlers", "BankTransactionCommandHandlers" }); _eventSourcingCommandConsumer.Start(); var commandQueueName = $"{TopicPrefix}commandqueue"; _commandConsumer1 = MessageQueueFactory.CreateCommandConsumer(commandQueueName, "0", new[] { "CommandHandlers" }, new ConsumerConfig { FullLoadThreshold = 5000, MailboxProcessBatchCount = 50 }); _commandConsumer1.Start(); //_commandConsumer2 = // MessageQueueFactory.CreateCommandConsumer(commandQueueName, "1", new[] { "CommandHandlers" }, new ConsumerConfig // { // FullLoadThreshold = 1000, // MailboxProcessBatchCount = 50 // }); //_commandConsumer2.Start(); //_commandConsumer3 = // MessageQueueFactory.CreateCommandConsumer(commandQueueName, "2", new[] { "CommandHandlers" }, new ConsumerConfig // { // FullLoadThreshold = 1000, // MailboxProcessBatchCount = 50 // }); //_commandConsumer3.Start(); #endregion #region event subscriber init _domainEventProcessor = MessageQueueFactory.CreateEventSubscriber(new[] { new TopicSubscription($"{TopicPrefix}DomainEvent"), new TopicSubscription($"{TopicPrefix}ProductDomainEvent") }, "DomainEventSubscriber", Environment.MachineName, new[] { "DomainEventSubscriber" }); _domainEventProcessor.Start(); _eventSourcingEventProcessor = EventSourcingFactory.CreateEventSubscriber(new[] { new TopicSubscription($"{TopicPrefix}BankDomainEvent") }, "BankDomainEventSubscriber", Environment.MachineName, new[] {"BankDomainEventSubscriber"}); _eventSourcingEventProcessor.Start(); #endregion #region application event subscriber init _applicationEventProcessor = MessageQueueFactory.CreateEventSubscriber($"{TopicPrefix}AppEvent", "AppEventSubscriber", Environment.MachineName, new[] { "ApplicationEventSubscriber" }); _applicationEventProcessor.Start(); #endregion #region EventPublisher init _messagePublisher = MessageQueueFactory.GetMessagePublisher(); _messagePublisher.Start(); #endregion #region CommandBus init _commandBus = MessageQueueFactory.GetCommandBus(); _commandBus.Start(); #endregion } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Framework.Editor.Base; using Framework.Utils; using UnityEditor; using UnityEngine; using EditorGUI = UnityEditor.EditorGUI; namespace Framework.Editor { [CustomActionEditor(typeof(AnyEntry))] [CustomActionEditor(typeof(EventEntry))] public class ActionGraphEditorEntryBase : ActionGraphEditorNode, IReorderableNotify { private readonly PropertyPath ConditionPropertyPath; protected AnyEntry AsAny => ActionNode as AnyEntry; protected EventEntry AsEvent => ActionNode as EventEntry; public ActionGraphEditorEntryBase(ActionGraph graph, ActionGraphNodeBase node, ActionGraphPresenter presenter) : base(graph, node, presenter) { var builder = new PathBuilder<AnyEntry>(); ConditionPropertyPath = builder .ByListOf<AnyEntry.EntryInfo>(t => nameof(t.Entries)) .Path(); if (ActionNode) ActionNode.Notifiers.Add(this); } public override void OnDestroy() { base.OnDestroy(); if (ActionNode) ActionNode.Notifiers.Remove(this); } public override void RebuildConnections(Func<object, GraphNode> lookup) { Inputs.Clear(); switch (ActionNode) { case AnyEntry asAny: { foreach (var entry in asAny.Entries) { var slot = new Slot(this, SlotType.Output); if (entry.Child) connectedTo.Add(MakeConnection(slot, lookup.Invoke(entry.Child)?.GetDefaultInputSlot())); Outputs.Add(slot); } break; } case EventEntry asEvent: { var slot = new Slot(this, SlotType.Output); if (asEvent.Child) connectedTo.Add(MakeConnection(slot, lookup.Invoke(asEvent.Child)?.GetDefaultInputSlot())); Outputs.Add(slot); break; } } } protected override void OnConnectToChild(Connection eventSource) { var asAction = eventSource.Target.Owner as ActionGraphEditorNode; var asNode = asAction.ActionNode as ActionGraphNode; if (!asNode) return; switch (ActionNode) { case AnyEntry asAny: { var index = Outputs.IndexOf(eventSource.From); if (index >= 0) { var entry = asAny.Entries[index]; if (entry.Child) { RemoveConnection(connectedTo.FirstOrDefault(c => c.From.Equals(Outputs[index]))); } entry.Child = asNode; asAny.Entries[index] = entry; connectedTo.Add(eventSource); } break; } case EventEntry asEvent: { RemoveConnection(connectedTo.FirstOrDefault(c => c.From.Equals(Outputs[0]))); asEvent.Child = asNode; connectedTo.Add(eventSource); break; } } } protected override bool CanRename() { return ActionNode is EventEntry; } protected override void DrawContent() { drawRect.height = BASIC_HEIGHT; List<string> outNames = new List<string>(); switch (ActionNode) { case AnyEntry asAny: { foreach (var entry in asAny.Entries) { outNames.Add(entry.Name); } break; } case EventEntry asEvent: { outNames.Add("out"); break; } } drawRect.y += 1; Rect oldRect = drawRect; drawRect.width -= 10; foreach (var outName in outNames) { GUI.Label(drawRect, outName, SpaceEditorStyles.AlignedRigthWhiteBoldText); drawRect.y += OUTPUT_HEIGHT; } Size = new Vector2(Size.x, Mathf.Max(BASIC_HEIGHT * 2, BASIC_HEIGHT + drawRect.y - oldRect.y)); } public void OnReordered(PropertyPath path, int oldIndex, int newIndex) { if (!AsAny || !ConditionPropertyPath.Equals(path)) return; var oldInput = AsAny.Entries[oldIndex]; AsAny.Entries.RemoveAt(oldIndex); AsAny.Entries.Insert(newIndex, oldInput); var oldSocket = Outputs[oldIndex]; Outputs.RemoveAt(oldIndex); Outputs.Insert(newIndex, oldSocket); Editor.WantsRepaint = true; } public void OnAdded(PropertyPath path) { if (!AsAny || !ConditionPropertyPath.Equals(path)) return; // All fresh entries shall be clear! if (AsAny.Entries.Any()) { var last = AsAny.Entries.Last(); last.Name = "out"; last.Child = null; last.Conditions.Clear(); AsAny.Entries[AsAny.Entries.Count - 1] = last; } Outputs.Add(new Slot(this, SlotType.Output)); Editor.WantsRepaint = true; } public void OnRemoved(PropertyPath path, int index) { if (!AsAny || !ConditionPropertyPath.Equals(path)) return; RemoveAllConnectionFrom(Outputs[index]); Outputs.RemoveAt(index); Editor.WantsRepaint = true; } public bool IsFromPath(PropertyPath path) { return ConditionPropertyPath.Equals(path); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Xml; using System.Xml.XPath; using System.Xml.Schema; using System.Diagnostics; using System.Collections; using System.ComponentModel; namespace System.Xml.Xsl.Runtime { /// <summary> /// Set iterators (Union, Intersection, Difference) that use containment to control two nested iterators return /// one of the following values from MoveNext(). /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public enum SetIteratorResult { NoMoreNodes, // Iteration is complete; there are no more nodes InitRightIterator, // Initialize right nested iterator NeedLeftNode, // The next node needs to be fetched from the left nested iterator NeedRightNode, // The next node needs to be fetched from the right nested iterator HaveCurrentNode, // This iterator's Current property is set to the next node in the iteration }; /// <summary> /// This iterator manages two sets of nodes that are already in document order with no duplicates. /// Using a merge sort, this operator returns the union of these sets in document order with no duplicates. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public struct UnionIterator { private XmlQueryRuntime _runtime; private XPathNavigator _navCurr, _navOther; private IteratorState _state; private enum IteratorState { InitLeft = 0, NeedLeft, NeedRight, LeftIsCurrent, RightIsCurrent, }; /// <summary> /// Create SetIterator. /// </summary> public void Create(XmlQueryRuntime runtime) { _runtime = runtime; _state = IteratorState.InitLeft; } /// <summary> /// Position this iterator to the next node in the union. /// </summary> public SetIteratorResult MoveNext(XPathNavigator nestedNavigator) { switch (_state) { case IteratorState.InitLeft: // Fetched node from left iterator, now get initial node from right iterator _navOther = nestedNavigator; _state = IteratorState.NeedRight; return SetIteratorResult.InitRightIterator; case IteratorState.NeedLeft: _navCurr = nestedNavigator; _state = IteratorState.LeftIsCurrent; break; case IteratorState.NeedRight: _navCurr = nestedNavigator; _state = IteratorState.RightIsCurrent; break; case IteratorState.LeftIsCurrent: // Just returned left node as current, so get new left _state = IteratorState.NeedLeft; return SetIteratorResult.NeedLeftNode; case IteratorState.RightIsCurrent: // Just returned right node as current, so get new right _state = IteratorState.NeedRight; return SetIteratorResult.NeedRightNode; } // Merge left and right nodes if (_navCurr == null) { // If both navCurr and navOther are null, then iteration is complete if (_navOther == null) return SetIteratorResult.NoMoreNodes; Swap(); } else if (_navOther != null) { int order = _runtime.ComparePosition(_navOther, _navCurr); // If navCurr is positioned to same node as navOther, if (order == 0) { // Skip navCurr, since it is a duplicate if (_state == IteratorState.LeftIsCurrent) { _state = IteratorState.NeedLeft; return SetIteratorResult.NeedLeftNode; } _state = IteratorState.NeedRight; return SetIteratorResult.NeedRightNode; } // If navOther is before navCurr in document order, then swap navCurr with navOther if (order < 0) Swap(); } // Return navCurr return SetIteratorResult.HaveCurrentNode; } /// <summary> /// Return the current result navigator. This is only defined after MoveNext() has returned -1. /// </summary> public XPathNavigator Current { get { return _navCurr; } } /// <summary> /// Swap navCurr with navOther and invert state to reflect the change. /// </summary> private void Swap() { XPathNavigator navTemp = _navCurr; _navCurr = _navOther; _navOther = navTemp; if (_state == IteratorState.LeftIsCurrent) _state = IteratorState.RightIsCurrent; else _state = IteratorState.LeftIsCurrent; } } /// <summary> /// This iterator manages two sets of nodes that are already in document order with no duplicates. /// This iterator returns the intersection of these sets in document order with no duplicates. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public struct IntersectIterator { private XmlQueryRuntime _runtime; private XPathNavigator _navLeft, _navRight; private IteratorState _state; private enum IteratorState { InitLeft = 0, NeedLeft, NeedRight, NeedLeftAndRight, HaveCurrent, }; /// <summary> /// Create IntersectIterator. /// </summary> public void Create(XmlQueryRuntime runtime) { _runtime = runtime; _state = IteratorState.InitLeft; } /// <summary> /// Position this iterator to the next node in the union. /// </summary> public SetIteratorResult MoveNext(XPathNavigator nestedNavigator) { int order; switch (_state) { case IteratorState.InitLeft: // Fetched node from left iterator, now get initial node from right iterator _navLeft = nestedNavigator; _state = IteratorState.NeedRight; return SetIteratorResult.InitRightIterator; case IteratorState.NeedLeft: _navLeft = nestedNavigator; break; case IteratorState.NeedRight: _navRight = nestedNavigator; break; case IteratorState.NeedLeftAndRight: // After fetching left node, still need right node _navLeft = nestedNavigator; _state = IteratorState.NeedRight; return SetIteratorResult.NeedRightNode; case IteratorState.HaveCurrent: // Just returned left node as current, so fetch new left and right nodes Debug.Assert(nestedNavigator == null, "null is passed to MoveNext after IteratorState.HaveCurrent has been returned."); _state = IteratorState.NeedLeftAndRight; return SetIteratorResult.NeedLeftNode; } if (_navLeft == null || _navRight == null) { // No more nodes from either left or right iterator (or both), so iteration is complete return SetIteratorResult.NoMoreNodes; } // Intersect left and right sets order = _runtime.ComparePosition(_navLeft, _navRight); if (order < 0) { // If navLeft is positioned to a node that is before navRight, skip left node _state = IteratorState.NeedLeft; return SetIteratorResult.NeedLeftNode; } else if (order > 0) { // If navLeft is positioned to a node that is after navRight, so skip right node _state = IteratorState.NeedRight; return SetIteratorResult.NeedRightNode; } // Otherwise, navLeft is positioned to the same node as navRight, so found one item in the intersection _state = IteratorState.HaveCurrent; return SetIteratorResult.HaveCurrentNode; } /// <summary> /// Return the current result navigator. This is only defined after MoveNext() has returned -1. /// </summary> public XPathNavigator Current { get { return _navLeft; } } } /// <summary> /// This iterator manages two sets of nodes that are already in document order with no duplicates. /// This iterator returns the difference of these sets (Left - Right) in document order with no duplicates. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public struct DifferenceIterator { private XmlQueryRuntime _runtime; private XPathNavigator _navLeft, _navRight; private IteratorState _state; private enum IteratorState { InitLeft = 0, NeedLeft, NeedRight, NeedLeftAndRight, HaveCurrent, }; /// <summary> /// Create DifferenceIterator. /// </summary> public void Create(XmlQueryRuntime runtime) { _runtime = runtime; _state = IteratorState.InitLeft; } /// <summary> /// Position this iterator to the next node in the union. /// </summary> public SetIteratorResult MoveNext(XPathNavigator nestedNavigator) { switch (_state) { case IteratorState.InitLeft: // Fetched node from left iterator, now get initial node from right iterator _navLeft = nestedNavigator; _state = IteratorState.NeedRight; return SetIteratorResult.InitRightIterator; case IteratorState.NeedLeft: _navLeft = nestedNavigator; break; case IteratorState.NeedRight: _navRight = nestedNavigator; break; case IteratorState.NeedLeftAndRight: // After fetching left node, still need right node _navLeft = nestedNavigator; _state = IteratorState.NeedRight; return SetIteratorResult.NeedRightNode; case IteratorState.HaveCurrent: // Just returned left node as current, so fetch new left node Debug.Assert(nestedNavigator == null, "null is passed to MoveNext after IteratorState.HaveCurrent has been returned."); _state = IteratorState.NeedLeft; return SetIteratorResult.NeedLeftNode; } if (_navLeft == null) { // If navLeft is null, then difference operation is complete return SetIteratorResult.NoMoreNodes; } else if (_navRight != null) { int order = _runtime.ComparePosition(_navLeft, _navRight); // If navLeft is positioned to same node as navRight, if (order == 0) { // Skip navLeft and navRight _state = IteratorState.NeedLeftAndRight; return SetIteratorResult.NeedLeftNode; } // If navLeft is after navRight in document order, then skip navRight if (order > 0) { _state = IteratorState.NeedRight; return SetIteratorResult.NeedRightNode; } } // Return navLeft _state = IteratorState.HaveCurrent; return SetIteratorResult.HaveCurrentNode; } /// <summary> /// Return the current result navigator. This is only defined after MoveNext() has returned -1. /// </summary> public XPathNavigator Current { get { return _navLeft; } } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; // ERROR: Not supported in C#: OptionDeclaration namespace _4PosBackOffice.NET { internal partial class frmStockGroupListNotes : System.Windows.Forms.Form { string gFilter; ADODB.Recordset gRS; string gFilterSQL; int gID; short gSection; bool gAll; string grpDelete; private void loadLanguage() { modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1219; //Select a Stock Group|Checked if (modRecordSet.rsLang.RecordCount){this.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;this.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1080; //Search|Checked if (modRecordSet.rsLang.RecordCount){lbl.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;lbl.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1065; //New|Checked if (modRecordSet.rsLang.RecordCount){cmdNew.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdNew.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004; //Exit|Checked if (modRecordSet.rsLang.RecordCount){cmdExit.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdExit.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'"; //UPGRADE_ISSUE: Form property frmStockGroupListNotes.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' if (modRecordSet.rsHelp.RecordCount) this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value; } public int getItem() { cmdNew.Text = "&All"; cmdNew.Visible = false; doSearch(); loadLanguage(); this.ShowDialog(); return gID; } private void getNamespace() { } private void cmdExit_Click(System.Object eventSender, System.EventArgs eventArgs) { this.Close(); } private void cmdNamespace_Click() { My.MyProject.Forms.frmFilter.loadFilter(ref gFilter); getNamespace(); } private void cmdNew_Click(System.Object eventSender, System.EventArgs eventArgs) { if (gSection) { //Exit form and set indicator to suggest all gID = -1; } else { My.MyProject.Forms.frmStockGroup.loadItem(ref 0); } doSearch(); } private void DataList1_DblClick(System.Object eventSender, System.EventArgs eventArgs) { object rs = null; if (cmdNew.Visible) { if (!string.IsNullOrEmpty(DataList1.BoundText)) { My.MyProject.Forms.frmStockGroup.loadItem(ref Convert.ToInt32(DataList1.BoundText)); } doSearch(); } else { if (string.IsNullOrEmpty(DataList1.BoundText)) { gID = 0; } else { gID = Convert.ToInt32(DataList1.BoundText); } switch (gSection) { case 0: this.Close(); break; case 1: modApplication.report_StockTake(gID); break; case 2: My.MyProject.Forms.frmStockTake.loadItem(ref gID); if (!string.IsNullOrEmpty(DataList1.BoundText)) { rs = modRecordSet.getRS(ref "SELECT StockGroup_Name FROM StockGroup WHERE StockGroupID =" + Conversion.Val(DataList1.BoundText)); //UPGRADE_WARNING: Couldn't resolve default property of object rs(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' if (Strings.UCase(Strings.Mid(rs("StockGroup_Name"), 1, 8)) == "HANDHELD") { //UPGRADE_WARNING: Couldn't resolve default property of object rs(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' grpDelete = Strings.Trim(rs("StockGroup_Name")); modRecordSet.cnnDB.Execute("DROP TABLE " + grpDelete); modRecordSet.cnnDB.Execute("DELETE * FROM StockGroup WHERE StockGroup_Name ='" + grpDelete + "'"); loadItem1(ref 2); } } break; case 3: modApplication.report_StockQuantityData(ref gID); break; case 4: //New to do StockItem by group modApplication.report_StockValueByDept(ref gID); break; case 5: //New to do the Addition of the StockTake My.MyProject.Forms.frmStockTakeAdd.loadItem(ref gID); break; //delete group and table //cnnDB.Execute "DROP TABLE " & DataList1.BoundText //cnnDB.Execute "DELETE from StockGroup WHERE StockGroup_Name = '" & DataList1.BoundText & "'" //On Error Resume Next //If DataList1.BoundText <> "" Then // Set rs = getRS("SELECT StockGroup_Name FROM StockGroup WHERE StockGroupID =" & Val(DataList1.BoundText)) // If UCase(Mid$(rs("StockGroup_Name"), 1, 8)) = "HANDHELD" Then // grpDelete = Trim(rs("StockGroup_Name")) // // cnnDB.Execute "DROP TABLE " & grpDelete // cnnDB.Execute "DELETE * FROM StockGroup WHERE StockGroup_Name ='" & grpDelete & "'" // loadItem1 2 // End If //End If } } } private void DataList1_KeyPress(System.Object eventSender, KeyPressEventArgs eventArgs) { switch (eventArgs.KeyChar) { case Strings.ChrW(13): DataList1_DblClick(DataList1, new System.EventArgs()); eventArgs.KeyChar = Strings.ChrW(0); break; case Strings.ChrW(27): this.Close(); eventArgs.KeyChar = Strings.ChrW(0); break; } } private void DataList1_MouseDown(System.Object eventSender, MouseEventArgs eventArgs) { ADODB.Recordset rs = default(ADODB.Recordset); // ERROR: Not supported in C#: OnErrorStatement if (!string.IsNullOrEmpty(DataList1.BoundText)) { rs = modRecordSet.getRS(ref "SELECT StockGroup_Name FROM StockGroup WHERE StockGroupID =" + Conversion.Val(DataList1.BoundText)); if (Strings.UCase(Strings.Mid(rs.Fields("StockGroup_Name").Value, 1, 8)) == "HANDHELD") { grpDelete = Strings.Trim(rs.Fields("StockGroup_Name").Value); if (eventArgs.Button == 2) { //UPGRADE_ISSUE: Form method frmStockGroupListNotes.PopupMenu was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' //Call PopupMenu(mnuHand) return; } } } } private void frmStockGroupListNotes_KeyDown(System.Object eventSender, System.Windows.Forms.KeyEventArgs eventArgs) { short KeyCode = eventArgs.KeyCode; short Shift = eventArgs.KeyData / 0x10000; if (KeyCode == 36) { gAll = !gAll; doSearch(); KeyCode = false; } } private void frmStockGroupListNotes_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); switch (KeyAscii) { case System.Windows.Forms.Keys.Escape: KeyAscii = 0; cmdExit_Click(cmdExit, new System.EventArgs()); break; } eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } public void loadItem(ref short section) { gSection = section; if (gSection) { cmdNew.Text = "&All"; cmdNew.Visible = false; } doSearch(); loadLanguage(); this.ShowDialog(); } public void loadItem1(ref short section) { gSection = section; if (gSection) { cmdNew.Text = "&All"; cmdNew.Visible = false; } doSearch(); } private void frmStockGroupListNotes_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs) { gRS.Close(); } public void mnuDel_Click(System.Object eventSender, System.EventArgs eventArgs) { short intres = 0; intres = Interaction.MsgBox("Do you want to delete this 'HANDHELD SCANNER' group", MsgBoxStyle.ApplicationModal + MsgBoxStyle.Question + MsgBoxStyle.YesNo, _4PosBackOffice.NET.My.MyProject.Application.Info.Title); if (intres == MsgBoxResult.Yes) { modRecordSet.cnnDB.Execute("DROP TABLE " + grpDelete); modRecordSet.cnnDB.Execute("DELETE * FROM StockGroup WHERE StockGroup_Name ='" + grpDelete + "'"); loadItem1(ref 2); } } private void txtSearch_Enter(System.Object eventSender, System.EventArgs eventArgs) { txtSearch.SelectionStart = 0; txtSearch.SelectionLength = 999; } private void txtSearch_KeyDown(System.Object eventSender, System.Windows.Forms.KeyEventArgs eventArgs) { short KeyCode = eventArgs.KeyCode; short Shift = eventArgs.KeyData / 0x10000; switch (KeyCode) { case 40: this.DataList1.Focus(); break; } } private void txtSearch_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); switch (KeyAscii) { case 13: doSearch(); KeyAscii = 0; break; } eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } private void doSearch() { string sql = null; string lString = null; lString = Strings.Trim(txtSearch.Text); lString = Strings.Replace(lString, " ", " "); lString = Strings.Replace(lString, " ", " "); lString = Strings.Replace(lString, " ", " "); lString = Strings.Replace(lString, " ", " "); lString = Strings.Replace(lString, " ", " "); lString = Strings.Replace(lString, " ", " "); if (string.IsNullOrEmpty(lString)) { } else { lString = "WHERE (StockGRoup_Name LIKE '%" + Strings.Replace(lString, " ", "%' AND StockGRoup_Name LIKE '%") + "%')"; } if (gAll) { } else { if (string.IsNullOrEmpty(lString)) { lString = " WHERE StockGroup_Disabled = 0 "; } else { lString = lString + " AND StockGroup_Disabled = 0 "; } } gRS = modRecordSet.getRS(ref "SELECT DISTINCT StockGRoupID, StockGRoup_Name FROM StockGRoup " + lString + " ORDER BY StockGRoup_Name"); //Display the list of Titles in the DataCombo DataList1.DataSource = gRS; DataList1.listField = "StockGRoup_Name"; //Bind the DataCombo to the ADO Recordset //UPGRADE_ISSUE: VBControlExtender property DataList1.DataSource is not supported at runtime. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="74E732F3-CAD8-417B-8BC9-C205714BB4A7"' DataList1.DataSource = gRS; DataList1.boundColumn = "StockGRoupID"; } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Signum.Engine.Maps; using Signum.Entities; using Signum.Utilities; using Signum.Utilities.ExpressionTrees; using Signum.Utilities.Reflection; namespace Signum.Engine.Linq { internal class ChildProjectionFlattener : DbExpressionVisitor { SelectExpression? currentSource; readonly AliasGenerator aliasGenerator; private ChildProjectionFlattener(AliasGenerator aliasGenerator) { this.aliasGenerator = aliasGenerator; } static internal ProjectionExpression Flatten(ProjectionExpression proj, AliasGenerator aliasGenerator) { var result = (ProjectionExpression)new ChildProjectionFlattener(aliasGenerator).Visit(proj); if (result == proj) return result; Expression columnCleaned = UnusedColumnRemover.Remove(result); Expression subqueryCleaned = RedundantSubqueryRemover.Remove(columnCleaned); return (ProjectionExpression)subqueryCleaned; } public Type? inMList = null; protected internal override Expression VisitMListProjection(MListProjectionExpression mlp) { var oldInEntity = inMList; inMList = mlp.Type; var result = VisitProjection(mlp.Projection); inMList = oldInEntity; return result; } protected internal override Expression VisitProjection(ProjectionExpression proj) { if (currentSource == null) { currentSource = WithoutOrder(proj.Select); Expression projector = this.Visit(proj.Projector); if (projector != proj.Projector) proj = new ProjectionExpression(proj.Select, projector, proj.UniqueFunction, proj.Type); currentSource = null; return proj; } else { HashSet<ColumnExpression> columns = ExternalColumnGatherer.Gatherer(proj, currentSource.Alias); if (columns.Count == 0) { Expression projector = Visit(proj.Projector); ConstantExpression key = Expression.Constant(0); Type kvpType = typeof(KeyValuePair<,>).MakeGenericType(key.Type, projector.Type); ConstructorInfo ciKVP = kvpType.GetConstructor(new[] { key.Type, projector.Type })!; Type projType = proj.UniqueFunction == null ? typeof(IEnumerable<>).MakeGenericType(kvpType) : kvpType; var childProj = new ProjectionExpression(proj.Select, Expression.New(ciKVP, key, projector), proj.UniqueFunction, projType); return new ChildProjectionExpression(childProj, Expression.Constant(0), inMList != null, inMList ?? proj.Type, new LookupToken()); } else { SelectExpression external; IEnumerable<ColumnExpression> externalColumns; if (!IsKey(currentSource, columns)) { Alias aliasDistinct = aliasGenerator.GetUniqueAlias(currentSource.Alias.Name + "D"); ColumnGenerator generatorDistinct = new ColumnGenerator(); List<ColumnDeclaration> columnDistinct = columns.Select(ce => generatorDistinct.MapColumn(ce)).ToList(); external = new SelectExpression(aliasDistinct, true, null, columnDistinct, currentSource, null, null, null, 0); Dictionary<ColumnExpression, ColumnExpression> distinctReplacements = columnDistinct.ToDictionary( cd => (ColumnExpression)cd.Expression, cd => cd.GetReference(aliasDistinct)); proj = (ProjectionExpression)ColumnReplacer.Replace(proj, distinctReplacements); externalColumns = distinctReplacements.Values.ToHashSet(); } else { external = currentSource; externalColumns = columns; } ColumnGenerator generatorSM = new ColumnGenerator(); List<ColumnDeclaration> columnsSMExternal = externalColumns.Select(ce => generatorSM.MapColumn(ce)).ToList(); List<ColumnDeclaration> columnsSMInternal = proj.Select.Columns.Select(cd => generatorSM.MapColumn(cd.GetReference(proj.Select.Alias))).ToList(); SelectExpression @internal = ExtractOrders(proj.Select, out List<OrderExpression>? innerOrders); Alias aliasSM = aliasGenerator.GetUniqueAlias(@internal.Alias.Name + "SM"); SelectExpression selectMany = new SelectExpression(aliasSM, false, null, columnsSMExternal.Concat(columnsSMInternal), new JoinExpression(JoinType.CrossApply, external, @internal, null), null, innerOrders, null, 0); SelectExpression old = currentSource; currentSource = WithoutOrder(selectMany); var selectManyReplacements = selectMany.Columns.ToDictionary( cd => (ColumnExpression)cd.Expression, cd => cd.GetReference(aliasSM)); Expression projector = ColumnReplacer.Replace(proj.Projector, selectManyReplacements); projector = Visit(projector); currentSource = old; Expression key = TupleReflection.TupleChainConstructor(columnsSMExternal.Select(cd => MakeEquatable(cd.GetReference(aliasSM)))); Type kvpType = typeof(KeyValuePair<,>).MakeGenericType(key.Type, projector.Type); ConstructorInfo ciKVP = kvpType.GetConstructor(new[] { key.Type, projector.Type })!; Type projType = proj.UniqueFunction == null ? typeof(IEnumerable<>).MakeGenericType(kvpType) : kvpType; var childProj = new ProjectionExpression(selectMany, Expression.New(ciKVP, key, projector), proj.UniqueFunction, projType); return new ChildProjectionExpression(childProj, TupleReflection.TupleChainConstructor(columns.Select(a => MakeEquatable(a))), inMList != null, inMList ?? proj.Type, new LookupToken()); } } } public Expression MakeEquatable(Expression expression) { if (expression.Type.IsArray) return Expression.New(typeof(ArrayBox<>).MakeGenericType(expression.Type.ElementType()!).GetConstructors().SingleEx(), expression); return expression.Nullify(); } private SelectExpression WithoutOrder(SelectExpression sel) { if (sel.Top != null || (sel.OrderBy.Count == 0)) return sel; return new SelectExpression(sel.Alias, sel.IsDistinct, sel.Top, sel.Columns, sel.From, sel.Where, null, sel.GroupBy, sel.SelectOptions); } private SelectExpression ExtractOrders(SelectExpression sel, out List<OrderExpression>? innerOrders) { if (sel.Top != null || (sel.OrderBy.Count == 0)) { innerOrders = null; return sel; } else { ColumnGenerator cg = new ColumnGenerator(sel.Columns); Dictionary<OrderExpression, ColumnDeclaration> newColumns = sel.OrderBy.ToDictionary(o => o, o => cg.NewColumn(o.Expression)); innerOrders = newColumns.Select(kvp => new OrderExpression(kvp.Key.OrderType, kvp.Value.GetReference(sel.Alias))).ToList(); return new SelectExpression(sel.Alias, sel.IsDistinct, sel.Top, sel.Columns.Concat(newColumns.Values), sel.From, sel.Where, null, sel.GroupBy, sel.SelectOptions); } } private bool IsKey(SelectExpression source, HashSet<ColumnExpression> columns) { var keys = KeyFinder.Keys(source); return keys.All(k => k != null && columns.Contains(k)); } internal static class KeyFinder { public static IEnumerable<ColumnExpression?> Keys(SourceExpression source) { if (source is SelectExpression) return KeysSelect((SelectExpression)source); if (source is TableExpression) return KeysTable((TableExpression)source); if(source is JoinExpression) return KeysJoin((JoinExpression)source); if (source is SetOperatorExpression) return KeysSet((SetOperatorExpression)source); throw new InvalidOperationException("Unexpected source"); } private static IEnumerable<ColumnExpression?> KeysSet(SetOperatorExpression set) { return Keys(set.Left).Concat(Keys(set.Right)); } private static IEnumerable<ColumnExpression?> KeysJoin(JoinExpression join) { switch (join.JoinType) { case JoinType.SingleRowLeftOuterJoin: return Keys(join.Left); case JoinType.CrossApply: { var leftKeys = Keys(join.Left); var rightKeys = Keys(join.Right); var onlyLeftKey = leftKeys.Only(); if(onlyLeftKey != null && join.Right is SelectExpression r && r.Where is BinaryExpression b && b.NodeType == ExpressionType.Equal && b.Left is ColumnExpression cLeft && b.Right is ColumnExpression cRight) { if(cLeft.Equals(onlyLeftKey) ^ cRight.Equals(onlyLeftKey)) { var other = b.Left == onlyLeftKey ? b.Right : b.Left; if (other is ColumnExpression c && join.Right.KnownAliases.Contains(c.Alias)) return rightKeys; } } return leftKeys.Concat(rightKeys); } case JoinType.CrossJoin: case JoinType.InnerJoin: case JoinType.OuterApply: case JoinType.LeftOuterJoin: case JoinType.RightOuterJoin: case JoinType.FullOuterJoin: return Keys(join.Left).Concat(Keys(join.Right)); default: break; } throw new InvalidOperationException("Unexpected Join Type"); } private static IEnumerable<ColumnExpression> KeysTable(TableExpression table) { if (table.Table is Table t && t.IsView) return t.Columns.Values.Where(c => c.PrimaryKey).Select(c => new ColumnExpression(c.Type, table.Alias, c.Name)); else return new[] { new ColumnExpression(typeof(int), table.Alias, table.Table.PrimaryKey.Name) }; } private static IEnumerable<ColumnExpression?> KeysSelect(SelectExpression select) { if (select.GroupBy.Any()) return select.GroupBy.Select(ce => select.Columns.FirstOrDefault(cd => cd.Expression.Equals(ce) /*could be improved*/)?.Let(cd => cd.GetReference(select.Alias))).ToList(); IEnumerable<ColumnExpression?> inner = Keys(select.From!); var result = inner.Select(ce => select.Columns.FirstOrDefault(cd => cd.Expression.Equals(ce))?.Let(cd => cd.GetReference(select.Alias))).ToList(); if (!select.IsDistinct) return result; var result2 = select.Columns.Select(cd => (ColumnExpression?)cd.GetReference(select.Alias)).ToList(); if (result.Any(c => c == null)) return result2; if (result2.Any(c => c == null)) return result; return result.Count > result2.Count ? result2 : result; } } internal class ColumnReplacer : DbExpressionVisitor { readonly Dictionary<ColumnExpression, ColumnExpression> Replacements; public ColumnReplacer(Dictionary<ColumnExpression, ColumnExpression> replacements) { Replacements = replacements; } public static Expression Replace(Expression expression, Dictionary<ColumnExpression, ColumnExpression> replacements) { return new ColumnReplacer(replacements).Visit(expression); } protected internal override Expression VisitColumn(ColumnExpression column) { return Replacements.TryGetC(column) ?? base.VisitColumn(column); } protected internal override Expression VisitChildProjection(ChildProjectionExpression child) { return child; } } internal class ExternalColumnGatherer : DbExpressionVisitor { readonly Alias externalAlias; readonly HashSet<ColumnExpression> columns = new HashSet<ColumnExpression>(); public ExternalColumnGatherer(Alias externalAlias) { this.externalAlias = externalAlias; } public static HashSet<ColumnExpression> Gatherer(Expression source, Alias externalAlias) { ExternalColumnGatherer ap = new ExternalColumnGatherer(externalAlias); ap.Visit(source); return ap.columns; } protected internal override Expression VisitColumn(ColumnExpression column) { if (externalAlias == column.Alias) columns.Add(column); return base.VisitColumn(column); } } } class ArrayBox<T> : IEquatable<ArrayBox<T>> { readonly int hashCode; public readonly T[]? Array; public ArrayBox(T[]? array) { this.Array = array; this.hashCode = 0; if(array != null) { foreach (var item in array) { this.hashCode = (this.hashCode << 1) ^ (item == null ? 0 : item.GetHashCode()); } } } public override int GetHashCode() => hashCode; public override bool Equals(object? obj) => obj is ArrayBox<T> a && Equals(a); public bool Equals([AllowNull]ArrayBox<T> other) => other != null && Enumerable.SequenceEqual(Array, other.Array); } }
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 CCN.WebAPI.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using System.Security.Principal; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.IO.Pipes.Tests { /// <summary> /// The Specific NamedPipe tests cover edge cases or otherwise narrow cases that /// show up within particular server/client directional combinations. /// </summary> public class NamedPipeTest_Specific : NamedPipeTestBase { [Fact] public void InvalidConnectTimeout_Throws_ArgumentOutOfRangeException() { using (NamedPipeClientStream client = new NamedPipeClientStream("client1")) { AssertExtensions.Throws<ArgumentOutOfRangeException>("timeout", () => client.Connect(-111)); AssertExtensions.Throws<ArgumentOutOfRangeException>("timeout", () => { client.ConnectAsync(-111); }); } } [Fact] public async Task ConnectToNonExistentServer_Throws_TimeoutException() { using (NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere")) { var ctx = new CancellationTokenSource(); Assert.Throws<TimeoutException>(() => client.Connect(60)); // 60 to be over internal 50 interval await Assert.ThrowsAsync<TimeoutException>(() => client.ConnectAsync(50)); await Assert.ThrowsAsync<TimeoutException>(() => client.ConnectAsync(60, ctx.Token)); // testing Token overload; ctx is not canceled in this test } } [Fact] public async Task CancelConnectToNonExistentServer_Throws_OperationCanceledException() { using (NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere")) { var ctx = new CancellationTokenSource(); Task clientConnectToken = client.ConnectAsync(ctx.Token); ctx.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => clientConnectToken); ctx.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => client.ConnectAsync(ctx.Token)); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Unix implementation uses bidirectional sockets public void ConnectWithConflictingDirections_Throws_UnauthorizedAccessException() { string serverName1 = GetUniquePipeName(); using (NamedPipeServerStream server = new NamedPipeServerStream(serverName1, PipeDirection.Out)) using (NamedPipeClientStream client = new NamedPipeClientStream(".", serverName1, PipeDirection.Out)) { Assert.Throws<UnauthorizedAccessException>(() => client.Connect()); Assert.False(client.IsConnected); } string serverName2 = GetUniquePipeName(); using (NamedPipeServerStream server = new NamedPipeServerStream(serverName2, PipeDirection.In)) using (NamedPipeClientStream client = new NamedPipeClientStream(".", serverName2, PipeDirection.In)) { Assert.Throws<UnauthorizedAccessException>(() => client.Connect()); Assert.False(client.IsConnected); } } [Theory] [InlineData(PipeOptions.None)] [InlineData(PipeOptions.Asynchronous)] [PlatformSpecific(TestPlatforms.Windows)] // Unix currently doesn't support message mode public async Task Windows_MessagePipeTransissionMode(PipeOptions serverOptions) { byte[] msg1 = new byte[] { 5, 7, 9, 10 }; byte[] msg2 = new byte[] { 2, 4 }; byte[] received1 = new byte[] { 0, 0, 0, 0 }; byte[] received2 = new byte[] { 0, 0 }; byte[] received3 = new byte[] { 0, 0, 0, 0 }; byte[] received4 = new byte[] { 0, 0, 0, 0 }; byte[] received5 = new byte[] { 0, 0 }; byte[] received6 = new byte[] { 0, 0, 0, 0 }; string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, serverOptions)) { using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation)) { server.ReadMode = PipeTransmissionMode.Message; Assert.Equal(PipeTransmissionMode.Message, server.ReadMode); Task clientTask = Task.Run(() => { client.Connect(); client.Write(msg1, 0, msg1.Length); client.Write(msg2, 0, msg2.Length); client.Write(msg1, 0, msg1.Length); client.Write(msg1, 0, msg1.Length); client.Write(msg2, 0, msg2.Length); client.Write(msg1, 0, msg1.Length); int serverCount = client.NumberOfServerInstances; Assert.Equal(1, serverCount); }); server.WaitForConnection(); int len1 = server.Read(received1, 0, msg1.Length); Assert.True(server.IsMessageComplete); Assert.Equal(msg1.Length, len1); Assert.Equal(msg1, received1); int len2 = server.Read(received2, 0, msg2.Length); Assert.True(server.IsMessageComplete); Assert.Equal(msg2.Length, len2); Assert.Equal(msg2, received2); int expectedRead = msg1.Length - 1; int len3 = server.Read(received3, 0, expectedRead); // read one less than message Assert.False(server.IsMessageComplete); Assert.Equal(expectedRead, len3); for (int i = 0; i < expectedRead; ++i) { Assert.Equal(msg1[i], received3[i]); } expectedRead = msg1.Length - expectedRead; Assert.Equal(expectedRead, server.Read(received3, len3, expectedRead)); Assert.True(server.IsMessageComplete); Assert.Equal(msg1, received3); Assert.Equal(msg1.Length, await server.ReadAsync(received4, 0, msg1.Length)); Assert.True(server.IsMessageComplete); Assert.Equal(msg1, received4); Assert.Equal(msg2.Length, await server.ReadAsync(received5, 0, msg2.Length)); Assert.True(server.IsMessageComplete); Assert.Equal(msg2, received5); expectedRead = msg1.Length - 1; Assert.Equal(expectedRead, await server.ReadAsync(received6, 0, expectedRead)); // read one less than message Assert.False(server.IsMessageComplete); for (int i = 0; i < expectedRead; ++i) { Assert.Equal(msg1[i], received6[i]); } expectedRead = msg1.Length - expectedRead; Assert.Equal(expectedRead, await server.ReadAsync(received6, msg1.Length - expectedRead, expectedRead)); Assert.True(server.IsMessageComplete); Assert.Equal(msg1, received6); await clientTask; } } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Unix doesn't support MaxNumberOfServerInstances public async Task Windows_Get_NumberOfServerInstances_Succeed() { string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 3)) { using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation)) { int expectedNumberOfServerInstances; Task serverTask = server.WaitForConnectionAsync(); client.Connect(); await serverTask; Assert.True(Interop.TryGetNumberOfServerInstances(client.SafePipeHandle, out expectedNumberOfServerInstances), "GetNamedPipeHandleState failed"); Assert.Equal(expectedNumberOfServerInstances, client.NumberOfServerInstances); } } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Win32 P/Invokes to verify the user name public async Task Windows_GetImpersonationUserName_Succeed() { string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName)) { using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation)) { string expectedUserName; Task serverTask = server.WaitForConnectionAsync(); client.Connect(); await serverTask; Assert.True(Interop.TryGetImpersonationUserName(server.SafePipeHandle, out expectedUserName), "GetNamedPipeHandleState failed"); Assert.Equal(expectedUserName, server.GetImpersonationUserName()); } } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/1011 [PlatformSpecific(TestPlatforms.AnyUnix)] // Uses P/Invoke to verify the user name public async Task Unix_GetImpersonationUserName_Succeed() { string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation)) { Task serverTask = server.WaitForConnectionAsync(); client.Connect(); await serverTask; string name = server.GetImpersonationUserName(); Assert.NotNull(name); Assert.False(string.IsNullOrWhiteSpace(name)); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Unix currently doesn't support message mode public void Unix_MessagePipeTransissionMode() { Assert.Throws<PlatformNotSupportedException>(() => new NamedPipeServerStream(GetUniquePipeName(), PipeDirection.InOut, 1, PipeTransmissionMode.Message)); } [Theory] [InlineData(PipeDirection.In)] [InlineData(PipeDirection.Out)] [InlineData(PipeDirection.InOut)] [PlatformSpecific(TestPlatforms.AnyUnix)] // Unix implementation uses bidirectional sockets public static void Unix_BufferSizeRoundtripping(PipeDirection direction) { int desiredBufferSize = 0; string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); desiredBufferSize = server.OutBufferSize * 2; } using (var server = new NamedPipeServerStream(pipeName, direction, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize)) using (var client = new NamedPipeClientStream(".", pipeName, direction == PipeDirection.In ? PipeDirection.Out : PipeDirection.In)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); if ((direction & PipeDirection.Out) != 0) { Assert.InRange(server.OutBufferSize, desiredBufferSize, int.MaxValue); } if ((direction & PipeDirection.In) != 0) { Assert.InRange(server.InBufferSize, desiredBufferSize, int.MaxValue); } } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Unix implementation uses bidirectional sockets public static void Windows_BufferSizeRoundtripping() { int desiredBufferSize = 10; string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); Assert.Equal(desiredBufferSize, server.OutBufferSize); Assert.Equal(desiredBufferSize, client.InBufferSize); } using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); Assert.Equal(desiredBufferSize, server.InBufferSize); Assert.Equal(0, client.OutBufferSize); } } [Fact] public void PipeTransmissionMode_Returns_Byte() { using (ServerClientPair pair = CreateServerClientPair()) { Assert.Equal(PipeTransmissionMode.Byte, pair.writeablePipe.TransmissionMode); Assert.Equal(PipeTransmissionMode.Byte, pair.readablePipe.TransmissionMode); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Unix doesn't currently support message mode public void Windows_SetReadModeTo__PipeTransmissionModeByte() { string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); // Throws regardless of connection status for the pipe that is set to PipeDirection.In Assert.Throws<UnauthorizedAccessException>(() => server.ReadMode = PipeTransmissionMode.Byte); client.ReadMode = PipeTransmissionMode.Byte; } using (var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); // Throws regardless of connection status for the pipe that is set to PipeDirection.In Assert.Throws<UnauthorizedAccessException>(() => client.ReadMode = PipeTransmissionMode.Byte); server.ReadMode = PipeTransmissionMode.Byte; } using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); server.ReadMode = PipeTransmissionMode.Byte; client.ReadMode = PipeTransmissionMode.Byte; } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Unix doesn't currently support message mode public void Unix_SetReadModeTo__PipeTransmissionModeByte() { string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); server.ReadMode = PipeTransmissionMode.Byte; client.ReadMode = PipeTransmissionMode.Byte; } using (var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); client.ReadMode = PipeTransmissionMode.Byte; server.ReadMode = PipeTransmissionMode.Byte; } using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); server.ReadMode = PipeTransmissionMode.Byte; client.ReadMode = PipeTransmissionMode.Byte; } } [Theory] [InlineData(PipeDirection.Out, PipeDirection.In)] [InlineData(PipeDirection.In, PipeDirection.Out)] public void InvalidReadMode_Throws_ArgumentOutOfRangeException(PipeDirection serverDirection, PipeDirection clientDirection) { string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, serverDirection, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var client = new NamedPipeClientStream(".", pipeName, clientDirection)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); Assert.Throws<ArgumentOutOfRangeException>(() => server.ReadMode = (PipeTransmissionMode)999); Assert.Throws<ArgumentOutOfRangeException>(() => client.ReadMode = (PipeTransmissionMode)999); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Checks MaxLength for PipeName on Unix public void NameTooLong_MaxLengthPerPlatform() { // Increase a name's length until it fails ArgumentOutOfRangeException e = null; string name = Path.GetRandomFileName(); for (int i = 0; ; i++) { try { name += 'c'; using (var s = new NamedPipeServerStream(name)) using (var c = new NamedPipeClientStream(name)) { Task t = s.WaitForConnectionAsync(); c.Connect(); t.GetAwaiter().GetResult(); } } catch (ArgumentOutOfRangeException exc) { e = exc; break; } } Assert.NotNull(e); Assert.NotNull(e.ActualValue); // Validate the length was expected string path = (string)e.ActualValue; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Assert.Equal(108, path.Length); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { Assert.Equal(104, path.Length); } else { Assert.InRange(path.Length, 92, int.MaxValue); } } } }
/* * Copyright 2004 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Reflection; using System.Runtime.Remoting; using System.Runtime.Remoting.Messaging; using System.Runtime.Remoting.Proxies; using NUnit.Framework; using Solenoid.Expressions.Support.Util; using Solenoid.Expressions.Tests.Objects; namespace Solenoid.Expressions.Tests.Util { /// <summary> /// Unit tests for the AssertUtils class. /// </summary> /// <author>Rick Evans</author> [TestFixture] public sealed class AssertUtilsTests { [Test] [ExpectedException(typeof (ArgumentException), ExpectedMessage = "foo")] public void IsTrueWithMesssage() { AssertUtils.IsTrue(false, "foo"); } [Test] public void IsTrueWithMessageValidExpression() { AssertUtils.IsTrue(true, "foo"); } [Test] [ExpectedException(typeof (ArgumentException), ExpectedMessage = "[Assertion failed] - this expression must be true")] public void IsTrue() { AssertUtils.IsTrue(false); } [Test] public void IsTrueValidExpression() { AssertUtils.IsTrue(true); } [Test] [ExpectedException(typeof (InvalidOperationException))] public void StateTrue() { AssertUtils.State(false, "foo"); } [Test] [ExpectedException(typeof (ArgumentNullException))] public void ArgumentNotNull() { AssertUtils.ArgumentNotNull(null, "foo"); } [Test] [ExpectedException(typeof (ArgumentNullException))] public void ArgumentNotNullWithMessage() { AssertUtils.ArgumentNotNull(null, "foo", "Bang!"); } [Test] public void ArgumentHasTextWithValidText() { AssertUtils.ArgumentHasText("... and no-one's getting fat 'cept Mama Cas!", "foo"); } [Test] public void ArgumentHasTextWithValidTextAndMessage() { AssertUtils.ArgumentHasText("... and no-one's getting fat 'cept Mama Cas!", "foo", "Bang!"); } [Test] [ExpectedException(typeof (ArgumentNullException))] public void ArgumentHasText() { AssertUtils.ArgumentHasText(null, "foo"); } [Test] [ExpectedException(typeof (ArgumentNullException))] public void ArgumentHasTextWithMessage() { AssertUtils.ArgumentHasText(null, "foo", "Bang!"); } [Test] [ExpectedException(typeof (ArgumentNullException))] public void ArgumentHasLengthArgumentIsNull() { AssertUtils.ArgumentHasLength(null, "foo"); } [Test] [ExpectedException(typeof (ArgumentNullException))] public void ArgumentHasLengthArgumentIsNullWithMessage() { AssertUtils.ArgumentHasLength(null, "foo", "Bang!"); } [Test] [ExpectedException(typeof (ArgumentNullException))] public void ArgumentHasLengthArgumentIsEmpty() { AssertUtils.ArgumentHasLength(new byte[0], "foo"); } [Test] [ExpectedException(typeof (ArgumentNullException))] public void ArgumentHasLengthArgumentIsEmptyWithMessage() { AssertUtils.ArgumentHasLength(new byte[0], "foo", "Bang!"); } [Test] public void ArgumentHasLengthArgumentHasElements() { AssertUtils.ArgumentHasLength(new byte[1], "foo"); } [Test] public void ArgumentHasLengthArgumentHasElementsWithMessage() { AssertUtils.ArgumentHasLength(new byte[1], "foo", "Bang!"); } [Test] [ExpectedException(typeof (ArgumentException))] public void ArgumentHasElementsArgumentIsNull() { AssertUtils.ArgumentHasElements(null, "foo"); } [Test] [ExpectedException(typeof (ArgumentException))] public void ArgumentHasElementsArgumentIsEmpty() { AssertUtils.ArgumentHasElements(new object[0], "foo"); } [Test] [ExpectedException(typeof (ArgumentException))] public void ArgumentHasElementsArgumentContainsNull() { AssertUtils.ArgumentHasElements(new object[] {new object(), null, new object()}, "foo"); } [Test] public void ArgumentHasElementsArgumentContainsNonNullsOnly() { AssertUtils.ArgumentHasElements(new object[] {new object(), new object(), new object()}, "foo"); } [Test] public void UnderstandsType() { var getDescriptionMethod = typeof (ITestObject).GetMethod("GetDescription", new Type[0]); var understandsMethod = typeof (AssertUtils).GetMethod("Understands", BindingFlags.Public | BindingFlags.Static, null, new Type[] {typeof (object), typeof (string), typeof (MethodBase)}, null); // null target, any type AssertNotUnderstandsType(null, "target", typeof (object), typeof (NotSupportedException), "Target 'target' is null."); // any target, null type AssertNotUnderstandsType(new object(), "target", null, typeof (ArgumentNullException), "Argument 'requiredType' cannot be null."); } [Test] public void UnderstandsMethod() { var getDescriptionMethod = typeof (ITestObject).GetMethod("GetDescription", new Type[0]); var understandsMethod = typeof (AssertUtils).GetMethod("Understands", BindingFlags.Public | BindingFlags.Static, null, new Type[] {typeof (object), typeof (string), typeof (MethodBase)}, null); // null target, static method AssertUtils.Understands(null, "target", understandsMethod); // null target, instance method AssertNotUnderstandsMethod(null, "target", getDescriptionMethod, typeof (NotSupportedException), "Target 'target' is null and target method 'Solenoid.Expressions.Tests.Objects.ITestObject.GetDescription' is not static."); // compatible target, instance method AssertUtils.Understands(new TestObject(), "target", getDescriptionMethod); // incompatible target, instance method AssertNotUnderstandsMethod(new object(), "target", getDescriptionMethod, typeof (NotSupportedException), "Target 'target' of type 'System.Object' does not support methods of 'Solenoid.Expressions.Tests.Objects.ITestObject'."); // compatible transparent proxy, instance method var compatibleProxy = new TestProxy(new TestObject()).GetTransparentProxy(); AssertUtils.Understands(compatibleProxy, "compatibleProxy", getDescriptionMethod); // incompatible transparent proxy, instance method var incompatibleProxy = new TestProxy(new object()).GetTransparentProxy(); AssertNotUnderstandsMethod(incompatibleProxy, "incompatibleProxy", getDescriptionMethod, typeof (NotSupportedException), "Target 'incompatibleProxy' is a transparent proxy that does not support methods of 'Solenoid.Expressions.Tests.Objects.ITestObject'."); } private void AssertNotUnderstandsType(object target, string targetName, Type requiredType, Type exceptionType, string partialMessage) { try { AssertUtils.Understands(target, targetName, requiredType); Assert.Fail(); } catch (Exception ex) { if (ex.GetType() != exceptionType) { Assert.Fail("Expected Exception of type {0}, but was {1}", exceptionType, ex.GetType()); } if (-1 == ex.Message.IndexOf(partialMessage)) { Assert.Fail("Expected Message '{0}', but got '{1}'", partialMessage, ex.Message); } } } private void AssertNotUnderstandsMethod(object target, string targetName, MethodBase method, Type exceptionType, string partialMessage) { try { AssertUtils.Understands(target, targetName, method); Assert.Fail(); } catch (Exception ex) { if (ex.GetType() != exceptionType) { Assert.Fail("Expected Exception of type {0}, but was {1}", exceptionType, ex.GetType()); } if (-1 == ex.Message.IndexOf(partialMessage)) { Assert.Fail("Expected Message '{0}', but got '{1}'", partialMessage, ex.Message); } } } private class TestProxy : RealProxy, IRemotingTypeInfo { private readonly object targetInstance; public TestProxy(object targetInstance) : base(typeof (MarshalByRefObject)) { this.targetInstance = targetInstance; } public override IMessage Invoke(IMessage msg) { // return new ReturnMessage(result, null, 0, null, callMsg); throw new NotSupportedException(); } public bool CanCastTo(Type fromType, object o) { var res = fromType.IsAssignableFrom(targetInstance.GetType()); return res; } public string TypeName { get { return targetInstance.GetType().AssemblyQualifiedName; } set { throw new NotSupportedException(); } } } } }
// ------------------------------------------------------------------------------------------------------------------- // Generated code, do not edit // Command Line: DomGen "xleroot.xsd" "Schema.cs" "gap" "LevelEditorXLE" // ------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using Sce.Atf.Dom; namespace LevelEditorXLE { public static class Schema { public const string NS = "gap"; public static void Initialize(XmlSchemaTypeCollection typeCollection) { Initialize((ns,name)=>typeCollection.GetNodeType(ns,name), (ns,name)=>typeCollection.GetRootElement(ns,name)); } public static void Initialize(IDictionary<string, XmlSchemaTypeCollection> typeCollections) { Initialize((ns,name)=>typeCollections[ns].GetNodeType(name), (ns,name)=>typeCollections[ns].GetRootElement(name)); } private static void Initialize(Func<string, string, DomNodeType> getNodeType, Func<string, string, ChildInfo> getRootElement) { placementsDocumentType.Type = getNodeType("gap", "placementsDocumentType"); placementsDocumentType.nameAttribute = placementsDocumentType.Type.GetAttributeInfo("name"); placementsDocumentType.placementChild = placementsDocumentType.Type.GetChildInfo("placement"); abstractPlacementObjectType.Type = getNodeType("gap", "abstractPlacementObjectType"); abstractPlacementObjectType.transformAttribute = abstractPlacementObjectType.Type.GetAttributeInfo("transform"); abstractPlacementObjectType.translateAttribute = abstractPlacementObjectType.Type.GetAttributeInfo("translate"); abstractPlacementObjectType.rotateAttribute = abstractPlacementObjectType.Type.GetAttributeInfo("rotate"); abstractPlacementObjectType.scaleAttribute = abstractPlacementObjectType.Type.GetAttributeInfo("scale"); abstractPlacementObjectType.pivotAttribute = abstractPlacementObjectType.Type.GetAttributeInfo("pivot"); abstractPlacementObjectType.transformationTypeAttribute = abstractPlacementObjectType.Type.GetAttributeInfo("transformationType"); abstractPlacementObjectType.visibleAttribute = abstractPlacementObjectType.Type.GetAttributeInfo("visible"); abstractPlacementObjectType.lockedAttribute = abstractPlacementObjectType.Type.GetAttributeInfo("locked"); abstractPlacementObjectType.IDAttribute = abstractPlacementObjectType.Type.GetAttributeInfo("ID"); transformObjectType.Type = getNodeType("gap", "transformObjectType"); transformObjectType.transformAttribute = transformObjectType.Type.GetAttributeInfo("transform"); transformObjectType.translateAttribute = transformObjectType.Type.GetAttributeInfo("translate"); transformObjectType.rotateAttribute = transformObjectType.Type.GetAttributeInfo("rotate"); transformObjectType.scaleAttribute = transformObjectType.Type.GetAttributeInfo("scale"); transformObjectType.pivotAttribute = transformObjectType.Type.GetAttributeInfo("pivot"); transformObjectType.transformationTypeAttribute = transformObjectType.Type.GetAttributeInfo("transformationType"); gameType.Type = getNodeType("gap", "gameType"); gameType.nameAttribute = gameType.Type.GetAttributeInfo("name"); gameType.fogEnabledAttribute = gameType.Type.GetAttributeInfo("fogEnabled"); gameType.fogColorAttribute = gameType.Type.GetAttributeInfo("fogColor"); gameType.fogRangeAttribute = gameType.Type.GetAttributeInfo("fogRange"); gameType.fogDensityAttribute = gameType.Type.GetAttributeInfo("fogDensity"); gameType.gameObjectFolderChild = gameType.Type.GetChildInfo("gameObjectFolder"); gameType.layersChild = gameType.Type.GetChildInfo("layers"); gameType.bookmarksChild = gameType.Type.GetChildInfo("bookmarks"); gameType.gameReferenceChild = gameType.Type.GetChildInfo("gameReference"); gameType.gridChild = gameType.Type.GetChildInfo("grid"); gameObjectFolderType.Type = getNodeType("gap", "gameObjectFolderType"); gameObjectFolderType.nameAttribute = gameObjectFolderType.Type.GetAttributeInfo("name"); gameObjectFolderType.visibleAttribute = gameObjectFolderType.Type.GetAttributeInfo("visible"); gameObjectFolderType.lockedAttribute = gameObjectFolderType.Type.GetAttributeInfo("locked"); gameObjectFolderType.gameObjectChild = gameObjectFolderType.Type.GetChildInfo("gameObject"); gameObjectFolderType.folderChild = gameObjectFolderType.Type.GetChildInfo("folder"); gameObjectType.Type = getNodeType("gap", "gameObjectType"); gameObjectType.transformAttribute = gameObjectType.Type.GetAttributeInfo("transform"); gameObjectType.translateAttribute = gameObjectType.Type.GetAttributeInfo("translate"); gameObjectType.rotateAttribute = gameObjectType.Type.GetAttributeInfo("rotate"); gameObjectType.scaleAttribute = gameObjectType.Type.GetAttributeInfo("scale"); gameObjectType.pivotAttribute = gameObjectType.Type.GetAttributeInfo("pivot"); gameObjectType.transformationTypeAttribute = gameObjectType.Type.GetAttributeInfo("transformationType"); gameObjectType.nameAttribute = gameObjectType.Type.GetAttributeInfo("name"); gameObjectType.visibleAttribute = gameObjectType.Type.GetAttributeInfo("visible"); gameObjectType.lockedAttribute = gameObjectType.Type.GetAttributeInfo("locked"); layersType.Type = getNodeType("gap", "layersType"); layersType.layerChild = layersType.Type.GetChildInfo("layer"); layerType.Type = getNodeType("gap", "layerType"); layerType.nameAttribute = layerType.Type.GetAttributeInfo("name"); layerType.gameObjectReferenceChild = layerType.Type.GetChildInfo("gameObjectReference"); layerType.layerChild = layerType.Type.GetChildInfo("layer"); gameObjectReferenceType.Type = getNodeType("gap", "gameObjectReferenceType"); gameObjectReferenceType.refAttribute = gameObjectReferenceType.Type.GetAttributeInfo("ref"); bookmarksType.Type = getNodeType("gap", "bookmarksType"); bookmarksType.bookmarkChild = bookmarksType.Type.GetChildInfo("bookmark"); bookmarkType.Type = getNodeType("gap", "bookmarkType"); bookmarkType.nameAttribute = bookmarkType.Type.GetAttributeInfo("name"); bookmarkType.cameraChild = bookmarkType.Type.GetChildInfo("camera"); bookmarkType.bookmarkChild = bookmarkType.Type.GetChildInfo("bookmark"); cameraType.Type = getNodeType("gap", "cameraType"); cameraType.eyeAttribute = cameraType.Type.GetAttributeInfo("eye"); cameraType.lookAtPointAttribute = cameraType.Type.GetAttributeInfo("lookAtPoint"); cameraType.upVectorAttribute = cameraType.Type.GetAttributeInfo("upVector"); cameraType.viewTypeAttribute = cameraType.Type.GetAttributeInfo("viewType"); cameraType.yFovAttribute = cameraType.Type.GetAttributeInfo("yFov"); cameraType.nearZAttribute = cameraType.Type.GetAttributeInfo("nearZ"); cameraType.farZAttribute = cameraType.Type.GetAttributeInfo("farZ"); cameraType.focusRadiusAttribute = cameraType.Type.GetAttributeInfo("focusRadius"); gameReferenceType.Type = getNodeType("gap", "gameReferenceType"); gameReferenceType.nameAttribute = gameReferenceType.Type.GetAttributeInfo("name"); gameReferenceType.refAttribute = gameReferenceType.Type.GetAttributeInfo("ref"); gameReferenceType.tagsAttribute = gameReferenceType.Type.GetAttributeInfo("tags"); gridType.Type = getNodeType("gap", "gridType"); gridType.sizeAttribute = gridType.Type.GetAttributeInfo("size"); gridType.subdivisionsAttribute = gridType.Type.GetAttributeInfo("subdivisions"); gridType.heightAttribute = gridType.Type.GetAttributeInfo("height"); gridType.snapAttribute = gridType.Type.GetAttributeInfo("snap"); gridType.visibleAttribute = gridType.Type.GetAttributeInfo("visible"); ambientSettingsType.Type = getNodeType("gap", "ambientSettingsType"); ambientSettingsType.AmbientLightAttribute = ambientSettingsType.Type.GetAttributeInfo("AmbientLight"); ambientSettingsType.AmbientBrightnessAttribute = ambientSettingsType.Type.GetAttributeInfo("AmbientBrightness"); ambientSettingsType.SkyTextureAttribute = ambientSettingsType.Type.GetAttributeInfo("SkyTexture"); ambientSettingsType.SkyReflectionScaleAttribute = ambientSettingsType.Type.GetAttributeInfo("SkyReflectionScale"); ambientSettingsType.SkyReflectionBlurrinessAttribute = ambientSettingsType.Type.GetAttributeInfo("SkyReflectionBlurriness"); ambientSettingsType.SkyBrightnessAttribute = ambientSettingsType.Type.GetAttributeInfo("SkyBrightness"); ambientSettingsType.RangeFogInscatterAttribute = ambientSettingsType.Type.GetAttributeInfo("RangeFogInscatter"); ambientSettingsType.RangeFogInscatterScaleAttribute = ambientSettingsType.Type.GetAttributeInfo("RangeFogInscatterScale"); ambientSettingsType.RangeFogThicknessAttribute = ambientSettingsType.Type.GetAttributeInfo("RangeFogThickness"); ambientSettingsType.RangeFogThicknessScaleAttribute = ambientSettingsType.Type.GetAttributeInfo("RangeFogThicknessScale"); ambientSettingsType.AtmosBlurStdDevAttribute = ambientSettingsType.Type.GetAttributeInfo("AtmosBlurStdDev"); ambientSettingsType.AtmosBlurStartAttribute = ambientSettingsType.Type.GetAttributeInfo("AtmosBlurStart"); ambientSettingsType.AtmosBlurEndAttribute = ambientSettingsType.Type.GetAttributeInfo("AtmosBlurEnd"); ambientSettingsType.FlagsAttribute = ambientSettingsType.Type.GetAttributeInfo("Flags"); toneMapSettingsType.Type = getNodeType("gap", "toneMapSettingsType"); toneMapSettingsType.BloomScaleAttribute = toneMapSettingsType.Type.GetAttributeInfo("BloomScale"); toneMapSettingsType.BloomThresholdAttribute = toneMapSettingsType.Type.GetAttributeInfo("BloomThreshold"); toneMapSettingsType.BloomRampingFactorAttribute = toneMapSettingsType.Type.GetAttributeInfo("BloomRampingFactor"); toneMapSettingsType.BloomDesaturationFactorAttribute = toneMapSettingsType.Type.GetAttributeInfo("BloomDesaturationFactor"); toneMapSettingsType.BloomBlurStdDevAttribute = toneMapSettingsType.Type.GetAttributeInfo("BloomBlurStdDev"); toneMapSettingsType.BloomBrightnessAttribute = toneMapSettingsType.Type.GetAttributeInfo("BloomBrightness"); toneMapSettingsType.SceneKeyAttribute = toneMapSettingsType.Type.GetAttributeInfo("SceneKey"); toneMapSettingsType.LuminanceMinAttribute = toneMapSettingsType.Type.GetAttributeInfo("LuminanceMin"); toneMapSettingsType.LuminanceMaxAttribute = toneMapSettingsType.Type.GetAttributeInfo("LuminanceMax"); toneMapSettingsType.WhitePointAttribute = toneMapSettingsType.Type.GetAttributeInfo("WhitePoint"); toneMapSettingsType.FlagsAttribute = toneMapSettingsType.Type.GetAttributeInfo("Flags"); envObjectType.Type = getNodeType("gap", "envObjectType"); envObjectType.transformAttribute = envObjectType.Type.GetAttributeInfo("transform"); envObjectType.translateAttribute = envObjectType.Type.GetAttributeInfo("translate"); envObjectType.rotateAttribute = envObjectType.Type.GetAttributeInfo("rotate"); envObjectType.scaleAttribute = envObjectType.Type.GetAttributeInfo("scale"); envObjectType.pivotAttribute = envObjectType.Type.GetAttributeInfo("pivot"); envObjectType.transformationTypeAttribute = envObjectType.Type.GetAttributeInfo("transformationType"); envObjectType.nameAttribute = envObjectType.Type.GetAttributeInfo("name"); envObjectType.visibleAttribute = envObjectType.Type.GetAttributeInfo("visible"); envObjectType.lockedAttribute = envObjectType.Type.GetAttributeInfo("locked"); envMiscType.Type = getNodeType("gap", "envMiscType"); envSettingsType.Type = getNodeType("gap", "envSettingsType"); envSettingsType.NameAttribute = envSettingsType.Type.GetAttributeInfo("Name"); envSettingsType.objectsChild = envSettingsType.Type.GetChildInfo("objects"); envSettingsType.settingsChild = envSettingsType.Type.GetChildInfo("settings"); envSettingsType.ambientChild = envSettingsType.Type.GetChildInfo("ambient"); envSettingsType.tonemapChild = envSettingsType.Type.GetChildInfo("tonemap"); envSettingsFolderType.Type = getNodeType("gap", "envSettingsFolderType"); envSettingsFolderType.ExportTargetAttribute = envSettingsFolderType.Type.GetAttributeInfo("ExportTarget"); envSettingsFolderType.ExportEnabledAttribute = envSettingsFolderType.Type.GetAttributeInfo("ExportEnabled"); envSettingsFolderType.settingsChild = envSettingsFolderType.Type.GetChildInfo("settings"); directionalLightType.Type = getNodeType("gap", "directionalLightType"); directionalLightType.transformAttribute = directionalLightType.Type.GetAttributeInfo("transform"); directionalLightType.translateAttribute = directionalLightType.Type.GetAttributeInfo("translate"); directionalLightType.rotateAttribute = directionalLightType.Type.GetAttributeInfo("rotate"); directionalLightType.scaleAttribute = directionalLightType.Type.GetAttributeInfo("scale"); directionalLightType.pivotAttribute = directionalLightType.Type.GetAttributeInfo("pivot"); directionalLightType.transformationTypeAttribute = directionalLightType.Type.GetAttributeInfo("transformationType"); directionalLightType.nameAttribute = directionalLightType.Type.GetAttributeInfo("name"); directionalLightType.visibleAttribute = directionalLightType.Type.GetAttributeInfo("visible"); directionalLightType.lockedAttribute = directionalLightType.Type.GetAttributeInfo("locked"); directionalLightType.DiffuseAttribute = directionalLightType.Type.GetAttributeInfo("Diffuse"); directionalLightType.DiffuseBrightnessAttribute = directionalLightType.Type.GetAttributeInfo("DiffuseBrightness"); directionalLightType.DiffuseModelAttribute = directionalLightType.Type.GetAttributeInfo("DiffuseModel"); directionalLightType.DiffuseWideningMinAttribute = directionalLightType.Type.GetAttributeInfo("DiffuseWideningMin"); directionalLightType.DiffuseWideningMaxAttribute = directionalLightType.Type.GetAttributeInfo("DiffuseWideningMax"); directionalLightType.SpecularAttribute = directionalLightType.Type.GetAttributeInfo("Specular"); directionalLightType.SpecularBrightnessAttribute = directionalLightType.Type.GetAttributeInfo("SpecularBrightness"); directionalLightType.SpecularNonMetalBrightnessAttribute = directionalLightType.Type.GetAttributeInfo("SpecularNonMetalBrightness"); directionalLightType.FlagsAttribute = directionalLightType.Type.GetAttributeInfo("Flags"); directionalLightType.ShadowResolveModelAttribute = directionalLightType.Type.GetAttributeInfo("ShadowResolveModel"); shadowFrustumSettings.Type = getNodeType("gap", "shadowFrustumSettings"); shadowFrustumSettings.NameAttribute = shadowFrustumSettings.Type.GetAttributeInfo("Name"); shadowFrustumSettings.FlagsAttribute = shadowFrustumSettings.Type.GetAttributeInfo("Flags"); shadowFrustumSettings.FrustumCountAttribute = shadowFrustumSettings.Type.GetAttributeInfo("FrustumCount"); shadowFrustumSettings.MaxDistanceFromCameraAttribute = shadowFrustumSettings.Type.GetAttributeInfo("MaxDistanceFromCamera"); shadowFrustumSettings.FrustumSizeFactorAttribute = shadowFrustumSettings.Type.GetAttributeInfo("FrustumSizeFactor"); shadowFrustumSettings.FocusDistanceAttribute = shadowFrustumSettings.Type.GetAttributeInfo("FocusDistance"); shadowFrustumSettings.TextureSizeAttribute = shadowFrustumSettings.Type.GetAttributeInfo("TextureSize"); shadowFrustumSettings.ShadowSlopeScaledBiasAttribute = shadowFrustumSettings.Type.GetAttributeInfo("ShadowSlopeScaledBias"); shadowFrustumSettings.ShadowDepthBiasClampAttribute = shadowFrustumSettings.Type.GetAttributeInfo("ShadowDepthBiasClamp"); shadowFrustumSettings.ShadowRasterDepthBiasAttribute = shadowFrustumSettings.Type.GetAttributeInfo("ShadowRasterDepthBias"); shadowFrustumSettings.WorldSpaceResolveBiasAttribute = shadowFrustumSettings.Type.GetAttributeInfo("WorldSpaceResolveBias"); shadowFrustumSettings.BlurAngleDegreesAttribute = shadowFrustumSettings.Type.GetAttributeInfo("BlurAngleDegrees"); shadowFrustumSettings.MinBlurSearchAttribute = shadowFrustumSettings.Type.GetAttributeInfo("MinBlurSearch"); shadowFrustumSettings.MaxBlurSearchAttribute = shadowFrustumSettings.Type.GetAttributeInfo("MaxBlurSearch"); shadowFrustumSettings.LightAttribute = shadowFrustumSettings.Type.GetAttributeInfo("Light"); oceanSettings.Type = getNodeType("gap", "oceanSettings"); oceanSettings.EnableAttribute = oceanSettings.Type.GetAttributeInfo("Enable"); oceanSettings.WindAngleAttribute = oceanSettings.Type.GetAttributeInfo("WindAngle"); oceanSettings.WindVelocityAttribute = oceanSettings.Type.GetAttributeInfo("WindVelocity"); oceanSettings.PhysicalDimensionsAttribute = oceanSettings.Type.GetAttributeInfo("PhysicalDimensions"); oceanSettings.GridDimensionsAttribute = oceanSettings.Type.GetAttributeInfo("GridDimensions"); oceanSettings.StrengthConstantXYAttribute = oceanSettings.Type.GetAttributeInfo("StrengthConstantXY"); oceanSettings.StrengthConstantZAttribute = oceanSettings.Type.GetAttributeInfo("StrengthConstantZ"); oceanSettings.DetailNormalsStrengthAttribute = oceanSettings.Type.GetAttributeInfo("DetailNormalsStrength"); oceanSettings.SpectrumFadeAttribute = oceanSettings.Type.GetAttributeInfo("SpectrumFade"); oceanSettings.ScaleAgainstWindAttribute = oceanSettings.Type.GetAttributeInfo("ScaleAgainstWind"); oceanSettings.SuppressionFactorAttribute = oceanSettings.Type.GetAttributeInfo("SuppressionFactor"); oceanSettings.GridShiftSpeedAttribute = oceanSettings.Type.GetAttributeInfo("GridShiftSpeed"); oceanSettings.BaseHeightAttribute = oceanSettings.Type.GetAttributeInfo("BaseHeight"); oceanSettings.FoamThresholdAttribute = oceanSettings.Type.GetAttributeInfo("FoamThreshold"); oceanSettings.FoamIncreaseSpeedAttribute = oceanSettings.Type.GetAttributeInfo("FoamIncreaseSpeed"); oceanSettings.FoamIncreaseClampAttribute = oceanSettings.Type.GetAttributeInfo("FoamIncreaseClamp"); oceanSettings.FoamDecreaseAttribute = oceanSettings.Type.GetAttributeInfo("FoamDecrease"); oceanLightingSettings.Type = getNodeType("gap", "oceanLightingSettings"); oceanLightingSettings.FoamBrightnessAttribute = oceanLightingSettings.Type.GetAttributeInfo("FoamBrightness"); oceanLightingSettings.OpticalThicknessScalarAttribute = oceanLightingSettings.Type.GetAttributeInfo("OpticalThicknessScalar"); oceanLightingSettings.OpticalThicknessColorAttribute = oceanLightingSettings.Type.GetAttributeInfo("OpticalThicknessColor"); oceanLightingSettings.SkyReflectionBrightnessAttribute = oceanLightingSettings.Type.GetAttributeInfo("SkyReflectionBrightness"); oceanLightingSettings.UpwellingScaleAttribute = oceanLightingSettings.Type.GetAttributeInfo("UpwellingScale"); oceanLightingSettings.RefractiveIndexAttribute = oceanLightingSettings.Type.GetAttributeInfo("RefractiveIndex"); oceanLightingSettings.ReflectionBumpScaleAttribute = oceanLightingSettings.Type.GetAttributeInfo("ReflectionBumpScale"); oceanLightingSettings.DetailNormalFrequencyAttribute = oceanLightingSettings.Type.GetAttributeInfo("DetailNormalFrequency"); oceanLightingSettings.SpecularityFrequencyAttribute = oceanLightingSettings.Type.GetAttributeInfo("SpecularityFrequency"); oceanLightingSettings.MatSpecularMinAttribute = oceanLightingSettings.Type.GetAttributeInfo("MatSpecularMin"); oceanLightingSettings.MatSpecularMaxAttribute = oceanLightingSettings.Type.GetAttributeInfo("MatSpecularMax"); oceanLightingSettings.MatRoughnessAttribute = oceanLightingSettings.Type.GetAttributeInfo("MatRoughness"); envUtilityType.Type = getNodeType("gap", "envUtilityType"); envUtilityType.SunAngleAttribute = envUtilityType.Type.GetAttributeInfo("SunAngle"); envUtilityType.SunNameAttribute = envUtilityType.Type.GetAttributeInfo("SunName"); fogVolumeType.Type = getNodeType("gap", "fogVolumeType"); fogVolumeType.transformAttribute = fogVolumeType.Type.GetAttributeInfo("transform"); fogVolumeType.translateAttribute = fogVolumeType.Type.GetAttributeInfo("translate"); fogVolumeType.rotateAttribute = fogVolumeType.Type.GetAttributeInfo("rotate"); fogVolumeType.scaleAttribute = fogVolumeType.Type.GetAttributeInfo("scale"); fogVolumeType.pivotAttribute = fogVolumeType.Type.GetAttributeInfo("pivot"); fogVolumeType.transformationTypeAttribute = fogVolumeType.Type.GetAttributeInfo("transformationType"); fogVolumeType.nameAttribute = fogVolumeType.Type.GetAttributeInfo("name"); fogVolumeType.visibleAttribute = fogVolumeType.Type.GetAttributeInfo("visible"); fogVolumeType.lockedAttribute = fogVolumeType.Type.GetAttributeInfo("locked"); fogVolumeType.DensityAttribute = fogVolumeType.Type.GetAttributeInfo("Density"); fogVolumeType.NoiseDensityScaleAttribute = fogVolumeType.Type.GetAttributeInfo("NoiseDensityScale"); fogVolumeType.NoiseSpeedAttribute = fogVolumeType.Type.GetAttributeInfo("NoiseSpeed"); fogVolumeType.ForwardColorAttribute = fogVolumeType.Type.GetAttributeInfo("ForwardColor"); fogVolumeType.ForwardColorScaleAttribute = fogVolumeType.Type.GetAttributeInfo("ForwardColorScale"); fogVolumeType.BackColorAttribute = fogVolumeType.Type.GetAttributeInfo("BackColor"); fogVolumeType.BackColorScaleAttribute = fogVolumeType.Type.GetAttributeInfo("BackColorScale"); fogVolumeType.ESM_CAttribute = fogVolumeType.Type.GetAttributeInfo("ESM_C"); fogVolumeType.ShadowBiasAttribute = fogVolumeType.Type.GetAttributeInfo("ShadowBias"); fogVolumeType.JitteringAmountAttribute = fogVolumeType.Type.GetAttributeInfo("JitteringAmount"); fogVolumeType.HeightStartAttribute = fogVolumeType.Type.GetAttributeInfo("HeightStart"); fogVolumeType.HeightEndAttribute = fogVolumeType.Type.GetAttributeInfo("HeightEnd"); fogVolumeRendererType.Type = getNodeType("gap", "fogVolumeRendererType"); fogVolumeRendererType.BlurredShadowSizeAttribute = fogVolumeRendererType.Type.GetAttributeInfo("BlurredShadowSize"); fogVolumeRendererType.ShadowDownsampleAttribute = fogVolumeRendererType.Type.GetAttributeInfo("ShadowDownsample"); fogVolumeRendererType.SkipShadowFrustumsAttribute = fogVolumeRendererType.Type.GetAttributeInfo("SkipShadowFrustums"); fogVolumeRendererType.MaxShadowFrustumsAttribute = fogVolumeRendererType.Type.GetAttributeInfo("MaxShadowFrustums"); fogVolumeRendererType.GridDimensionsAttribute = fogVolumeRendererType.Type.GetAttributeInfo("GridDimensions"); fogVolumeRendererType.WorldSpaceGridDepthAttribute = fogVolumeRendererType.Type.GetAttributeInfo("WorldSpaceGridDepth"); shallowSurfaceType.Type = getNodeType("gap", "shallowSurfaceType"); shallowSurfaceType.transformAttribute = shallowSurfaceType.Type.GetAttributeInfo("transform"); shallowSurfaceType.translateAttribute = shallowSurfaceType.Type.GetAttributeInfo("translate"); shallowSurfaceType.rotateAttribute = shallowSurfaceType.Type.GetAttributeInfo("rotate"); shallowSurfaceType.scaleAttribute = shallowSurfaceType.Type.GetAttributeInfo("scale"); shallowSurfaceType.pivotAttribute = shallowSurfaceType.Type.GetAttributeInfo("pivot"); shallowSurfaceType.transformationTypeAttribute = shallowSurfaceType.Type.GetAttributeInfo("transformationType"); shallowSurfaceType.nameAttribute = shallowSurfaceType.Type.GetAttributeInfo("name"); shallowSurfaceType.visibleAttribute = shallowSurfaceType.Type.GetAttributeInfo("visible"); shallowSurfaceType.lockedAttribute = shallowSurfaceType.Type.GetAttributeInfo("locked"); shallowSurfaceType.MarkerAttribute = shallowSurfaceType.Type.GetAttributeInfo("Marker"); shallowSurfaceType.GridPhysicalSizeAttribute = shallowSurfaceType.Type.GetAttributeInfo("GridPhysicalSize"); shallowSurfaceType.GridDimsAttribute = shallowSurfaceType.Type.GetAttributeInfo("GridDims"); shallowSurfaceType.SimGridCountAttribute = shallowSurfaceType.Type.GetAttributeInfo("SimGridCount"); shallowSurfaceType.BaseHeightAttribute = shallowSurfaceType.Type.GetAttributeInfo("BaseHeight"); shallowSurfaceType.SimMethodAttribute = shallowSurfaceType.Type.GetAttributeInfo("SimMethod"); shallowSurfaceType.RainQuantityAttribute = shallowSurfaceType.Type.GetAttributeInfo("RainQuantity"); shallowSurfaceType.EvaporationConstantAttribute = shallowSurfaceType.Type.GetAttributeInfo("EvaporationConstant"); shallowSurfaceType.PressureConstantAttribute = shallowSurfaceType.Type.GetAttributeInfo("PressureConstant"); shallowSurfaceType.OpticalThicknessColorAttribute = shallowSurfaceType.Type.GetAttributeInfo("OpticalThicknessColor"); shallowSurfaceType.OpticalThicknessScalarAttribute = shallowSurfaceType.Type.GetAttributeInfo("OpticalThicknessScalar"); shallowSurfaceType.FoamColorAttribute = shallowSurfaceType.Type.GetAttributeInfo("FoamColor"); shallowSurfaceType.SpecularAttribute = shallowSurfaceType.Type.GetAttributeInfo("Specular"); shallowSurfaceType.RoughnessAttribute = shallowSurfaceType.Type.GetAttributeInfo("Roughness"); shallowSurfaceType.RefractiveIndexAttribute = shallowSurfaceType.Type.GetAttributeInfo("RefractiveIndex"); shallowSurfaceType.UpwellingScaleAttribute = shallowSurfaceType.Type.GetAttributeInfo("UpwellingScale"); shallowSurfaceType.SkyReflectionScaleAttribute = shallowSurfaceType.Type.GetAttributeInfo("SkyReflectionScale"); placementsCellReferenceType.Type = getNodeType("gap", "placementsCellReferenceType"); placementsCellReferenceType.refAttribute = placementsCellReferenceType.Type.GetAttributeInfo("ref"); placementsCellReferenceType.ExportTargetAttribute = placementsCellReferenceType.Type.GetAttributeInfo("ExportTarget"); placementsCellReferenceType.nameAttribute = placementsCellReferenceType.Type.GetAttributeInfo("name"); placementsCellReferenceType.captureMinsAttribute = placementsCellReferenceType.Type.GetAttributeInfo("captureMins"); placementsCellReferenceType.captureMaxsAttribute = placementsCellReferenceType.Type.GetAttributeInfo("captureMaxs"); placementsCellReferenceType.offsetAttribute = placementsCellReferenceType.Type.GetAttributeInfo("offset"); placementsCellReferenceType.ExportEnabledAttribute = placementsCellReferenceType.Type.GetAttributeInfo("ExportEnabled"); placementsCellReferenceType.cachedCellMinsAttribute = placementsCellReferenceType.Type.GetAttributeInfo("cachedCellMins"); placementsCellReferenceType.cachedCellMaxsAttribute = placementsCellReferenceType.Type.GetAttributeInfo("cachedCellMaxs"); placementsFolderType.Type = getNodeType("gap", "placementsFolderType"); placementsFolderType.baseEditorPathAttribute = placementsFolderType.Type.GetAttributeInfo("baseEditorPath"); placementsFolderType.baseExportPathAttribute = placementsFolderType.Type.GetAttributeInfo("baseExportPath"); placementsFolderType.CellCountAttribute = placementsFolderType.Type.GetAttributeInfo("CellCount"); placementsFolderType.CellsOriginAttribute = placementsFolderType.Type.GetAttributeInfo("CellsOrigin"); placementsFolderType.CellSizeAttribute = placementsFolderType.Type.GetAttributeInfo("CellSize"); placementsFolderType.ExportTargetAttribute = placementsFolderType.Type.GetAttributeInfo("ExportTarget"); placementsFolderType.ExportEnabledAttribute = placementsFolderType.Type.GetAttributeInfo("ExportEnabled"); placementsFolderType.cellChild = placementsFolderType.Type.GetChildInfo("cell"); placementObjectType.Type = getNodeType("gap", "placementObjectType"); placementObjectType.transformAttribute = placementObjectType.Type.GetAttributeInfo("transform"); placementObjectType.translateAttribute = placementObjectType.Type.GetAttributeInfo("translate"); placementObjectType.rotateAttribute = placementObjectType.Type.GetAttributeInfo("rotate"); placementObjectType.scaleAttribute = placementObjectType.Type.GetAttributeInfo("scale"); placementObjectType.pivotAttribute = placementObjectType.Type.GetAttributeInfo("pivot"); placementObjectType.transformationTypeAttribute = placementObjectType.Type.GetAttributeInfo("transformationType"); placementObjectType.visibleAttribute = placementObjectType.Type.GetAttributeInfo("visible"); placementObjectType.lockedAttribute = placementObjectType.Type.GetAttributeInfo("locked"); placementObjectType.IDAttribute = placementObjectType.Type.GetAttributeInfo("ID"); placementObjectType.modelAttribute = placementObjectType.Type.GetAttributeInfo("model"); placementObjectType.materialAttribute = placementObjectType.Type.GetAttributeInfo("material"); abstractTerrainMaterialDescType.Type = getNodeType("gap", "abstractTerrainMaterialDescType"); abstractTerrainMaterialDescType.MaterialIdAttribute = abstractTerrainMaterialDescType.Type.GetAttributeInfo("MaterialId"); terrainBaseTextureType.Type = getNodeType("gap", "terrainBaseTextureType"); terrainBaseTextureType.diffusedimsAttribute = terrainBaseTextureType.Type.GetAttributeInfo("diffusedims"); terrainBaseTextureType.normaldimsAttribute = terrainBaseTextureType.Type.GetAttributeInfo("normaldims"); terrainBaseTextureType.paramdimsAttribute = terrainBaseTextureType.Type.GetAttributeInfo("paramdims"); terrainBaseTextureType.materialChild = terrainBaseTextureType.Type.GetChildInfo("material"); terrainBaseTextureStrataType.Type = getNodeType("gap", "terrainBaseTextureStrataType"); terrainBaseTextureStrataType.texture0Attribute = terrainBaseTextureStrataType.Type.GetAttributeInfo("texture0"); terrainBaseTextureStrataType.texture1Attribute = terrainBaseTextureStrataType.Type.GetAttributeInfo("texture1"); terrainBaseTextureStrataType.texture2Attribute = terrainBaseTextureStrataType.Type.GetAttributeInfo("texture2"); terrainBaseTextureStrataType.mapping0Attribute = terrainBaseTextureStrataType.Type.GetAttributeInfo("mapping0"); terrainBaseTextureStrataType.mapping1Attribute = terrainBaseTextureStrataType.Type.GetAttributeInfo("mapping1"); terrainBaseTextureStrataType.mapping2Attribute = terrainBaseTextureStrataType.Type.GetAttributeInfo("mapping2"); terrainBaseTextureStrataType.endheightAttribute = terrainBaseTextureStrataType.Type.GetAttributeInfo("endheight"); terrainStrataMaterialType.Type = getNodeType("gap", "terrainStrataMaterialType"); terrainStrataMaterialType.MaterialIdAttribute = terrainStrataMaterialType.Type.GetAttributeInfo("MaterialId"); terrainStrataMaterialType.strataChild = terrainStrataMaterialType.Type.GetChildInfo("strata"); terrainMaterialType.Type = getNodeType("gap", "terrainMaterialType"); terrainMaterialType.MaterialIdAttribute = terrainMaterialType.Type.GetAttributeInfo("MaterialId"); terrainMaterialType.FlatTextureAttribute = terrainMaterialType.Type.GetAttributeInfo("FlatTexture"); terrainMaterialType.SlopeTexture0Attribute = terrainMaterialType.Type.GetAttributeInfo("SlopeTexture0"); terrainMaterialType.SlopeTexture1Attribute = terrainMaterialType.Type.GetAttributeInfo("SlopeTexture1"); terrainMaterialType.SlopeTexture2Attribute = terrainMaterialType.Type.GetAttributeInfo("SlopeTexture2"); terrainMaterialType.BlendingTextureAttribute = terrainMaterialType.Type.GetAttributeInfo("BlendingTexture"); terrainMaterialType.FlatTextureMappingAttribute = terrainMaterialType.Type.GetAttributeInfo("FlatTextureMapping"); terrainMaterialType.SlopeTexture0MappingAttribute = terrainMaterialType.Type.GetAttributeInfo("SlopeTexture0Mapping"); terrainMaterialType.SlopeTexture1MappingAttribute = terrainMaterialType.Type.GetAttributeInfo("SlopeTexture1Mapping"); terrainMaterialType.SlopeTexture2MappingAttribute = terrainMaterialType.Type.GetAttributeInfo("SlopeTexture2Mapping"); terrainMaterialType.BlendingTextureMappingAttribute = terrainMaterialType.Type.GetAttributeInfo("BlendingTextureMapping"); terrainProcTextureType.Type = getNodeType("gap", "terrainProcTextureType"); terrainProcTextureType.MaterialIdAttribute = terrainProcTextureType.Type.GetAttributeInfo("MaterialId"); terrainProcTextureType.NameAttribute = terrainProcTextureType.Type.GetAttributeInfo("Name"); terrainProcTextureType.Texture0Attribute = terrainProcTextureType.Type.GetAttributeInfo("Texture0"); terrainProcTextureType.Texture1Attribute = terrainProcTextureType.Type.GetAttributeInfo("Texture1"); terrainProcTextureType.HGridAttribute = terrainProcTextureType.Type.GetAttributeInfo("HGrid"); terrainProcTextureType.GainAttribute = terrainProcTextureType.Type.GetAttributeInfo("Gain"); vegetationSpawnObjectType.Type = getNodeType("gap", "vegetationSpawnObjectType"); vegetationSpawnObjectType.MaxDrawDistanceAttribute = vegetationSpawnObjectType.Type.GetAttributeInfo("MaxDrawDistance"); vegetationSpawnObjectType.FrequencyWeightAttribute = vegetationSpawnObjectType.Type.GetAttributeInfo("FrequencyWeight"); vegetationSpawnObjectType.ModelAttribute = vegetationSpawnObjectType.Type.GetAttributeInfo("Model"); vegetationSpawnObjectType.MaterialAttribute = vegetationSpawnObjectType.Type.GetAttributeInfo("Material"); vegetationSpawnMaterialType.Type = getNodeType("gap", "vegetationSpawnMaterialType"); vegetationSpawnMaterialType.NoSpawnWeightAttribute = vegetationSpawnMaterialType.Type.GetAttributeInfo("NoSpawnWeight"); vegetationSpawnMaterialType.SuppressionThresholdAttribute = vegetationSpawnMaterialType.Type.GetAttributeInfo("SuppressionThreshold"); vegetationSpawnMaterialType.SuppressionNoiseAttribute = vegetationSpawnMaterialType.Type.GetAttributeInfo("SuppressionNoise"); vegetationSpawnMaterialType.SuppressionGainAttribute = vegetationSpawnMaterialType.Type.GetAttributeInfo("SuppressionGain"); vegetationSpawnMaterialType.SuppressionLacunarityAttribute = vegetationSpawnMaterialType.Type.GetAttributeInfo("SuppressionLacunarity"); vegetationSpawnMaterialType.MaterialIdAttribute = vegetationSpawnMaterialType.Type.GetAttributeInfo("MaterialId"); vegetationSpawnMaterialType.objectChild = vegetationSpawnMaterialType.Type.GetChildInfo("object"); vegetationSpawnConfigType.Type = getNodeType("gap", "vegetationSpawnConfigType"); vegetationSpawnConfigType.BaseGridSpacingAttribute = vegetationSpawnConfigType.Type.GetAttributeInfo("BaseGridSpacing"); vegetationSpawnConfigType.JitterAmountAttribute = vegetationSpawnConfigType.Type.GetAttributeInfo("JitterAmount"); vegetationSpawnConfigType.materialChild = vegetationSpawnConfigType.Type.GetChildInfo("material"); terrainCoverageLayer.Type = getNodeType("gap", "terrainCoverageLayer"); terrainCoverageLayer.IdAttribute = terrainCoverageLayer.Type.GetAttributeInfo("Id"); terrainCoverageLayer.ResolutionAttribute = terrainCoverageLayer.Type.GetAttributeInfo("Resolution"); terrainCoverageLayer.OverlapAttribute = terrainCoverageLayer.Type.GetAttributeInfo("Overlap"); terrainCoverageLayer.SourceFileAttribute = terrainCoverageLayer.Type.GetAttributeInfo("SourceFile"); terrainCoverageLayer.EnableAttribute = terrainCoverageLayer.Type.GetAttributeInfo("Enable"); terrainCoverageLayer.FormatAttribute = terrainCoverageLayer.Type.GetAttributeInfo("Format"); terrainCoverageLayer.ShaderNormalizationModeAttribute = terrainCoverageLayer.Type.GetAttributeInfo("ShaderNormalizationMode"); terrainType.Type = getNodeType("gap", "terrainType"); terrainType.UberSurfaceDirAttribute = terrainType.Type.GetAttributeInfo("UberSurfaceDir"); terrainType.CellsDirAttribute = terrainType.Type.GetAttributeInfo("CellsDir"); terrainType.ConfigFileTargetAttribute = terrainType.Type.GetAttributeInfo("ConfigFileTarget"); terrainType.NodeDimensionsAttribute = terrainType.Type.GetAttributeInfo("NodeDimensions"); terrainType.OverlapAttribute = terrainType.Type.GetAttributeInfo("Overlap"); terrainType.SpacingAttribute = terrainType.Type.GetAttributeInfo("Spacing"); terrainType.CellTreeDepthAttribute = terrainType.Type.GetAttributeInfo("CellTreeDepth"); terrainType.CellCountAttribute = terrainType.Type.GetAttributeInfo("CellCount"); terrainType.OffsetAttribute = terrainType.Type.GetAttributeInfo("Offset"); terrainType.HasEncodedGradientFlagsAttribute = terrainType.Type.GetAttributeInfo("HasEncodedGradientFlags"); terrainType.GradFlagSlopeThreshold0Attribute = terrainType.Type.GetAttributeInfo("GradFlagSlopeThreshold0"); terrainType.GradFlagSlopeThreshold1Attribute = terrainType.Type.GetAttributeInfo("GradFlagSlopeThreshold1"); terrainType.GradFlagSlopeThreshold2Attribute = terrainType.Type.GetAttributeInfo("GradFlagSlopeThreshold2"); terrainType.SunPathAngleAttribute = terrainType.Type.GetAttributeInfo("SunPathAngle"); terrainType.baseTextureChild = terrainType.Type.GetChildInfo("baseTexture"); terrainType.VegetationSpawnChild = terrainType.Type.GetChildInfo("VegetationSpawn"); terrainType.coverageChild = terrainType.Type.GetChildInfo("coverage"); resourceReferenceType.Type = getNodeType("gap", "resourceReferenceType"); resourceReferenceType.uriAttribute = resourceReferenceType.Type.GetAttributeInfo("uri"); gameObjectComponentType.Type = getNodeType("gap", "gameObjectComponentType"); gameObjectComponentType.nameAttribute = gameObjectComponentType.Type.GetAttributeInfo("name"); gameObjectComponentType.activeAttribute = gameObjectComponentType.Type.GetAttributeInfo("active"); transformComponentType.Type = getNodeType("gap", "transformComponentType"); transformComponentType.nameAttribute = transformComponentType.Type.GetAttributeInfo("name"); transformComponentType.activeAttribute = transformComponentType.Type.GetAttributeInfo("active"); transformComponentType.translationAttribute = transformComponentType.Type.GetAttributeInfo("translation"); transformComponentType.rotationAttribute = transformComponentType.Type.GetAttributeInfo("rotation"); transformComponentType.scaleAttribute = transformComponentType.Type.GetAttributeInfo("scale"); gameObjectWithComponentType.Type = getNodeType("gap", "gameObjectWithComponentType"); gameObjectWithComponentType.transformAttribute = gameObjectWithComponentType.Type.GetAttributeInfo("transform"); gameObjectWithComponentType.translateAttribute = gameObjectWithComponentType.Type.GetAttributeInfo("translate"); gameObjectWithComponentType.rotateAttribute = gameObjectWithComponentType.Type.GetAttributeInfo("rotate"); gameObjectWithComponentType.scaleAttribute = gameObjectWithComponentType.Type.GetAttributeInfo("scale"); gameObjectWithComponentType.pivotAttribute = gameObjectWithComponentType.Type.GetAttributeInfo("pivot"); gameObjectWithComponentType.transformationTypeAttribute = gameObjectWithComponentType.Type.GetAttributeInfo("transformationType"); gameObjectWithComponentType.nameAttribute = gameObjectWithComponentType.Type.GetAttributeInfo("name"); gameObjectWithComponentType.visibleAttribute = gameObjectWithComponentType.Type.GetAttributeInfo("visible"); gameObjectWithComponentType.lockedAttribute = gameObjectWithComponentType.Type.GetAttributeInfo("locked"); gameObjectWithComponentType.componentChild = gameObjectWithComponentType.Type.GetChildInfo("component"); gameObjectGroupType.Type = getNodeType("gap", "gameObjectGroupType"); gameObjectGroupType.transformAttribute = gameObjectGroupType.Type.GetAttributeInfo("transform"); gameObjectGroupType.translateAttribute = gameObjectGroupType.Type.GetAttributeInfo("translate"); gameObjectGroupType.rotateAttribute = gameObjectGroupType.Type.GetAttributeInfo("rotate"); gameObjectGroupType.scaleAttribute = gameObjectGroupType.Type.GetAttributeInfo("scale"); gameObjectGroupType.pivotAttribute = gameObjectGroupType.Type.GetAttributeInfo("pivot"); gameObjectGroupType.transformationTypeAttribute = gameObjectGroupType.Type.GetAttributeInfo("transformationType"); gameObjectGroupType.nameAttribute = gameObjectGroupType.Type.GetAttributeInfo("name"); gameObjectGroupType.visibleAttribute = gameObjectGroupType.Type.GetAttributeInfo("visible"); gameObjectGroupType.lockedAttribute = gameObjectGroupType.Type.GetAttributeInfo("locked"); gameObjectGroupType.gameObjectChild = gameObjectGroupType.Type.GetChildInfo("gameObject"); markerPointType.Type = getNodeType("gap", "markerPointType"); markerPointType.translateAttribute = markerPointType.Type.GetAttributeInfo("translate"); triMeshMarkerType.Type = getNodeType("gap", "triMeshMarkerType"); triMeshMarkerType.transformAttribute = triMeshMarkerType.Type.GetAttributeInfo("transform"); triMeshMarkerType.translateAttribute = triMeshMarkerType.Type.GetAttributeInfo("translate"); triMeshMarkerType.rotateAttribute = triMeshMarkerType.Type.GetAttributeInfo("rotate"); triMeshMarkerType.scaleAttribute = triMeshMarkerType.Type.GetAttributeInfo("scale"); triMeshMarkerType.pivotAttribute = triMeshMarkerType.Type.GetAttributeInfo("pivot"); triMeshMarkerType.transformationTypeAttribute = triMeshMarkerType.Type.GetAttributeInfo("transformationType"); triMeshMarkerType.nameAttribute = triMeshMarkerType.Type.GetAttributeInfo("name"); triMeshMarkerType.visibleAttribute = triMeshMarkerType.Type.GetAttributeInfo("visible"); triMeshMarkerType.lockedAttribute = triMeshMarkerType.Type.GetAttributeInfo("locked"); triMeshMarkerType.indexlistAttribute = triMeshMarkerType.Type.GetAttributeInfo("indexlist"); triMeshMarkerType.ShowMarkerAttribute = triMeshMarkerType.Type.GetAttributeInfo("ShowMarker"); triMeshMarkerType.pointsChild = triMeshMarkerType.Type.GetChildInfo("points"); xleGameType.Type = getNodeType("gap", "xleGameType"); xleGameType.nameAttribute = xleGameType.Type.GetAttributeInfo("name"); xleGameType.fogEnabledAttribute = xleGameType.Type.GetAttributeInfo("fogEnabled"); xleGameType.fogColorAttribute = xleGameType.Type.GetAttributeInfo("fogColor"); xleGameType.fogRangeAttribute = xleGameType.Type.GetAttributeInfo("fogRange"); xleGameType.fogDensityAttribute = xleGameType.Type.GetAttributeInfo("fogDensity"); xleGameType.ExportDirectoryAttribute = xleGameType.Type.GetAttributeInfo("ExportDirectory"); xleGameType.gameObjectFolderChild = xleGameType.Type.GetChildInfo("gameObjectFolder"); xleGameType.layersChild = xleGameType.Type.GetChildInfo("layers"); xleGameType.bookmarksChild = xleGameType.Type.GetChildInfo("bookmarks"); xleGameType.gameReferenceChild = xleGameType.Type.GetChildInfo("gameReference"); xleGameType.gridChild = xleGameType.Type.GetChildInfo("grid"); xleGameType.placementsChild = xleGameType.Type.GetChildInfo("placements"); xleGameType.terrainChild = xleGameType.Type.GetChildInfo("terrain"); xleGameType.environmentChild = xleGameType.Type.GetChildInfo("environment"); placementsDocumentRootElement = getRootElement(NS, "placementsDocument"); gameRootElement = getRootElement(NS, "game"); } public static class placementsDocumentType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static ChildInfo placementChild; } public static class abstractPlacementObjectType { public static DomNodeType Type; public static AttributeInfo transformAttribute; public static AttributeInfo translateAttribute; public static AttributeInfo rotateAttribute; public static AttributeInfo scaleAttribute; public static AttributeInfo pivotAttribute; public static AttributeInfo transformationTypeAttribute; public static AttributeInfo visibleAttribute; public static AttributeInfo lockedAttribute; public static AttributeInfo IDAttribute; } public static class transformObjectType { public static DomNodeType Type; public static AttributeInfo transformAttribute; public static AttributeInfo translateAttribute; public static AttributeInfo rotateAttribute; public static AttributeInfo scaleAttribute; public static AttributeInfo pivotAttribute; public static AttributeInfo transformationTypeAttribute; } public static class gameType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo fogEnabledAttribute; public static AttributeInfo fogColorAttribute; public static AttributeInfo fogRangeAttribute; public static AttributeInfo fogDensityAttribute; public static ChildInfo gameObjectFolderChild; public static ChildInfo layersChild; public static ChildInfo bookmarksChild; public static ChildInfo gameReferenceChild; public static ChildInfo gridChild; } public static class gameObjectFolderType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo visibleAttribute; public static AttributeInfo lockedAttribute; public static ChildInfo gameObjectChild; public static ChildInfo folderChild; } public static class gameObjectType { public static DomNodeType Type; public static AttributeInfo transformAttribute; public static AttributeInfo translateAttribute; public static AttributeInfo rotateAttribute; public static AttributeInfo scaleAttribute; public static AttributeInfo pivotAttribute; public static AttributeInfo transformationTypeAttribute; public static AttributeInfo nameAttribute; public static AttributeInfo visibleAttribute; public static AttributeInfo lockedAttribute; } public static class layersType { public static DomNodeType Type; public static ChildInfo layerChild; } public static class layerType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static ChildInfo gameObjectReferenceChild; public static ChildInfo layerChild; } public static class gameObjectReferenceType { public static DomNodeType Type; public static AttributeInfo refAttribute; } public static class bookmarksType { public static DomNodeType Type; public static ChildInfo bookmarkChild; } public static class bookmarkType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static ChildInfo cameraChild; public static ChildInfo bookmarkChild; } public static class cameraType { public static DomNodeType Type; public static AttributeInfo eyeAttribute; public static AttributeInfo lookAtPointAttribute; public static AttributeInfo upVectorAttribute; public static AttributeInfo viewTypeAttribute; public static AttributeInfo yFovAttribute; public static AttributeInfo nearZAttribute; public static AttributeInfo farZAttribute; public static AttributeInfo focusRadiusAttribute; } public static class gameReferenceType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo refAttribute; public static AttributeInfo tagsAttribute; } public static class gridType { public static DomNodeType Type; public static AttributeInfo sizeAttribute; public static AttributeInfo subdivisionsAttribute; public static AttributeInfo heightAttribute; public static AttributeInfo snapAttribute; public static AttributeInfo visibleAttribute; } public static class ambientSettingsType { public static DomNodeType Type; public static AttributeInfo AmbientLightAttribute; public static AttributeInfo AmbientBrightnessAttribute; public static AttributeInfo SkyTextureAttribute; public static AttributeInfo SkyReflectionScaleAttribute; public static AttributeInfo SkyReflectionBlurrinessAttribute; public static AttributeInfo SkyBrightnessAttribute; public static AttributeInfo RangeFogInscatterAttribute; public static AttributeInfo RangeFogInscatterScaleAttribute; public static AttributeInfo RangeFogThicknessAttribute; public static AttributeInfo RangeFogThicknessScaleAttribute; public static AttributeInfo AtmosBlurStdDevAttribute; public static AttributeInfo AtmosBlurStartAttribute; public static AttributeInfo AtmosBlurEndAttribute; public static AttributeInfo FlagsAttribute; } public static class toneMapSettingsType { public static DomNodeType Type; public static AttributeInfo BloomScaleAttribute; public static AttributeInfo BloomThresholdAttribute; public static AttributeInfo BloomRampingFactorAttribute; public static AttributeInfo BloomDesaturationFactorAttribute; public static AttributeInfo BloomBlurStdDevAttribute; public static AttributeInfo BloomBrightnessAttribute; public static AttributeInfo SceneKeyAttribute; public static AttributeInfo LuminanceMinAttribute; public static AttributeInfo LuminanceMaxAttribute; public static AttributeInfo WhitePointAttribute; public static AttributeInfo FlagsAttribute; } public static class envObjectType { public static DomNodeType Type; public static AttributeInfo transformAttribute; public static AttributeInfo translateAttribute; public static AttributeInfo rotateAttribute; public static AttributeInfo scaleAttribute; public static AttributeInfo pivotAttribute; public static AttributeInfo transformationTypeAttribute; public static AttributeInfo nameAttribute; public static AttributeInfo visibleAttribute; public static AttributeInfo lockedAttribute; } public static class envMiscType { public static DomNodeType Type; } public static class envSettingsType { public static DomNodeType Type; public static AttributeInfo NameAttribute; public static ChildInfo objectsChild; public static ChildInfo settingsChild; public static ChildInfo ambientChild; public static ChildInfo tonemapChild; } public static class envSettingsFolderType { public static DomNodeType Type; public static AttributeInfo ExportTargetAttribute; public static AttributeInfo ExportEnabledAttribute; public static ChildInfo settingsChild; } public static class directionalLightType { public static DomNodeType Type; public static AttributeInfo transformAttribute; public static AttributeInfo translateAttribute; public static AttributeInfo rotateAttribute; public static AttributeInfo scaleAttribute; public static AttributeInfo pivotAttribute; public static AttributeInfo transformationTypeAttribute; public static AttributeInfo nameAttribute; public static AttributeInfo visibleAttribute; public static AttributeInfo lockedAttribute; public static AttributeInfo DiffuseAttribute; public static AttributeInfo DiffuseBrightnessAttribute; public static AttributeInfo DiffuseModelAttribute; public static AttributeInfo DiffuseWideningMinAttribute; public static AttributeInfo DiffuseWideningMaxAttribute; public static AttributeInfo SpecularAttribute; public static AttributeInfo SpecularBrightnessAttribute; public static AttributeInfo SpecularNonMetalBrightnessAttribute; public static AttributeInfo FlagsAttribute; public static AttributeInfo ShadowResolveModelAttribute; } public static class shadowFrustumSettings { public static DomNodeType Type; public static AttributeInfo NameAttribute; public static AttributeInfo FlagsAttribute; public static AttributeInfo FrustumCountAttribute; public static AttributeInfo MaxDistanceFromCameraAttribute; public static AttributeInfo FrustumSizeFactorAttribute; public static AttributeInfo FocusDistanceAttribute; public static AttributeInfo TextureSizeAttribute; public static AttributeInfo ShadowSlopeScaledBiasAttribute; public static AttributeInfo ShadowDepthBiasClampAttribute; public static AttributeInfo ShadowRasterDepthBiasAttribute; public static AttributeInfo WorldSpaceResolveBiasAttribute; public static AttributeInfo BlurAngleDegreesAttribute; public static AttributeInfo MinBlurSearchAttribute; public static AttributeInfo MaxBlurSearchAttribute; public static AttributeInfo LightAttribute; } public static class oceanSettings { public static DomNodeType Type; public static AttributeInfo EnableAttribute; public static AttributeInfo WindAngleAttribute; public static AttributeInfo WindVelocityAttribute; public static AttributeInfo PhysicalDimensionsAttribute; public static AttributeInfo GridDimensionsAttribute; public static AttributeInfo StrengthConstantXYAttribute; public static AttributeInfo StrengthConstantZAttribute; public static AttributeInfo DetailNormalsStrengthAttribute; public static AttributeInfo SpectrumFadeAttribute; public static AttributeInfo ScaleAgainstWindAttribute; public static AttributeInfo SuppressionFactorAttribute; public static AttributeInfo GridShiftSpeedAttribute; public static AttributeInfo BaseHeightAttribute; public static AttributeInfo FoamThresholdAttribute; public static AttributeInfo FoamIncreaseSpeedAttribute; public static AttributeInfo FoamIncreaseClampAttribute; public static AttributeInfo FoamDecreaseAttribute; } public static class oceanLightingSettings { public static DomNodeType Type; public static AttributeInfo FoamBrightnessAttribute; public static AttributeInfo OpticalThicknessScalarAttribute; public static AttributeInfo OpticalThicknessColorAttribute; public static AttributeInfo SkyReflectionBrightnessAttribute; public static AttributeInfo UpwellingScaleAttribute; public static AttributeInfo RefractiveIndexAttribute; public static AttributeInfo ReflectionBumpScaleAttribute; public static AttributeInfo DetailNormalFrequencyAttribute; public static AttributeInfo SpecularityFrequencyAttribute; public static AttributeInfo MatSpecularMinAttribute; public static AttributeInfo MatSpecularMaxAttribute; public static AttributeInfo MatRoughnessAttribute; } public static class envUtilityType { public static DomNodeType Type; public static AttributeInfo SunAngleAttribute; public static AttributeInfo SunNameAttribute; } public static class fogVolumeType { public static DomNodeType Type; public static AttributeInfo transformAttribute; public static AttributeInfo translateAttribute; public static AttributeInfo rotateAttribute; public static AttributeInfo scaleAttribute; public static AttributeInfo pivotAttribute; public static AttributeInfo transformationTypeAttribute; public static AttributeInfo nameAttribute; public static AttributeInfo visibleAttribute; public static AttributeInfo lockedAttribute; public static AttributeInfo DensityAttribute; public static AttributeInfo NoiseDensityScaleAttribute; public static AttributeInfo NoiseSpeedAttribute; public static AttributeInfo ForwardColorAttribute; public static AttributeInfo ForwardColorScaleAttribute; public static AttributeInfo BackColorAttribute; public static AttributeInfo BackColorScaleAttribute; public static AttributeInfo ESM_CAttribute; public static AttributeInfo ShadowBiasAttribute; public static AttributeInfo JitteringAmountAttribute; public static AttributeInfo HeightStartAttribute; public static AttributeInfo HeightEndAttribute; } public static class fogVolumeRendererType { public static DomNodeType Type; public static AttributeInfo BlurredShadowSizeAttribute; public static AttributeInfo ShadowDownsampleAttribute; public static AttributeInfo SkipShadowFrustumsAttribute; public static AttributeInfo MaxShadowFrustumsAttribute; public static AttributeInfo GridDimensionsAttribute; public static AttributeInfo WorldSpaceGridDepthAttribute; } public static class shallowSurfaceType { public static DomNodeType Type; public static AttributeInfo transformAttribute; public static AttributeInfo translateAttribute; public static AttributeInfo rotateAttribute; public static AttributeInfo scaleAttribute; public static AttributeInfo pivotAttribute; public static AttributeInfo transformationTypeAttribute; public static AttributeInfo nameAttribute; public static AttributeInfo visibleAttribute; public static AttributeInfo lockedAttribute; public static AttributeInfo MarkerAttribute; public static AttributeInfo GridPhysicalSizeAttribute; public static AttributeInfo GridDimsAttribute; public static AttributeInfo SimGridCountAttribute; public static AttributeInfo BaseHeightAttribute; public static AttributeInfo SimMethodAttribute; public static AttributeInfo RainQuantityAttribute; public static AttributeInfo EvaporationConstantAttribute; public static AttributeInfo PressureConstantAttribute; public static AttributeInfo OpticalThicknessColorAttribute; public static AttributeInfo OpticalThicknessScalarAttribute; public static AttributeInfo FoamColorAttribute; public static AttributeInfo SpecularAttribute; public static AttributeInfo RoughnessAttribute; public static AttributeInfo RefractiveIndexAttribute; public static AttributeInfo UpwellingScaleAttribute; public static AttributeInfo SkyReflectionScaleAttribute; } public static class placementsCellReferenceType { public static DomNodeType Type; public static AttributeInfo refAttribute; public static AttributeInfo ExportTargetAttribute; public static AttributeInfo nameAttribute; public static AttributeInfo captureMinsAttribute; public static AttributeInfo captureMaxsAttribute; public static AttributeInfo offsetAttribute; public static AttributeInfo ExportEnabledAttribute; public static AttributeInfo cachedCellMinsAttribute; public static AttributeInfo cachedCellMaxsAttribute; } public static class placementsFolderType { public static DomNodeType Type; public static AttributeInfo baseEditorPathAttribute; public static AttributeInfo baseExportPathAttribute; public static AttributeInfo CellCountAttribute; public static AttributeInfo CellsOriginAttribute; public static AttributeInfo CellSizeAttribute; public static AttributeInfo ExportTargetAttribute; public static AttributeInfo ExportEnabledAttribute; public static ChildInfo cellChild; } public static class placementObjectType { public static DomNodeType Type; public static AttributeInfo transformAttribute; public static AttributeInfo translateAttribute; public static AttributeInfo rotateAttribute; public static AttributeInfo scaleAttribute; public static AttributeInfo pivotAttribute; public static AttributeInfo transformationTypeAttribute; public static AttributeInfo visibleAttribute; public static AttributeInfo lockedAttribute; public static AttributeInfo IDAttribute; public static AttributeInfo modelAttribute; public static AttributeInfo materialAttribute; } public static class abstractTerrainMaterialDescType { public static DomNodeType Type; public static AttributeInfo MaterialIdAttribute; } public static class terrainBaseTextureType { public static DomNodeType Type; public static AttributeInfo diffusedimsAttribute; public static AttributeInfo normaldimsAttribute; public static AttributeInfo paramdimsAttribute; public static ChildInfo materialChild; } public static class terrainBaseTextureStrataType { public static DomNodeType Type; public static AttributeInfo texture0Attribute; public static AttributeInfo texture1Attribute; public static AttributeInfo texture2Attribute; public static AttributeInfo mapping0Attribute; public static AttributeInfo mapping1Attribute; public static AttributeInfo mapping2Attribute; public static AttributeInfo endheightAttribute; } public static class terrainStrataMaterialType { public static DomNodeType Type; public static AttributeInfo MaterialIdAttribute; public static ChildInfo strataChild; } public static class terrainMaterialType { public static DomNodeType Type; public static AttributeInfo MaterialIdAttribute; public static AttributeInfo FlatTextureAttribute; public static AttributeInfo SlopeTexture0Attribute; public static AttributeInfo SlopeTexture1Attribute; public static AttributeInfo SlopeTexture2Attribute; public static AttributeInfo BlendingTextureAttribute; public static AttributeInfo FlatTextureMappingAttribute; public static AttributeInfo SlopeTexture0MappingAttribute; public static AttributeInfo SlopeTexture1MappingAttribute; public static AttributeInfo SlopeTexture2MappingAttribute; public static AttributeInfo BlendingTextureMappingAttribute; } public static class terrainProcTextureType { public static DomNodeType Type; public static AttributeInfo MaterialIdAttribute; public static AttributeInfo NameAttribute; public static AttributeInfo Texture0Attribute; public static AttributeInfo Texture1Attribute; public static AttributeInfo HGridAttribute; public static AttributeInfo GainAttribute; } public static class vegetationSpawnObjectType { public static DomNodeType Type; public static AttributeInfo MaxDrawDistanceAttribute; public static AttributeInfo FrequencyWeightAttribute; public static AttributeInfo ModelAttribute; public static AttributeInfo MaterialAttribute; } public static class vegetationSpawnMaterialType { public static DomNodeType Type; public static AttributeInfo NoSpawnWeightAttribute; public static AttributeInfo SuppressionThresholdAttribute; public static AttributeInfo SuppressionNoiseAttribute; public static AttributeInfo SuppressionGainAttribute; public static AttributeInfo SuppressionLacunarityAttribute; public static AttributeInfo MaterialIdAttribute; public static ChildInfo objectChild; } public static class vegetationSpawnConfigType { public static DomNodeType Type; public static AttributeInfo BaseGridSpacingAttribute; public static AttributeInfo JitterAmountAttribute; public static ChildInfo materialChild; } public static class terrainCoverageLayer { public static DomNodeType Type; public static AttributeInfo IdAttribute; public static AttributeInfo ResolutionAttribute; public static AttributeInfo OverlapAttribute; public static AttributeInfo SourceFileAttribute; public static AttributeInfo EnableAttribute; public static AttributeInfo FormatAttribute; public static AttributeInfo ShaderNormalizationModeAttribute; } public static class terrainType { public static DomNodeType Type; public static AttributeInfo UberSurfaceDirAttribute; public static AttributeInfo CellsDirAttribute; public static AttributeInfo ConfigFileTargetAttribute; public static AttributeInfo NodeDimensionsAttribute; public static AttributeInfo OverlapAttribute; public static AttributeInfo SpacingAttribute; public static AttributeInfo CellTreeDepthAttribute; public static AttributeInfo CellCountAttribute; public static AttributeInfo OffsetAttribute; public static AttributeInfo HasEncodedGradientFlagsAttribute; public static AttributeInfo GradFlagSlopeThreshold0Attribute; public static AttributeInfo GradFlagSlopeThreshold1Attribute; public static AttributeInfo GradFlagSlopeThreshold2Attribute; public static AttributeInfo SunPathAngleAttribute; public static ChildInfo baseTextureChild; public static ChildInfo VegetationSpawnChild; public static ChildInfo coverageChild; } public static class resourceReferenceType { public static DomNodeType Type; public static AttributeInfo uriAttribute; } public static class gameObjectComponentType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo activeAttribute; } public static class transformComponentType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo activeAttribute; public static AttributeInfo translationAttribute; public static AttributeInfo rotationAttribute; public static AttributeInfo scaleAttribute; } public static class gameObjectWithComponentType { public static DomNodeType Type; public static AttributeInfo transformAttribute; public static AttributeInfo translateAttribute; public static AttributeInfo rotateAttribute; public static AttributeInfo scaleAttribute; public static AttributeInfo pivotAttribute; public static AttributeInfo transformationTypeAttribute; public static AttributeInfo nameAttribute; public static AttributeInfo visibleAttribute; public static AttributeInfo lockedAttribute; public static ChildInfo componentChild; } public static class gameObjectGroupType { public static DomNodeType Type; public static AttributeInfo transformAttribute; public static AttributeInfo translateAttribute; public static AttributeInfo rotateAttribute; public static AttributeInfo scaleAttribute; public static AttributeInfo pivotAttribute; public static AttributeInfo transformationTypeAttribute; public static AttributeInfo nameAttribute; public static AttributeInfo visibleAttribute; public static AttributeInfo lockedAttribute; public static ChildInfo gameObjectChild; } public static class markerPointType { public static DomNodeType Type; public static AttributeInfo translateAttribute; } public static class triMeshMarkerType { public static DomNodeType Type; public static AttributeInfo transformAttribute; public static AttributeInfo translateAttribute; public static AttributeInfo rotateAttribute; public static AttributeInfo scaleAttribute; public static AttributeInfo pivotAttribute; public static AttributeInfo transformationTypeAttribute; public static AttributeInfo nameAttribute; public static AttributeInfo visibleAttribute; public static AttributeInfo lockedAttribute; public static AttributeInfo indexlistAttribute; public static AttributeInfo ShowMarkerAttribute; public static ChildInfo pointsChild; } public static class xleGameType { public static DomNodeType Type; public static AttributeInfo nameAttribute; public static AttributeInfo fogEnabledAttribute; public static AttributeInfo fogColorAttribute; public static AttributeInfo fogRangeAttribute; public static AttributeInfo fogDensityAttribute; public static AttributeInfo ExportDirectoryAttribute; public static ChildInfo gameObjectFolderChild; public static ChildInfo layersChild; public static ChildInfo bookmarksChild; public static ChildInfo gameReferenceChild; public static ChildInfo gridChild; public static ChildInfo placementsChild; public static ChildInfo terrainChild; public static ChildInfo environmentChild; } public static ChildInfo placementsDocumentRootElement; public static ChildInfo gameRootElement; } }
// <copyright file="DirectoryWatcherBaseTest.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> namespace DirectoryWatcherSample.Test { using System; using System.Collections.Generic; using System.IO; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public sealed class DirectoryWatcherBaseTest { [TestMethod] public void CreateNullPath() { DirectoryInfo path = null; Action act = () => new FakeDirectoryWatcher(path); act.Should().Throw<ArgumentNullException>().Which.ParamName.Should().Be("path"); } [TestMethod] public void CreateAndDispose() { DirectoryWatcherBase watcher = new FakeDirectoryWatcher(new DirectoryInfo(@"X:\root")); Action act = () => watcher.Dispose(); act.Should().NotThrow(); } [TestMethod] public void UpdateZeroSubscriptions() { FakeDirectoryWatcher watcher = new FakeDirectoryWatcher(new DirectoryInfo(@"X:\root")); Action act = () => watcher.Update(@"X:\root\file1.txt"); act.Should().NotThrow(); } [TestMethod] public void UpdateIrrelevantFileOneSubscription() { List<string> updates = new List<string>(); FakeDirectoryWatcher watcher = new FakeDirectoryWatcher(new DirectoryInfo(@"X:\root")); DirectoryWatcherBase watcherBase = watcher; watcherBase.Subscribe("file1.txt", f => updates.Add(f.FullName)); watcher.Update(@"X:\root\not-relevant.txt"); updates.Should().BeEmpty(); } [TestMethod] public void UpdateRelevantFileOneSubscription() { List<string> updates = new List<string>(); FakeDirectoryWatcher watcher = new FakeDirectoryWatcher(new DirectoryInfo(@"X:\root")); DirectoryWatcherBase watcherBase = watcher; watcherBase.Subscribe("file1.txt", f => updates.Add(f.FullName)); watcher.Update(@"X:\root\file1.txt"); updates.Should().ContainSingle().Which.Should().Be(@"X:\root\file1.txt"); } [TestMethod] public void UpdateRelevantFileOneSubscriptionDifferentCase() { List<string> updates = new List<string>(); FakeDirectoryWatcher watcher = new FakeDirectoryWatcher(new DirectoryInfo(@"X:\root")); DirectoryWatcherBase watcherBase = watcher; watcherBase.Subscribe("file1.txt", f => updates.Add(f.FullName)); watcher.Update(@"X:\root\FILE1.txt"); updates.Should().ContainSingle().Which.Should().Be(@"X:\root\file1.txt"); } [TestMethod] public void UpdateTwoFilesTwoSubscriptions() { List<string> updates = new List<string>(); FakeDirectoryWatcher watcher = new FakeDirectoryWatcher(new DirectoryInfo(@"X:\root")); DirectoryWatcherBase watcherBase = watcher; watcherBase.Subscribe("file1.txt", f => updates.Add(f.FullName)); watcherBase.Subscribe("file2.txt", f => updates.Add(f.FullName)); watcher.Update(@"X:\root\file2.txt"); watcher.Update(@"X:\root\file1.txt"); updates.Should().HaveCount(2).And.ContainInOrder( @"X:\root\file2.txt", @"X:\root\file1.txt"); } [TestMethod] public void UpdateAfterDispose() { List<string> updates = new List<string>(); FakeDirectoryWatcher watcher = new FakeDirectoryWatcher(new DirectoryInfo(@"X:\root")); using (DirectoryWatcherBase watcherBase = watcher) { watcherBase.Subscribe("file1.txt", f => updates.Add(f.FullName)); } watcher.Update(@"X:\root\file1.txt"); updates.Should().BeEmpty(); } [TestMethod] public void UpdateTwoAfterOneSubscriptionDispose() { List<string> updates = new List<string>(); FakeDirectoryWatcher watcher = new FakeDirectoryWatcher(new DirectoryInfo(@"X:\root")); DirectoryWatcherBase watcherBase = watcher; using (watcherBase.Subscribe("file1.txt", f => updates.Add(f.FullName))) { } watcherBase.Subscribe("file2.txt", f => updates.Add(f.FullName)); watcher.Update(@"X:\root\file1.txt"); watcher.Update(@"X:\root\file2.txt"); updates.Should().ContainSingle().Which.Should().Be(@"X:\root\file2.txt"); } [TestMethod] public void AfterSubscriptionDisposeSubscribeAgainAndUpdate() { List<string> updates = new List<string>(); FakeDirectoryWatcher watcher = new FakeDirectoryWatcher(new DirectoryInfo(@"X:\root")); DirectoryWatcherBase watcherBase = watcher; using (watcherBase.Subscribe("file1.txt", f => updates.Add(f.FullName))) { } watcherBase.Subscribe("file1.txt", f => updates.Add(f.FullName)); watcherBase.Subscribe("file2.txt", f => updates.Add(f.FullName)); watcher.Update(@"X:\root\file1.txt"); watcher.Update(@"X:\root\file2.txt"); updates.Should().HaveCount(2).And.ContainInOrder( @"X:\root\file1.txt", @"X:\root\file2.txt"); } [TestMethod] public void SubscribeSameFileTwice() { DirectoryWatcherBase watcherBase = new FakeDirectoryWatcher(new DirectoryInfo(@"X:\root")); Action<FileInfo> onUpdate = f => { }; watcherBase.Subscribe("file1.txt", onUpdate); Action act = () => watcherBase.Subscribe("file1.txt", onUpdate); act.Should().Throw<InvalidOperationException>() .WithMessage(@"A subscription for 'X:\root\file1.txt' already exists."); } [TestMethod] public void SubscribeSameFileTwiceDifferentCase() { DirectoryWatcherBase watcherBase = new FakeDirectoryWatcher(new DirectoryInfo(@"X:\root")); Action<FileInfo> onUpdate = f => { }; watcherBase.Subscribe("file1.txt", onUpdate); Action act = () => watcherBase.Subscribe("FILE1.txt", onUpdate); act.Should().Throw<InvalidOperationException>() .WithMessage(@"A subscription for 'X:\root\FILE1.txt' already exists."); } [TestMethod] public void SubscribeNullFile() { DirectoryWatcherBase watcherBase = new FakeDirectoryWatcher(new DirectoryInfo(@"X:\root")); Action<FileInfo> onUpdate = f => { }; string file = null; Action act = () => watcherBase.Subscribe(file, onUpdate); act.Should().Throw<ArgumentNullException>().Which.ParamName.Should().Be("file"); } [TestMethod] public void SubscribeNullCallback() { DirectoryWatcherBase watcherBase = new FakeDirectoryWatcher(new DirectoryInfo(@"X:\root")); Action<FileInfo> onUpdate = null; Action act = () => watcherBase.Subscribe("file1.txt", onUpdate); act.Should().Throw<ArgumentNullException>().Which.ParamName.Should().Be("onUpdate"); } [TestMethod] public void SubscribeBadFileName() { DirectoryWatcherBase watcherBase = new FakeDirectoryWatcher(new DirectoryInfo(@"X:\root")); Action<FileInfo> onUpdate = f => { }; Action act = () => watcherBase.Subscribe("**BADNAME??", onUpdate); ArgumentException ae = act.Should().Throw<ArgumentException>().Which; ae.Message.Should().Contain("Invalid file name '**BADNAME??'"); ae.ParamName.Should().Be("file"); } [TestMethod] public void SubscribeEmptyFileName() { DirectoryWatcherBase watcherBase = new FakeDirectoryWatcher(new DirectoryInfo(@"X:\root")); Action<FileInfo> onUpdate = f => { }; Action act = () => watcherBase.Subscribe(string.Empty, onUpdate); ArgumentException ae = act.Should().Throw<ArgumentException>().Which; ae.Message.Should().Contain("File name cannot be empty"); ae.ParamName.Should().Be("file"); } [TestMethod] public void SubscribeDotFileName() { DirectoryWatcherBase watcherBase = new FakeDirectoryWatcher(new DirectoryInfo(@"X:\root")); Action<FileInfo> onUpdate = f => { }; Action act = () => watcherBase.Subscribe(".", onUpdate); ArgumentException ae = act.Should().Throw<ArgumentException>().Which; ae.Message.Should().Contain(@"The file '.' is not directly within directory 'X:\root'"); ae.ParamName.Should().Be("file"); } [TestMethod] public void SubscribeFileRelativeSubDir() { DirectoryWatcherBase watcherBase = new FakeDirectoryWatcher(new DirectoryInfo(@"X:\root")); Action<FileInfo> onUpdate = f => { }; Action act = () => watcherBase.Subscribe(@"inner\file1.txt", onUpdate); ArgumentException ae = act.Should().Throw<ArgumentException>().Which; ae.Message.Should().Contain(@"Invalid file name 'inner\file1.txt'"); ae.ParamName.Should().Be("file"); } [TestMethod] public void SubscribeFileRelativeOutsideDir() { DirectoryWatcherBase watcherBase = new FakeDirectoryWatcher(new DirectoryInfo(@"X:\root")); Action<FileInfo> onUpdate = f => { }; Action act = () => watcherBase.Subscribe(@"..\file1.txt", onUpdate); ArgumentException ae = act.Should().Throw<ArgumentException>().Which; ae.Message.Should().Contain(@"Invalid file name '..\file1.txt'"); ae.ParamName.Should().Be("file"); } [TestMethod] public void SubscribeFileRootedPath() { DirectoryWatcherBase watcherBase = new FakeDirectoryWatcher(new DirectoryInfo(@"X:\root")); Action<FileInfo> onUpdate = f => { }; Action act = () => watcherBase.Subscribe(@"D:\path.txt", onUpdate); ArgumentException ae = act.Should().Throw<ArgumentException>().Which; ae.Message.Should().Contain(@"Invalid file name 'D:\path.txt'"); ae.ParamName.Should().Be("file"); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; namespace ClosedXML.Excel { public enum XLDataType { Text, Number, Boolean, DateTime, TimeSpan } public enum XLTableCellType { None, Header, Data, Total } public enum XLClearOptions { ContentsAndFormats, Contents, Formats } public interface IXLCell { /// <summary> /// Gets or sets the cell's value. To get or set a strongly typed value, use the GetValue&lt;T&gt; and SetValue methods. /// <para>ClosedXML will try to detect the data type through parsing. If it can't then the value will be left as a string.</para> /// <para>If the object is an IEnumerable, ClosedXML will copy the collection's data into a table starting from this cell.</para> /// <para>If the object is a range, ClosedXML will copy the range starting from this cell.</para> /// <para>Setting the value to an object (not IEnumerable/range) will call the object's ToString() method.</para> /// </summary> /// <value> /// The object containing the value(s) to set. /// </value> Object Value { get; set; } /// <summary>Gets this cell's address, relative to the worksheet.</summary> /// <value>The cell's address.</value> IXLAddress Address { get; } /// <summary> /// Returns the current region. The current region is a range bounded by any combination of blank rows and blank columns /// </summary> /// <value> /// The current region. /// </value> IXLRange CurrentRegion { get; } /// <summary> /// Gets or sets the type of this cell's data. /// <para>Changing the data type will cause ClosedXML to covert the current value to the new data type.</para> /// <para>An exception will be thrown if the current value cannot be converted to the new data type.</para> /// </summary> /// <value> /// The type of the cell's data. /// </value> /// <exception cref="ArgumentException"></exception> XLDataType DataType { get; set; } /// <summary> /// Sets the type of this cell's data. /// <para>Changing the data type will cause ClosedXML to covert the current value to the new data type.</para> /// <para>An exception will be thrown if the current value cannot be converted to the new data type.</para> /// </summary> /// <param name="dataType">Type of the data.</param> /// <returns></returns> IXLCell SetDataType(XLDataType dataType); /// <summary> /// Sets the cell's value. /// <para>If the object is an IEnumerable ClosedXML will copy the collection's data into a table starting from this cell.</para> /// <para>If the object is a range ClosedXML will copy the range starting from this cell.</para> /// <para>Setting the value to an object (not IEnumerable/range) will call the object's ToString() method.</para> /// <para>ClosedXML will try to translate it to the corresponding type, if it can't then the value will be left as a string.</para> /// </summary> /// <value> /// The object containing the value(s) to set. /// </value> IXLCell SetValue<T>(T value); /// <summary> /// Gets the cell's value converted to the T type. /// <para>ClosedXML will try to covert the current value to the T type.</para> /// <para>An exception will be thrown if the current value cannot be converted to the T type.</para> /// </summary> /// <typeparam name="T">The return type.</typeparam> /// <exception cref="ArgumentException"></exception> T GetValue<T>(); /// <summary> /// Gets the cell's value converted to a String. /// </summary> String GetString(); /// <summary> /// Gets the cell's value formatted depending on the cell's data type and style. /// </summary> String GetFormattedString(); /// <summary> /// Gets the cell's value converted to Double. /// <para>ClosedXML will try to covert the current value to Double.</para> /// <para>An exception will be thrown if the current value cannot be converted to Double.</para> /// </summary> Double GetDouble(); /// <summary> /// Gets the cell's value converted to Boolean. /// <para>ClosedXML will try to covert the current value to Boolean.</para> /// <para>An exception will be thrown if the current value cannot be converted to Boolean.</para> /// </summary> Boolean GetBoolean(); /// <summary> /// Gets the cell's value converted to DateTime. /// <para>ClosedXML will try to covert the current value to DateTime.</para> /// <para>An exception will be thrown if the current value cannot be converted to DateTime.</para> /// </summary> DateTime GetDateTime(); /// <summary> /// Gets the cell's value converted to TimeSpan. /// <para>ClosedXML will try to covert the current value to TimeSpan.</para> /// <para>An exception will be thrown if the current value cannot be converted to TimeSpan.</para> /// </summary> TimeSpan GetTimeSpan(); XLHyperlink GetHyperlink(); Boolean TryGetValue<T>(out T value); Boolean HasHyperlink { get; } /// <summary> /// Clears the contents of this cell. /// </summary> /// <param name="clearOptions">Specify what you want to clear.</param> IXLCell Clear(XLClearOptions clearOptions = XLClearOptions.ContentsAndFormats); /// <summary> /// Deletes the current cell and shifts the surrounding cells according to the shiftDeleteCells parameter. /// </summary> /// <param name="shiftDeleteCells">How to shift the surrounding cells.</param> void Delete(XLShiftDeletedCells shiftDeleteCells); /// <summary> /// Gets or sets the cell's formula with A1 references. /// </summary> /// <value>The formula with A1 references.</value> String FormulaA1 { get; set; } IXLCell SetFormulaA1(String formula); /// <summary> /// Gets or sets the cell's formula with R1C1 references. /// </summary> /// <value>The formula with R1C1 references.</value> String FormulaR1C1 { get; set; } IXLCell SetFormulaR1C1(String formula); /// <summary> /// Returns this cell as an IXLRange. /// </summary> IXLRange AsRange(); /// <summary> /// Gets or sets the cell's style. /// </summary> IXLStyle Style { get; set; } /// <summary> /// Gets or sets a value indicating whether this cell's text should be shared or not. /// </summary> /// <value> /// If false the cell's text will not be shared and stored as an inline value. /// </value> Boolean ShareString { get; set; } /// <summary> /// Inserts the IEnumerable data elements and returns the range it occupies. /// </summary> /// <param name="data">The IEnumerable data.</param> IXLRange InsertData(IEnumerable data); /// <summary> /// Inserts the IEnumerable data elements and returns the range it occupies. /// </summary> /// <param name="data">The IEnumerable data.</param> /// <param name="tranpose">if set to <c>true</c> the data will be transposed before inserting.</param> /// <returns></returns> IXLRange InsertData(IEnumerable data, Boolean tranpose); /// <summary> /// Inserts the data of a data table. /// </summary> /// <param name="dataTable">The data table.</param> /// <returns>The range occupied by the inserted data</returns> IXLRange InsertData(DataTable dataTable); /// <summary> /// Inserts the IEnumerable data elements as a table and returns it. /// <para>The new table will receive a generic name: Table#</para> /// </summary> /// <param name="data">The table data.</param> IXLTable InsertTable<T>(IEnumerable<T> data); /// <summary> /// Inserts the IEnumerable data elements as a table and returns it. /// <para>The new table will receive a generic name: Table#</para> /// </summary> /// <param name="data">The table data.</param> /// <param name="createTable"> /// if set to <c>true</c> it will create an Excel table. /// <para>if set to <c>false</c> the table will be created in memory.</para> /// </param> IXLTable InsertTable<T>(IEnumerable<T> data, Boolean createTable); /// <summary> /// Creates an Excel table from the given IEnumerable data elements. /// </summary> /// <param name="data">The table data.</param> /// <param name="tableName">Name of the table.</param> IXLTable InsertTable<T>(IEnumerable<T> data, String tableName); /// <summary> /// Inserts the IEnumerable data elements as a table and returns it. /// </summary> /// <param name="data">The table data.</param> /// <param name="tableName">Name of the table.</param> /// <param name="createTable"> /// if set to <c>true</c> it will create an Excel table. /// <para>if set to <c>false</c> the table will be created in memory.</para> /// </param> IXLTable InsertTable<T>(IEnumerable<T> data, String tableName, Boolean createTable); /// <summary> /// Inserts the DataTable data elements as a table and returns it. /// <para>The new table will receive a generic name: Table#</para> /// </summary> /// <param name="data">The table data.</param> IXLTable InsertTable(DataTable data); /// <summary> /// Inserts the DataTable data elements as a table and returns it. /// <para>The new table will receive a generic name: Table#</para> /// </summary> /// <param name="data">The table data.</param> /// <param name="createTable"> /// if set to <c>true</c> it will create an Excel table. /// <para>if set to <c>false</c> the table will be created in memory.</para> /// </param> IXLTable InsertTable(DataTable data, Boolean createTable); /// <summary> /// Creates an Excel table from the given DataTable data elements. /// </summary> /// <param name="data">The table data.</param> /// <param name="tableName">Name of the table.</param> IXLTable InsertTable(DataTable data, String tableName); /// <summary> /// Inserts the DataTable data elements as a table and returns it. /// </summary> /// <param name="data">The table data.</param> /// <param name="tableName">Name of the table.</param> /// <param name="createTable"> /// if set to <c>true</c> it will create an Excel table. /// <para>if set to <c>false</c> the table will be created in memory.</para> /// </param> IXLTable InsertTable(DataTable data, String tableName, Boolean createTable); XLTableCellType TableCellType(); XLHyperlink Hyperlink { get; set; } IXLWorksheet Worksheet { get; } IXLDataValidation DataValidation { get; } IXLDataValidation NewDataValidation { get; } IXLDataValidation SetDataValidation(); IXLCells InsertCellsAbove(int numberOfRows); IXLCells InsertCellsBelow(int numberOfRows); IXLCells InsertCellsAfter(int numberOfColumns); IXLCells InsertCellsBefore(int numberOfColumns); /// <summary> /// Creates a named range out of this cell. /// <para>If the named range exists, it will add this range to that named range.</para> /// <para>The default scope for the named range is Workbook.</para> /// </summary> /// <param name="rangeName">Name of the range.</param> IXLCell AddToNamed(String rangeName); /// <summary> /// Creates a named range out of this cell. /// <para>If the named range exists, it will add this range to that named range.</para> /// <param name="rangeName">Name of the range.</param> /// <param name="scope">The scope for the named range.</param> /// </summary> IXLCell AddToNamed(String rangeName, XLScope scope); /// <summary> /// Creates a named range out of this cell. /// <para>If the named range exists, it will add this range to that named range.</para> /// <param name="rangeName">Name of the range.</param> /// <param name="scope">The scope for the named range.</param> /// <param name="comment">The comments for the named range.</param> /// </summary> IXLCell AddToNamed(String rangeName, XLScope scope, String comment); IXLCell CopyFrom(IXLCell otherCell); IXLCell CopyFrom(String otherCell); IXLCell CopyTo(IXLCell target); IXLCell CopyTo(String target); String ValueCached { get; } IXLRichText RichText { get; } Boolean HasRichText { get; } IXLComment Comment { get; } Boolean HasComment { get; } Boolean IsMerged(); Boolean IsEmpty(); Boolean IsEmpty(Boolean includeFormats); IXLCell CellAbove(); IXLCell CellAbove(Int32 step); IXLCell CellBelow(); IXLCell CellBelow(Int32 step); IXLCell CellLeft(); IXLCell CellLeft(Int32 step); IXLCell CellRight(); IXLCell CellRight(Int32 step); IXLColumn WorksheetColumn(); IXLRow WorksheetRow(); Boolean HasDataValidation { get; } IXLConditionalFormat AddConditionalFormat(); void Select(); Boolean Active { get; set; } IXLCell SetActive(Boolean value = true); Boolean HasFormula { get; } Boolean HasArrayFormula { get; } IXLRangeAddress FormulaReference { get; set; } } }
// Copyright (C) 2014 dot42 // // Original filename: Android.Sax.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 Android.Sax { /// <summary> /// <para>Listens for the end of text elements. </para> /// </summary> /// <java-name> /// android/sax/EndTextElementListener /// </java-name> [Dot42.DexImport("android/sax/EndTextElementListener", AccessFlags = 1537)] public partial interface IEndTextElementListener /* scope: __dot42__ */ { /// <summary> /// <para>Invoked at the end of a text element with the body of the element.</para><para></para> /// </summary> /// <java-name> /// end /// </java-name> [Dot42.DexImport("end", "(Ljava/lang/String;)V", AccessFlags = 1025)] void End(string body) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Listens for the beginning and ending of elements. </para> /// </summary> /// <java-name> /// android/sax/ElementListener /// </java-name> [Dot42.DexImport("android/sax/ElementListener", AccessFlags = 1537)] public partial interface IElementListener : global::Android.Sax.IStartElementListener, global::Android.Sax.IEndElementListener /* scope: __dot42__ */ { } /// <summary> /// <para>Listens for the beginning and ending of text elements. </para> /// </summary> /// <java-name> /// android/sax/TextElementListener /// </java-name> [Dot42.DexImport("android/sax/TextElementListener", AccessFlags = 1537)] public partial interface ITextElementListener : global::Android.Sax.IStartElementListener, global::Android.Sax.IEndTextElementListener /* scope: __dot42__ */ { } /// <summary> /// <para>Listens for the end of elements. </para> /// </summary> /// <java-name> /// android/sax/EndElementListener /// </java-name> [Dot42.DexImport("android/sax/EndElementListener", AccessFlags = 1537)] public partial interface IEndElementListener /* scope: __dot42__ */ { /// <summary> /// <para>Invoked at the end of an element. </para> /// </summary> /// <java-name> /// end /// </java-name> [Dot42.DexImport("end", "()V", AccessFlags = 1025)] void End() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The root XML element. The entry point for this API. Not safe for concurrent use.</para><para>For example, passing this XML:</para><para><pre> /// &lt;feed xmlns='&gt; /// &lt;entry&gt; /// &lt;id&gt;bob&lt;/id&gt; /// &lt;/entry&gt; /// &lt;/feed&gt; /// </pre></para><para>to this code:</para><para><pre> /// static final String ATOM_NAMESPACE = "http://www.w3.org/2005/Atom"; /// /// ... /// /// RootElement root = new RootElement(ATOM_NAMESPACE, "feed"); /// Element entry = root.getChild(ATOM_NAMESPACE, "entry"); /// entry.getChild(ATOM_NAMESPACE, "id").setEndTextElementListener( /// new EndTextElementListener() { /// public void end(String body) { /// System.out.println("Entry ID: " + body); /// } /// }); /// /// XMLReader reader = ...; /// reader.setContentHandler(root.getContentHandler()); /// reader.parse(...); /// </pre></para><para>would output:</para><para><pre> /// Entry ID: bob /// </pre> </para> /// </summary> /// <java-name> /// android/sax/RootElement /// </java-name> [Dot42.DexImport("android/sax/RootElement", AccessFlags = 33)] public partial class RootElement : global::Android.Sax.Element /* scope: __dot42__ */ { /// <summary> /// <para>Constructs a new root element with the given name.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)] public RootElement(string uri, string localName) /* MethodBuilder.Create */ { } /// <summary> /// <para>Constructs a new root element with the given name. Uses an empty string as the namespace.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public RootElement(string localName) /* MethodBuilder.Create */ { } /// <summary> /// <para>Gets the SAX <c> ContentHandler </c> . Pass this to your SAX parser. </para> /// </summary> /// <java-name> /// getContentHandler /// </java-name> [Dot42.DexImport("getContentHandler", "()Lorg/xml/sax/ContentHandler;", AccessFlags = 1)] public virtual global::Org.Xml.Sax.IContentHandler GetContentHandler() /* MethodBuilder.Create */ { return default(global::Org.Xml.Sax.IContentHandler); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal RootElement() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Gets the SAX <c> ContentHandler </c> . Pass this to your SAX parser. </para> /// </summary> /// <java-name> /// getContentHandler /// </java-name> public global::Org.Xml.Sax.IContentHandler ContentHandler { [Dot42.DexImport("getContentHandler", "()Lorg/xml/sax/ContentHandler;", AccessFlags = 1)] get{ return GetContentHandler(); } } } /// <summary> /// <para>Listens for the beginning of elements. </para> /// </summary> /// <java-name> /// android/sax/StartElementListener /// </java-name> [Dot42.DexImport("android/sax/StartElementListener", AccessFlags = 1537)] public partial interface IStartElementListener /* scope: __dot42__ */ { /// <summary> /// <para>Invoked at the beginning of an element.</para><para></para> /// </summary> /// <java-name> /// start /// </java-name> [Dot42.DexImport("start", "(Lorg/xml/sax/Attributes;)V", AccessFlags = 1025)] void Start(global::Org.Xml.Sax.IAttributes attributes) /* MethodBuilder.Create */ ; } /// <summary> /// <para>An XML element. Provides access to child elements and hooks to listen for events related to this element.</para><para><para>RootElement </para></para> /// </summary> /// <java-name> /// android/sax/Element /// </java-name> [Dot42.DexImport("android/sax/Element", AccessFlags = 33)] public partial class Element /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal Element() /* MethodBuilder.Create */ { } /// <summary> /// <para>Gets the child element with the given name. Uses an empty string as the namespace. </para> /// </summary> /// <java-name> /// getChild /// </java-name> [Dot42.DexImport("getChild", "(Ljava/lang/String;)Landroid/sax/Element;", AccessFlags = 1)] public virtual global::Android.Sax.Element GetChild(string localName) /* MethodBuilder.Create */ { return default(global::Android.Sax.Element); } /// <summary> /// <para>Gets the child element with the given name. </para> /// </summary> /// <java-name> /// getChild /// </java-name> [Dot42.DexImport("getChild", "(Ljava/lang/String;Ljava/lang/String;)Landroid/sax/Element;", AccessFlags = 1)] public virtual global::Android.Sax.Element GetChild(string uri, string localName) /* MethodBuilder.Create */ { return default(global::Android.Sax.Element); } /// <summary> /// <para>Gets the child element with the given name. Uses an empty string as the namespace. We will throw a org.xml.sax.SAXException at parsing time if the specified child is missing. This helps you ensure that your listeners are called. </para> /// </summary> /// <java-name> /// requireChild /// </java-name> [Dot42.DexImport("requireChild", "(Ljava/lang/String;)Landroid/sax/Element;", AccessFlags = 1)] public virtual global::Android.Sax.Element RequireChild(string localName) /* MethodBuilder.Create */ { return default(global::Android.Sax.Element); } /// <summary> /// <para>Gets the child element with the given name. We will throw a org.xml.sax.SAXException at parsing time if the specified child is missing. This helps you ensure that your listeners are called. </para> /// </summary> /// <java-name> /// requireChild /// </java-name> [Dot42.DexImport("requireChild", "(Ljava/lang/String;Ljava/lang/String;)Landroid/sax/Element;", AccessFlags = 1)] public virtual global::Android.Sax.Element RequireChild(string uri, string localName) /* MethodBuilder.Create */ { return default(global::Android.Sax.Element); } /// <summary> /// <para>Sets start and end element listeners at the same time. </para> /// </summary> /// <java-name> /// setElementListener /// </java-name> [Dot42.DexImport("setElementListener", "(Landroid/sax/ElementListener;)V", AccessFlags = 1)] public virtual void SetElementListener(global::Android.Sax.IElementListener elementListener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Sets start and end text element listeners at the same time. </para> /// </summary> /// <java-name> /// setTextElementListener /// </java-name> [Dot42.DexImport("setTextElementListener", "(Landroid/sax/TextElementListener;)V", AccessFlags = 1)] public virtual void SetTextElementListener(global::Android.Sax.ITextElementListener elementListener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Sets a listener for the start of this element. </para> /// </summary> /// <java-name> /// setStartElementListener /// </java-name> [Dot42.DexImport("setStartElementListener", "(Landroid/sax/StartElementListener;)V", AccessFlags = 1)] public virtual void SetStartElementListener(global::Android.Sax.IStartElementListener startElementListener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Sets a listener for the end of this element. </para> /// </summary> /// <java-name> /// setEndElementListener /// </java-name> [Dot42.DexImport("setEndElementListener", "(Landroid/sax/EndElementListener;)V", AccessFlags = 1)] public virtual void SetEndElementListener(global::Android.Sax.IEndElementListener endElementListener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Sets a listener for the end of this text element. </para> /// </summary> /// <java-name> /// setEndTextElementListener /// </java-name> [Dot42.DexImport("setEndTextElementListener", "(Landroid/sax/EndTextElementListener;)V", AccessFlags = 1)] public virtual void SetEndTextElementListener(global::Android.Sax.IEndTextElementListener endTextElementListener) /* MethodBuilder.Create */ { } /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } } }
// <copyright file=TableWindow3D.xaml.cs // <copyright> // Copyright (c) 2016, University of Stuttgart // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software), // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> // <license>MIT License</license> // <main contributors> // Markus Funk, Thomas Kosch, Sven Mayer // </main contributors> // <co-contributors> // Paul Brombosch, Mai El-Komy, Juana Heusler, // Matthias Hoppe, Robert Konrad, Alexander Martin // </co-contributors> // <patent information> // We are aware that this software implements patterns and ideas, // which might be protected by patents in your country. // Example patents in Germany are: // Patent reference number: DE 103 20 557.8 // Patent reference number: DE 10 2013 220 107.9 // Please make sure when using this software not to violate any existing patents in your country. // </patent information> // <date> 11/2/2016 12:25:58 PM</date> using HciLab.Utilities.Mathematics.Core; using HciLab.Utilities.Mathematics.Geometry2D; using motionEAPAdmin.Backend; using motionEAPAdmin.ContentProviders; using motionEAPAdmin.Scene; using System; using System.Diagnostics; using System.Windows; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Media3D; namespace motionEAPAdmin.Frontend { /// <summary> /// Interaction logic for TableWindow.xaml /// </summary> public partial class TableWindow3D : Window { private static TableWindow3D m_Instance; private double m_XSpeed = 0; private double m_YSpeed = 0; private double m_Scalespeed = 0; private bool m_Zooming = false; private PerspectiveCamera m_Camera; public enum Mode { Normal = 0, Calibration = 1, PolygonEdit = 2 } private Mode m_Mode = Mode.Normal; private ModelVisual3D m_CheckerBoardVisual; private ModelVisual3D m_BlackPlane = new ModelVisual3D(); private Point3D m_HoveredPoint = new Point3D(0, 0, 0); private Point3D m_LastHoveredPoint = new Point3D(0, 0, 0); private System.Windows.Media.Imaging.BitmapSource m_CbImage; private bool isDragged = false; //For CameraCalibration via mouse private bool m_MouseMovesCamera = false; private bool m_MouseMovesCameraAngle = false; private bool m_MouseMovesCameraFOV = false; private System.Windows.Point m_LastHoveredPos = new System.Windows.Point(0, 0); public static TableWindow3D Instance { get { if (m_Instance == null) { m_Instance = new TableWindow3D(); } return m_Instance; } } public TableWindow3D() { InitializeComponent(); //This serves as a transparent x,y Plane for Editor interaction //Geometry3D backDrop = new Geometry3D(); //Plane is just a tiny bit set off below the z=0 plane to avoid rendering and interaction overlapping problems m_BlackPlane.Content = HciLab.Utilities.Mash3D.Rectangle3DGeo.Rect(-1000.0, -1000.0, 2000.0, 2000.0, System.Windows.Media.Colors.Black, -0.05); double w = CalibrationManager.Instance.GetProjectionArea().Width; double h = CalibrationManager.Instance.GetProjectionArea().Height; m_Camera = new PerspectiveCamera( SettingsManager.Instance.Settings.SettingsTable.ProjCamPosition, SettingsManager.Instance.Settings.SettingsTable.ProjCamLookDirection, new Vector3D(0, 1, 0), SettingsManager.Instance.Settings.SettingsTable.ProjCamFOV); m_Viewport.Camera = m_Camera; m_Projection.Positions.Clear(); m_Projection.Positions.Add(new Point3D(0, 0, 0)); m_Projection.Positions.Add(new Point3D(w, 0, 0)); m_Projection.Positions.Add(new Point3D(w, h, 0)); m_Projection.Positions.Add(new Point3D(w, h, 0)); m_Projection.Positions.Add(new Point3D(0, h, 0)); m_Projection.Positions.Add(new Point3D(0, 0, 0)); if (ScreenManager.isSecondScreenConnected()) { System.Drawing.Rectangle projectorResolution = ScreenManager.getProjectorResolution(); Left = projectorResolution.Left; Top = projectorResolution.Top; Width = projectorResolution.Width; Height = projectorResolution.Height; } else { AllowsTransparency = false; Topmost = false; WindowStyle = System.Windows.WindowStyle.SingleBorderWindow; } AllowDrop = true; CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering); m_CbImage = CalibrationManager.Instance.renderCheckerboard(32, 20, 1280, 800, 0, 0); m_CheckerBoardVisual = new ModelVisual3D(); m_CheckerBoardVisual.Content = HciLab.Utilities.Mash3D.Image3DGeo.Image(0.0, 0.0, 690.0, 430.0, m_CbImage, -0.01); CalibrationManager.Instance.changedCalibrationMode += new CalibrationManager.ChangedCalibrationModeHandler(Instance_changedCalibrationMode); this.InvalidateVisual(); } public PerspectiveCamera Camera { get; set; } private void ViewPort_Drop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent("SceneItem")) { string item = e.Data.GetData("SceneItem") as string; var pos = e.GetPosition(m_Viewport); var hitRes = VisualTreeHelper.HitTest(m_Viewport, pos); RayMeshGeometry3DHitTestResult rayMeshRes = hitRes as RayMeshGeometry3DHitTestResult; if (rayMeshRes != null) { double x = (double)rayMeshRes.PointHit.X; double y = (double)rayMeshRes.PointHit.Y; Scene.SceneItem s = null; if (item == typeof(SceneRect).ToString()) s = new Scene.SceneRect(x, y, 50, 50, System.Windows.Media.Color.FromRgb(0, 255, 0)); else if (item == typeof(SceneText).ToString()) s = new Scene.SceneText(x, y, "Text", System.Windows.Media.Color.FromRgb(255, 255, 255), 10.0, new FontFamily("Arial")); else if (item == typeof(SceneTextViewer).ToString()) s = new Scene.SceneTextViewer( x, y, 0.2, 0.2, "Text", new FontFamily("Arial"), 10.0, System.Windows.Media.Color.FromRgb(255, 255, 255)); else if (item == typeof(SceneCircle).ToString()) s = new Scene.SceneCircle(x, y, 10, 0.0, Math.PI * 2.0, System.Windows.Media.Color.FromRgb(0, 255, 0)); else if (item == typeof(SceneImage).ToString()) s = new Scene.SceneImage(x, y, 100, 100, null); else if (item == typeof(SceneVideo).ToString()) s = new Scene.SceneVideo(x, y, 100, 100, null); else if (item == typeof(ScenePolygon).ToString()) s = new Scene.ScenePolygon(new Polygon(new Vector2[] { new Vector2(0+x, 0+y), new Vector2(50+x, 50+y), new Vector2(50+x, y) }), System.Windows.Media.Color.FromRgb(0, 255, 0)); else if (item == typeof(SceneAudio).ToString()) s = new Scene.SceneAudio(null); if (s != null) SceneManager.Instance.CurrentScene.Add(s); else throw new NotImplementedException(); } } } private void ViewPort_DragEnter(object sender, DragEventArgs e) { if (!e.Data.GetDataPresent("SceneItem") || sender == e.Source) { e.Effects = DragDropEffects.None; } } void Instance_changedCalibrationMode(object pSource, bool pIsInCalibrationMode, Boolean pSaveCalibration) { if (pIsInCalibrationMode == true) { //Temporarily disabled displaying of calibration Image //this.Content = m_CalibrattionModeImage; m_Mode = Mode.Calibration; } else { //TODO: Do this somewhere else (e.g. CalibrationManager) if (pSaveCalibration) { SettingsManager.Instance.Settings.SettingsTable.ProjCamPosition = m_Camera.Position; SettingsManager.Instance.Settings.SettingsTable.ProjCamLookDirection = m_Camera.LookDirection; SettingsManager.Instance.Settings.SettingsTable.ProjCamFOV = m_Camera.FieldOfView; } m_Mode = Mode.Normal; this.Content = m_Viewport; } this.InvalidateVisual(); } private void Window_Loaded(object sender, RoutedEventArgs e) { if (ScreenManager.isSecondScreenConnected()) WindowState = WindowState.Maximized; } public void ShowCheckerboard() { m_Viewport.Children.Add(m_CheckerBoardVisual); m_Viewport.InvalidateVisual(); } public void HideCheckerboard() { m_Viewport.Children.Remove(m_CheckerBoardVisual); m_Viewport.InvalidateVisual(); } void CompositionTarget_Rendering(object sender, System.EventArgs e) { UpdateSceneManager(); SceneManager.Instance.Update(); if (CalibrationManager.Instance.IsInCalibrationMode == false) { m_Viewport.Children.Clear(); m_Viewport.Children.Add(m_Light); m_Viewport.Children.Add(m_BlackPlane); foreach (Scene.Scene m in SceneManager.Instance.getAllScenes()) { m_Viewport.Children.Add(m); foreach (Scene.SceneItem s in m.Items) { if (s is Scene.Scene) Debugger.Break(); if (s != null) if (m_Viewport.Children.Contains(s)) { m_Viewport.Children.Remove(s); } m_Viewport.Children.Add(s); if (s is Scene.ScenePolygon && (s as Scene.ScenePolygon).IsInEditMode) { m_Viewport.Children.Add(HciLab.Utilities.Mash3D.PolygonMash3D.newPolygonToWireFrame((s as Scene.ScenePolygon).Polygon, (s as Scene.ScenePolygon).Z + 1)); m_Viewport.Children.Add(HciLab.Utilities.Mash3D.PolygonMash3D.newPolygonToPoints((s as Scene.ScenePolygon).Polygon, (s as Scene.ScenePolygon).Z +2)); } } } } } private void UpdateSceneManager() { if (SceneManager.Instance == null || SceneManager.Instance.CurrentScene == null || SceneManager.Instance.CurrentScene.SelectedItem == null) return; if (m_Zooming && m_Scalespeed != 0) { SceneManager.Instance.CurrentScene.SelectedItem.Scale += m_Scalespeed; } else if (m_XSpeed != 0 || m_YSpeed != 0) { SceneManager.Instance.CurrentScene.SelectedItem.Move(m_XSpeed, m_YSpeed); } } protected override void OnMouseDown(System.Windows.Input.MouseButtonEventArgs e) { base.OnMouseDown(e); //UbidisplayManager.Instance.MouseDown((int)e.GetPosition(m_TableCanvas).X, (int)e.GetPosition(m_TableCanvas).Y); } protected override void OnMouseUp(System.Windows.Input.MouseButtonEventArgs e) { base.OnMouseUp(e); //UbidisplayManager.Instance.MouseUp((int)e.GetPosition(m_TableCanvas).X, (int)e.GetPosition(m_TableCanvas).Y); } protected override void OnMouseMove(System.Windows.Input.MouseEventArgs e) { base.OnMouseMove(e); //UbidisplayManager.Instance.MouseMove((int)e.GetPosition(m_TableCanvas).X, (int)e.GetPosition(m_TableCanvas).Y); } protected override void OnTouchDown(System.Windows.Input.TouchEventArgs e) { base.OnTouchDown(e); //UbidisplayManager.Instance.TouchDown((int)e.GetTouchPoint(m_TableCanvas).Position.X, (int)e.GetTouchPoint(m_TableCanvas).Position.Y, e.TouchDevice.Id); } protected override void OnTouchMove(System.Windows.Input.TouchEventArgs e) { base.OnTouchMove(e); //UbidisplayManager.Instance.TouchMove((int)e.GetTouchPoint(m_TableCanvas).Position.X, (int)e.GetTouchPoint(m_TableCanvas).Position.Y, e.TouchDevice.Id); } protected override void OnTouchUp(System.Windows.Input.TouchEventArgs e) { base.OnTouchUp(e); //UbidisplayManager.Instance.TouchUp((int)e.GetTouchPoint(m_TableCanvas).Position.X, (int)e.GetTouchPoint(m_TableCanvas).Position.Y, e.TouchDevice.Id); } protected override void OnKeyDown(System.Windows.Input.KeyEventArgs e) { base.OnKeyDown(e); const double speed = 0.001f; const double sspeed = 0.002f; switch (e.Key) { case System.Windows.Input.Key.LeftShift: case System.Windows.Input.Key.RightShift: m_Zooming = true; break; case System.Windows.Input.Key.Up: if (m_Zooming) m_Scalespeed = sspeed; else m_YSpeed = -speed; break; case System.Windows.Input.Key.Down: if (m_Zooming) m_Scalespeed = -sspeed; else m_YSpeed = speed; break; case System.Windows.Input.Key.Left: if (m_Zooming) m_Scalespeed = -sspeed; else m_XSpeed = -speed; break; case System.Windows.Input.Key.Right: if (m_Zooming) m_Scalespeed = sspeed; else m_XSpeed = speed; break; } } protected override void OnKeyUp(System.Windows.Input.KeyEventArgs e) { base.OnKeyUp(e); switch (e.Key) { case System.Windows.Input.Key.LeftShift: case System.Windows.Input.Key.RightShift: m_Zooming = false; break; case System.Windows.Input.Key.Up: case System.Windows.Input.Key.Down: if (m_Zooming) m_Scalespeed = 0; else m_YSpeed = 0; break; case System.Windows.Input.Key.Left: case System.Windows.Input.Key.Right: if (m_Zooming) m_Scalespeed = 0; else m_XSpeed = 0; break; } } private void OnViewportMouseMove(object sender, System.Windows.Input.MouseEventArgs e) { System.Windows.Point pos = e.GetPosition(m_Viewport); var hitRes = VisualTreeHelper.HitTest(m_Viewport, pos); RayMeshGeometry3DHitTestResult rayMeshRes = hitRes as RayMeshGeometry3DHitTestResult; if (rayMeshRes != null) { if (e.LeftButton == MouseButtonState.Pressed) OnViewMove(rayMeshRes.VisualHit, new Vector2(rayMeshRes.PointHit.X, rayMeshRes.PointHit.Y), MouseButton.Left); else if (e.RightButton == MouseButtonState.Pressed) OnViewMove(rayMeshRes.VisualHit, new Vector2(rayMeshRes.PointHit.X, rayMeshRes.PointHit.Y), MouseButton.Right); else if (e.MiddleButton == MouseButtonState.Pressed) OnViewMove(rayMeshRes.VisualHit, new Vector2(rayMeshRes.PointHit.X, rayMeshRes.PointHit.Y), MouseButton.Middle); } double factor; if (m_Mode == Mode.Calibration) { double xDelta = pos.X - m_LastHoveredPos.X; double yDelta = pos.Y - m_LastHoveredPos.Y; m_LastHoveredPos = pos; if (m_MouseMovesCamera) { factor = 0.1; var cPos = m_Camera.Position; var newCamPos = new Point3D(cPos.X - factor * xDelta, cPos.Y - factor * yDelta, cPos.Z); m_Camera.Position = newCamPos; SettingsManager.Instance.Settings.SettingsTable.ProjCamPosition = newCamPos; } if (m_MouseMovesCameraAngle) { factor = 0.001; var cAngle = m_Camera.LookDirection; var newCamAngle = new Vector3D(cAngle.X, cAngle.Y - factor * yDelta, cAngle.Z); m_Camera.LookDirection = newCamAngle; SettingsManager.Instance.Settings.SettingsTable.ProjCamLookDirection = newCamAngle; } if (m_MouseMovesCameraFOV) { factor = 0.01; double newFOV = m_Camera.FieldOfView + factor * xDelta; m_Camera.FieldOfView = newFOV; SettingsManager.Instance.Settings.SettingsTable.ProjCamFOV = newFOV; } } else { if (rayMeshRes != null) m_HoveredPoint = rayMeshRes.PointHit; if (hitRes != null) { if (hitRes.VisualHit is SceneItem) { if ((hitRes.VisualHit as SceneItem).Touchy == true) Mouse.OverrideCursor = Cursors.SizeAll; else Mouse.OverrideCursor = Cursors.No; } else { Mouse.OverrideCursor = null; } } if (SceneManager.Instance.CurrentScene.SelectedItem != null && isDragged == true) { if (SceneManager.Instance.CurrentScene.SelectedItem is ScenePolygon) (SceneManager.Instance.CurrentScene.SelectedItem as ScenePolygon).Move(m_HoveredPoint.X - m_LastHoveredPoint.X, m_HoveredPoint.Y - m_LastHoveredPoint.Y); else SceneManager.Instance.CurrentScene.SelectedItem.Move(m_HoveredPoint.X - m_LastHoveredPoint.X, m_HoveredPoint.Y - m_LastHoveredPoint.Y); m_LastHoveredPoint = m_HoveredPoint; } } } private void OnViewportMouseDown(object pSender, System.Windows.Input.MouseButtonEventArgs e) { System.Windows.Point pos = e.GetPosition(m_Viewport); var hitRes = VisualTreeHelper.HitTest(m_Viewport, pos); RayMeshGeometry3DHitTestResult rayMeshRes = hitRes as RayMeshGeometry3DHitTestResult; if (rayMeshRes != null) { OnViewDown(rayMeshRes.VisualHit, new Vector2(rayMeshRes.PointHit.X, rayMeshRes.PointHit.Y), e.ChangedButton); } if (m_Mode == Mode.Calibration) { m_LastHoveredPos = pos; if (e.LeftButton == MouseButtonState.Pressed) m_MouseMovesCamera = true; else if (e.RightButton == MouseButtonState.Pressed) m_MouseMovesCameraAngle = true; else if (e.MiddleButton == MouseButtonState.Pressed) m_MouseMovesCameraFOV = true; } else { if (hitRes != null) { if (hitRes.VisualHit is SceneItem && (hitRes.VisualHit as SceneItem).Touchy == true) { SceneItem s = hitRes.VisualHit as SceneItem; SceneManager.Instance.CurrentScene.SelectedItem = s; isDragged = true; BackendControl.Instance.refreshGUI(); } m_LastHoveredPoint = m_HoveredPoint; } } } private void OnViewportMouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e) { System.Windows.Point pos = e.GetPosition(m_Viewport); var hitRes = VisualTreeHelper.HitTest(m_Viewport, pos); RayMeshGeometry3DHitTestResult rayMeshRes = hitRes as RayMeshGeometry3DHitTestResult; if (rayMeshRes != null) { OnViewUp(rayMeshRes.VisualHit, new Vector2(rayMeshRes.PointHit.X, rayMeshRes.PointHit.Y), e.ChangedButton); } if (m_Mode == Mode.Calibration) { if (e.LeftButton == MouseButtonState.Released) m_MouseMovesCamera = false; if (e.RightButton == MouseButtonState.Released) m_MouseMovesCameraAngle = false; if (e.MiddleButton == MouseButtonState.Released) m_MouseMovesCameraFOV = false; } else { isDragged = false; //SceneManager.Instance.CurrentScene.EditItem = null; } } private void OnViewPortMouseEnter(object sender, MouseEventArgs e) { } private void OnViewPortMouseLeave(object sender, MouseEventArgs e) { //SceneManager.Instance.CurrentScene.EditItem = null; Mouse.OverrideCursor = null; isDragged = false; } private void OnViewportMouseWheel(object sender, MouseWheelEventArgs e) { if (m_Mode == Mode.Calibration) { var cPos = m_Camera.Position; var newCamPos = new Point3D(cPos.X, cPos.Y, cPos.Z - (e.Delta * 0.05)); m_Camera.Position = newCamPos; SettingsManager.Instance.Settings.SettingsTable.ProjCamPosition = newCamPos; } } public delegate void ViewDownHandler(object pSource, Vector2 pPos, MouseButton pMouseButton); public event ViewDownHandler viewDown; public void OnViewDown(object pSource, Vector2 pPos, MouseButton pMouseButton) { if (this.viewDown != null) viewDown(pSource, pPos, pMouseButton); } public delegate void ViewUpHandler(object pSource, Vector2 pPos, MouseButton pMouseButton); public event ViewUpHandler viewUp; public void OnViewUp(object pSource, Vector2 pPos, MouseButton pMouseButton) { if (this.viewUp != null) viewUp(pSource, pPos, pMouseButton); } public delegate void ViewMoveHandler(object pSource, Vector2 pPos, MouseButton pMouseButton); public event ViewMoveHandler viewMove; public void OnViewMove(object pSource, Vector2 pPos, MouseButton pMouseButton) { if (this.viewMove != null) viewMove(pSource, pPos, pMouseButton); } } }
// 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 Xunit; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing { public class ValueTupleTests : ParsingTests { protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { return SyntaxFactory.ParseSyntaxTree(text, options: options); } [Fact] public void SimpleTuple() { var tree = UsingTree(@" class C { (int, string) Foo() { return (1, ""Alice""); } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ReturnStatement); { N(SyntaxKind.ReturnKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.StringLiteralExpression); { N(SyntaxKind.StringLiteralToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void LongTuple() { var tree = UsingTree(@" class C { (int, int, int, string, string, string, int, int, int) Foo() { } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TuplesInLambda() { var tree = UsingTree(@" class C { var x = ((string, string) a, (int, int) b) => { }; }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TuplesWithNamesInLambda() { var tree = UsingTree(@" class C { var x = ((string a, string) a, (int, int b) b) => { }; }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TupleInParameters() { var tree = UsingTree(@" class C { void Foo((int, string) a) { } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } }
using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using MusicStoreUI.Models; namespace MusicStoreUI.Controllers { [Authorize] public class ManageController : Controller { public ManageController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager) { UserManager = userManager; SignInManager = signInManager; } public UserManager<ApplicationUser> UserManager { get; } public SignInManager<ApplicationUser> SignInManager { get; } // // GET: /Manage/Index public async Task<ActionResult> Index(ManageMessageId? message = null) { ViewBag.StatusMessage = message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed." : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set." : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set." : message == ManageMessageId.Error ? "An error has occurred." : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added." : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed." : ""; var user = await GetCurrentUserAsync(); var model = new IndexViewModel { HasPassword = await UserManager.HasPasswordAsync(user), PhoneNumber = await UserManager.GetPhoneNumberAsync(user), TwoFactor = await UserManager.GetTwoFactorEnabledAsync(user), Logins = await UserManager.GetLoginsAsync(user), BrowserRemembered = await SignInManager.IsTwoFactorClientRememberedAsync(user) }; return View(model); } // // POST: /Manage/RemoveLogin [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemoveLogin(string loginProvider, string providerKey) { ManageMessageId? message = ManageMessageId.Error; var user = await GetCurrentUserAsync(); if (user != null) { var result = await UserManager.RemoveLoginAsync(user, loginProvider, providerKey); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false); message = ManageMessageId.RemoveLoginSuccess; } } return RedirectToAction("ManageLogins", new { Message = message }); } // // GET: /Account/AddPhoneNumber public IActionResult AddPhoneNumber() { return View(); } // // POST: /Account/AddPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); // Generate the token and send it var code = await UserManager.GenerateChangePhoneNumberTokenAsync(user, model.Number); await MessageServices.SendSmsAsync(model.Number, "Your security code is: " + code); return RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.Number }); } // // POST: /Manage/EnableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> EnableTwoFactorAuthentication() { var user = await GetCurrentUserAsync(); if (user != null) { await UserManager.SetTwoFactorEnabledAsync(user, true); // TODO: flow remember me somehow? await SignInManager.SignInAsync(user, isPersistent: false); } return RedirectToAction("Index", "Manage"); } // // POST: /Manage/DisableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> DisableTwoFactorAuthentication() { var user = await GetCurrentUserAsync(); if (user != null) { await UserManager.SetTwoFactorEnabledAsync(user, false); await SignInManager.SignInAsync(user, isPersistent: false); } return RedirectToAction("Index", "Manage"); } // // GET: /Account/VerifyPhoneNumber public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber) { // This code allows you exercise the flow without actually sending codes // For production use please register a SMS provider in IdentityConfig and generate a code here. #if DEMO ViewBag.Code = await UserManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber); #endif return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber }); } // // POST: /Account/VerifyPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await UserManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false); return RedirectToAction("Index", new { Message = ManageMessageId.AddPhoneSuccess }); } } // If we got this far, something failed, redisplay form ModelState.AddModelError("", "Failed to verify phone"); return View(model); } // // GET: /Account/RemovePhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemovePhoneNumber() { var user = await GetCurrentUserAsync(); if (user != null) { var result = await UserManager.SetPhoneNumberAsync(user, null); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess }); } } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } // // GET: /Manage/ChangePassword public IActionResult ChangePassword() { return View(); } // // POST: /Account/Manage [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await UserManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false); return RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess }); } AddErrors(result); return View(model); } return RedirectToAction("Index", new { Message = ManageMessageId.Error }); } // // GET: /Manage/SetPassword public IActionResult SetPassword() { return View(); } // // POST: /Manage/SetPassword [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> SetPassword(SetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await UserManager.AddPasswordAsync(user, model.NewPassword); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false); return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess }); } AddErrors(result); return View(model); } return RedirectToAction("Index", new { Message = ManageMessageId.Error }); } // // POST: /Manage/RememberBrowser [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RememberBrowser() { var user = await GetCurrentUserAsync(); if (user != null) { await SignInManager.RememberTwoFactorClientAsync(user); await SignInManager.SignInAsync(user, isPersistent: false); } return RedirectToAction("Index", "Manage"); } // // POST: /Manage/ForgetBrowser [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ForgetBrowser() { await SignInManager.ForgetTwoFactorClientAsync(); return RedirectToAction("Index", "Manage"); } // // GET: /Account/Manage public async Task<IActionResult> ManageLogins(ManageMessageId? message = null) { ViewBag.StatusMessage = message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed." : message == ManageMessageId.AddLoginSuccess ? "The external login was added." : message == ManageMessageId.Error ? "An error has occurred." : ""; var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var userLogins = await UserManager.GetLoginsAsync(user); var schemes = await SignInManager.GetExternalAuthenticationSchemesAsync(); var otherLogins = schemes.Where(auth => userLogins.All(ul => auth.Name != ul.LoginProvider)).ToList(); ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1; return View(new ManageLoginsViewModel { CurrentLogins = userLogins, OtherLogins = otherLogins }); } // // POST: /Manage/LinkLogin [HttpPost] [ValidateAntiForgeryToken] public ActionResult LinkLogin(string provider) { // Request a redirect to the external login provider to link a login for the current user var redirectUrl = Url.Action("LinkLoginCallback", "Manage"); var properties = SignInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, UserManager.GetUserId(User)); return new ChallengeResult(provider, properties); } // // GET: /Manage/LinkLoginCallback public async Task<ActionResult> LinkLoginCallback() { var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var loginInfo = await SignInManager.GetExternalLoginInfoAsync(await UserManager.GetUserIdAsync(user)); if (loginInfo == null) { return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error }); } var result = await UserManager.AddLoginAsync(user, loginInfo); var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error; return RedirectToAction("ManageLogins", new { Message = message }); } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error.Description); } } public enum ManageMessageId { AddPhoneSuccess, AddLoginSuccess, ChangePasswordSuccess, SetTwoFactorSuccess, SetPasswordSuccess, RemoveLoginSuccess, RemovePhoneSuccess, Error } private Task<ApplicationUser> GetCurrentUserAsync() { return UserManager.GetUserAsync(HttpContext.User); } #endregion } }
// // PixbufUtils.cs // // Author: // Stephane Delcroix <[email protected]> // Ruben Vermeersch <[email protected]> // // Copyright (C) 2009-2010 Novell, Inc. // Copyright (C) 2009 Stephane Delcroix // Copyright (C) 2009-2010 Ruben Vermeersch // // 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.Runtime.InteropServices; using Gdk; using Hyena; using TagLib.Image; namespace FSpot.Utils { public static class PixbufUtils { public static ImageOrientation Rotate270 (ImageOrientation orientation) { if (orientation == ImageOrientation.None) { orientation = ImageOrientation.TopLeft; } ImageOrientation [] rot = { ImageOrientation.LeftBottom, ImageOrientation.LeftTop, ImageOrientation.RightTop, ImageOrientation.RightBottom, ImageOrientation.BottomLeft, ImageOrientation.TopLeft, ImageOrientation.TopRight, ImageOrientation.BottomRight }; orientation = rot [((int)orientation) -1]; return orientation; } public static ImageOrientation Rotate90 (ImageOrientation orientation) { orientation = Rotate270 (orientation); orientation = Rotate270 (orientation); orientation = Rotate270 (orientation); return orientation; } public static Rectangle TransformOrientation (Pixbuf src, Rectangle args, ImageOrientation orientation) { return TransformOrientation (src.Width, src.Height, args, orientation); } public static Rectangle TransformOrientation (int total_width, int total_height, Rectangle args, ImageOrientation orientation) { Rectangle area = args; switch (orientation) { case ImageOrientation.BottomRight: area.X = total_width - args.X - args.Width; area.Y = total_height - args.Y - args.Height; break; case ImageOrientation.TopRight: area.X = total_width - args.X - args.Width; break; case ImageOrientation.BottomLeft: area.Y = total_height - args.Y - args.Height; break; case ImageOrientation.LeftTop: area.X = args.Y; area.Y = args.X; area.Width = args.Height; area.Height = args.Width; break; case ImageOrientation.RightBottom: area.X = total_height - args.Y - args.Height; area.Y = total_width - args.X - args.Width; area.Width = args.Height; area.Height = args.Width; break; case ImageOrientation.RightTop: area.X = total_height - args.Y - args.Height; area.Y = args.X; area.Width = args.Height; area.Height = args.Width; break; case ImageOrientation.LeftBottom: area.X = args.Y; area.Y = total_width - args.X - args.Width; area.Width = args.Height; area.Height = args.Width; break; default: break; } return area; } public static Point TransformOrientation (int total_width, int total_height, Point args, ImageOrientation orientation) { Point p = args; switch (orientation) { default: case ImageOrientation.TopLeft: break; case ImageOrientation.TopRight: p.X = total_width - p.X; break; case ImageOrientation.BottomRight: p.X = total_width - p.X; p.Y = total_height - p.Y; break; case ImageOrientation.BottomLeft: p.Y = total_height - p.Y; break; case ImageOrientation.LeftTop: p.X = args.Y; p.Y = args.X; break; case ImageOrientation.RightTop: p.X = total_height - args.Y; p.Y = args.X; break; case ImageOrientation.RightBottom: p.X = total_height - args.Y; p.Y = total_width - args.X; break; case ImageOrientation.LeftBottom: p.X = args.Y; p.Y = total_width - args.X; break; } return p; } public static ImageOrientation ReverseTransformation (ImageOrientation orientation) { switch (orientation) { default: case ImageOrientation.TopLeft: case ImageOrientation.TopRight: case ImageOrientation.BottomRight: case ImageOrientation.BottomLeft: return orientation; case ImageOrientation.LeftTop: return ImageOrientation.RightBottom; case ImageOrientation.RightTop: return ImageOrientation.LeftBottom; case ImageOrientation.RightBottom: return ImageOrientation.LeftTop; case ImageOrientation.LeftBottom: return ImageOrientation.RightTop; } } public static Pixbuf TransformOrientation (this Pixbuf src, ImageOrientation orientation) { Pixbuf dest; switch (orientation) { default: case ImageOrientation.TopLeft: dest = src.ShallowCopy (); break; case ImageOrientation.TopRight: dest = src.Flip (false); break; case ImageOrientation.BottomRight: dest = src.RotateSimple (PixbufRotation.Upsidedown); break; case ImageOrientation.BottomLeft: dest = src.Flip (true); break; case ImageOrientation.LeftTop: using (var rotated = src.RotateSimple (PixbufRotation.Clockwise)) { dest = rotated.Flip (false); } break; case ImageOrientation.RightTop: dest = src.RotateSimple (PixbufRotation.Clockwise); break; case ImageOrientation.RightBottom: using (var rotated = src.RotateSimple (PixbufRotation.Counterclockwise)) { dest = rotated.Flip (false); } break; case ImageOrientation.LeftBottom: dest = src.RotateSimple (PixbufRotation.Counterclockwise); break; } return dest; } public static Pixbuf ShallowCopy (this Pixbuf pixbuf) { if (pixbuf == null) return null; var result = new Pixbuf (pixbuf, 0, 0, pixbuf.Width, pixbuf.Height); return result; } public static Pixbuf ScaleToMaxSize (this Pixbuf pixbuf, int width, int height, bool upscale = true) { int scale_width = 0; int scale_height = 0; double scale = Fit (pixbuf, width, height, upscale, out scale_width, out scale_height); Gdk.Pixbuf result; if (upscale || (scale < 1.0)) result = pixbuf.ScaleSimple (scale_width, scale_height, (scale_width > 20) ? Gdk.InterpType.Bilinear : Gdk.InterpType.Nearest); else result = pixbuf.Copy (); return result; } public static double Fit (Pixbuf pixbuf, int dest_width, int dest_height, bool upscale_smaller, out int fit_width, out int fit_height) { return Fit (pixbuf.Width, pixbuf.Height, dest_width, dest_height, upscale_smaller, out fit_width, out fit_height); } public static double Fit (int orig_width, int orig_height, int dest_width, int dest_height, bool upscale_smaller, out int fit_width, out int fit_height) { if (orig_width == 0 || orig_height == 0) { fit_width = 0; fit_height = 0; return 0.0; } double scale = Math.Min (dest_width / (double)orig_width, dest_height / (double)orig_height); if (scale > 1.0 && !upscale_smaller) scale = 1.0; fit_width = (int)Math.Round (scale * orig_width); fit_height = (int)Math.Round (scale * orig_height); return scale; } public static void CreateDerivedVersion (SafeUri source, SafeUri destination, uint jpeg_quality, Pixbuf pixbuf) { SaveToSuitableFormat (destination, pixbuf, jpeg_quality); using var metadata_from = MetadataUtils.Parse (source); using var metadata_to = MetadataUtils.Parse (destination); metadata_to.CopyFrom (metadata_from); // Reset orientation to make sure images appear upright. metadata_to.ImageTag.Orientation = ImageOrientation.TopLeft; metadata_to.Save (); } static void SaveToSuitableFormat (SafeUri destination, Pixbuf pixbuf, uint jpeg_quality) { // FIXME: this needs to work on streams rather than filenames. Do that when we switch to // newer GDK. var extension = destination.GetExtension ().ToLower (); if (extension == ".png") pixbuf.Save (destination.LocalPath, "png"); else if (extension == ".jpg" || extension == ".jpeg") pixbuf.Save (destination.LocalPath, "jpeg", jpeg_quality); else throw new NotImplementedException ("Saving this file format is not supported"); } #region Gdk hackery // This hack below is needed because there is no wrapped version of // Save which allows specifying the variable arguments (it's not // possible with p/invoke). [DllImport("libgdk_pixbuf-2.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern bool gdk_pixbuf_save (IntPtr raw, IntPtr filename, IntPtr type, out IntPtr error, IntPtr optlabel1, IntPtr optvalue1, IntPtr dummy); static bool Save (this Pixbuf pixbuf, string filename, string type, uint jpeg_quality) { IntPtr error = IntPtr.Zero; IntPtr nfilename = GLib.Marshaller.StringToPtrGStrdup (filename); IntPtr ntype = GLib.Marshaller.StringToPtrGStrdup (type); IntPtr optlabel1 = GLib.Marshaller.StringToPtrGStrdup ("quality"); IntPtr optvalue1 = GLib.Marshaller.StringToPtrGStrdup (jpeg_quality.ToString ()); bool ret = gdk_pixbuf_save (pixbuf.Handle, nfilename, ntype, out error, optlabel1, optvalue1, IntPtr.Zero); GLib.Marshaller.Free (nfilename); GLib.Marshaller.Free (ntype); GLib.Marshaller.Free (optlabel1); GLib.Marshaller.Free (optvalue1); if (error != IntPtr.Zero) throw new GLib.GException (error); return ret; } #endregion } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System.Collections.Generic; using Glass.Mapper.Pipelines.DataMapperResolver; using Glass.Mapper.Sc.Configuration; using Glass.Mapper.Sc.DataMappers; using NUnit.Framework; using Sitecore.Data; using Sitecore.FakeDb; using Sitecore.Rules; using Sitecore.Rules.InsertOptions; namespace Glass.Mapper.Sc.FakeDb.DataMappers { public class SitecoreFieldRulesMapperFixture { #region Method - CanHandle [Test] public void CanHandle_TypeIsRulesList_ReturnsTrue() { //Assign var mapper = new SitecoreFieldRulesMapper(); var config = new SitecoreFieldConfiguration(); var context = (Context)null; config.PropertyInfo = typeof (StubClass).GetProperty("Property"); //Act var result = mapper.CanHandle(config, context); //Assert Assert.IsTrue(result); } [Test] public void CanHandle_TypeIsNotRulesList_ReturnsFalse() { //Assign var mapper = new SitecoreFieldRulesMapper(); var config = new SitecoreFieldConfiguration(); var context = (Context)null; config.PropertyInfo = typeof(StubClass).GetProperty("PropertyInt"); //Act var result = mapper.CanHandle(config, context); //Assert Assert.IsFalse(result); } [Test] public void CanHandle_GenericTypeIsNotRulesList_ReturnsFalse() { //Assign var mapper = new SitecoreFieldRulesMapper(); var config = new SitecoreFieldConfiguration(); var context = (Context)null; config.PropertyInfo = typeof(StubClass).GetProperty("PropertyIntEnum"); //Act var result = mapper.CanHandle(config, context); //Assert Assert.IsFalse(result); } #endregion #region Method - GetField [Test] public void GetField_FieldContains2Rules_RulesListContains2Rules() { //Assign var templateId = ID.NewID; var targetId = ID.NewID; var fieldName = "Field"; using (Db database = new Db { new DbTemplate(templateId) { {fieldName, ""} }, new Sitecore.FakeDb.DbItem("Target", targetId, templateId), }) { var fieldValue = "<ruleset> <rule uid=\"{A7FC7A4F-72C0-4FBE-B1C7-759E139848E0}\"> <conditions> <condition id=\"{4F5389E9-79B7-4FE1-A43A-EEA4ECD19C94}\" uid=\"6B54B8B6B128471696870047DD93DDED\" operatorid=\"{10537C58-1684-4CAB-B4C0-40C10907CE31}\" value=\"10\" /> </conditions> </rule> <rule uid=\"{22BA1F43-9F29-46ED-83AF-151471297AF6}\"> <conditions> <condition id=\"{DA0D1AEA-0144-4A40-9AF0-3123526C9163}\" uid=\"51CC5EC564494B68B9391C6B7A64A796\" fieldname=\"Test\" /> </conditions> <actions> <action id=\"{94C5C335-0902-4B45-B528-11B220005DD7}\" uid=\"7833EA2A3E75401AAE8B295067112DCC\" /> </actions> </rule></ruleset>"; var item = database.GetItem("/sitecore/content/Target"); var field = item.Fields[fieldName]; var mapper = new SitecoreFieldRulesMapper(); var config = new SitecoreFieldConfiguration(); var context = (Context) null; config.PropertyInfo = typeof(StubClass).GetProperty("Property"); mapper.Setup(new DataMapperResolverArgs(context, config)); using (new ItemEditing(item, true)) { field.Value = fieldValue; } //Act var result = mapper.GetField(field, null, null) as RuleList<StubRuleContext>; //Assert Assert.AreEqual(2, result.Count); } } [Test] public void GetField_FieldIsEmpty_RulesListContains0Rules() { //Assign var templateId = ID.NewID; var targetId = ID.NewID; var fieldName = "Field"; using (Db database = new Db { new DbTemplate(templateId) { {fieldName, ""} }, new Sitecore.FakeDb.DbItem("Target", targetId, templateId), }) { var fieldValue = ""; var item = database.GetItem("/sitecore/content/Target"); var field = item.Fields[fieldName]; var mapper = new SitecoreFieldRulesMapper(); var config = new SitecoreFieldConfiguration(); var context = (Context) null; config.PropertyInfo = typeof(StubClass).GetProperty("Property"); mapper.Setup(new DataMapperResolverArgs(context, config)); using (new ItemEditing(item, true)) { field.Value = fieldValue; } //Act var result = mapper.GetField(field, null, null) as RuleList<StubRuleContext>; //Assert Assert.AreEqual(0, result.Count); } } #endregion #region Stubs public class StubClass { public RuleList<StubRuleContext> Property { get; set; } public int PropertyInt { get; set; } public IEnumerable<int> PropertyIntEnum { get; set; } } public class StubRuleContext : InsertOptionsRuleContext { } #endregion } }
namespace NEventStore.Persistence.InMemory { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using NEventStore.Logging; using NEventStore.Persistence.Sql; using NEventStore.Serialization; public class InMemoryPersistenceEngine : IPersistStreams { private static readonly ILog Logger = LogFactory.BuildLogger(typeof (InMemoryPersistenceEngine)); private readonly ConcurrentDictionary<string, Bucket> _buckets = new ConcurrentDictionary<string, Bucket>(); private bool _disposed; private int _checkpoint; private Bucket this[string bucketId] { get { return _buckets.GetOrAdd(bucketId, _ => new Bucket()); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void Initialize() { Logger.Info(Resources.InitializingEngine); } public IEnumerable<ICommit> GetFrom(string bucketId, string streamId, int minRevision, int maxRevision) { ThrowWhenDisposed(); Logger.Debug(Resources.GettingAllCommitsFromRevision, streamId, minRevision, maxRevision); return this[bucketId].GetFrom(streamId, minRevision, maxRevision); } public IEnumerable<ICommit> GetFrom(string bucketId, DateTime start) { ThrowWhenDisposed(); Logger.Debug(Resources.GettingAllCommitsFromTime, bucketId, start); return this[bucketId].GetFrom(start); } public IEnumerable<ICommit> GetStreams(string bucketId, params string[] streamIds) { throw new NotImplementedException(); } public IEnumerable<ICommit> GetAggregatesStreams(string bucketId, string streamIdOriginal) { throw new NotImplementedException(); } public IEnumerable<ICommit> GetFrom(string checkpointToken) { Logger.Debug(Resources.GettingAllCommitsFromCheckpoint, checkpointToken); ICheckpoint checkpoint = LongCheckpoint.Parse(checkpointToken); return _buckets .Values .SelectMany(b => b.GetCommits()) .Where(c => c.Checkpoint.CompareTo(checkpoint) > 0) .OrderBy(c => c.Checkpoint) .ToArray(); } public ICheckpoint GetCheckpoint(string checkpointToken = null) { return LongCheckpoint.Parse(checkpointToken); } public IEnumerable<ICommit> GetFromTo(string bucketId, DateTime start, DateTime end) { ThrowWhenDisposed(); Logger.Debug(Resources.GettingAllCommitsFromToTime, start, end); return this[bucketId].GetFromTo(start, end); } public ICommit Commit(CommitAttempt attempt) { ThrowWhenDisposed(); Logger.Debug(Resources.AttemptingToCommit, attempt.CommitId, attempt.StreamId, attempt.CommitSequence); return this[attempt.BucketId].Commit(attempt, new LongCheckpoint(Interlocked.Increment(ref _checkpoint))); } public IEnumerable<ICommit> GetUndispatchedCommits() { ThrowWhenDisposed(); return _buckets.Values.SelectMany(b => b.GetUndispatchedCommits()); } public void MarkCommitAsDispatched(ICommit commit) { ThrowWhenDisposed(); Logger.Debug(Resources.MarkingAsDispatched, commit.CommitId); this[commit.BucketId].MarkCommitAsDispatched(commit); } public IEnumerable<IStreamHead> GetStreamsToSnapshot(string bucketId, int maxThreshold) { ThrowWhenDisposed(); Logger.Debug(Resources.GettingStreamsToSnapshot, bucketId, maxThreshold); return this[bucketId].GetStreamsToSnapshot(maxThreshold); } public ISnapshot GetSnapshot(string bucketId, string streamId, int maxRevision) { ThrowWhenDisposed(); Logger.Debug(Resources.GettingSnapshotForStream, bucketId, streamId, maxRevision); return this[bucketId].GetSnapshot(streamId, maxRevision); } public bool AddSnapshot(ISnapshot snapshot) { ThrowWhenDisposed(); Logger.Debug(Resources.AddingSnapshot, snapshot.StreamId, snapshot.StreamRevision); return this[snapshot.BucketId].AddSnapshot(snapshot); } public void Purge() { ThrowWhenDisposed(); Logger.Warn(Resources.PurgingStore); foreach (var bucket in _buckets.Values) { bucket.Purge(); } } public void Purge(string bucketId) { Bucket _; _buckets.TryRemove(bucketId, out _); } public void Drop() { _buckets.Clear(); } public void DeleteStream(string bucketId, string streamId) { Logger.Warn(Resources.DeletingStream, streamId, bucketId); Bucket bucket; if (!_buckets.TryGetValue(bucketId, out bucket)) { return; } bucket.DeleteStream(streamId); } public bool SafeDeleteStream(string bucketId, string streamId, int itemCount) { throw new NotImplementedException(); } public void DeleteStreams(string bucketId, List<string> streamIds) { Logger.Warn(Resources.DeletingStream, streamIds, bucketId); Bucket bucket; if (!_buckets.TryGetValue(bucketId, out bucket)) { return; } bucket.DeleteStreams(streamIds); } public IStreamIdHasher GetStreamIdHasher() { throw new NotImplementedException(); } public ISerialize GetSerializer() { throw new NotImplementedException(); } public bool IsDisposed { get { return _disposed; } } private void Dispose(bool disposing) { _disposed = true; Logger.Info(Resources.DisposingEngine); } private void ThrowWhenDisposed() { if (!_disposed) { return; } Logger.Warn(Resources.AlreadyDisposed); throw new ObjectDisposedException(Resources.AlreadyDisposed); } private class InMemoryCommit : Commit { private readonly ICheckpoint _checkpoint; public InMemoryCommit( string bucketId, string streamId, int streamRevision, Guid commitId, int commitSequence, DateTime commitStamp, string checkpointToken, IDictionary<string, object> headers, IEnumerable<EventMessage> events, ICheckpoint checkpoint) : base(bucketId, streamId, streamRevision, commitId, commitSequence, commitStamp, checkpointToken, headers, events) { _checkpoint = checkpoint; } public ICheckpoint Checkpoint { get { return _checkpoint; } } } private class IdentityForDuplicationDetection { protected bool Equals(IdentityForDuplicationDetection other) { return string.Equals(this.streamId, other.streamId) && string.Equals(this.bucketId, other.bucketId) && this.commitSequence == other.commitSequence && this.commitId.Equals(other.commitId); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != this.GetType()) { return false; } return Equals((IdentityForDuplicationDetection)obj); } public override int GetHashCode() { unchecked { int hashCode = this.streamId.GetHashCode(); hashCode = (hashCode * 397) ^ this.bucketId.GetHashCode(); hashCode = (hashCode * 397) ^ this.commitSequence; hashCode = (hashCode * 397) ^ this.commitId.GetHashCode(); return hashCode; } } private int commitSequence; private Guid commitId; private string bucketId; private string streamId; public IdentityForDuplicationDetection(CommitAttempt commitAttempt) { bucketId = commitAttempt.BucketId; streamId = commitAttempt.StreamId; commitId = commitAttempt.CommitId; commitSequence = commitAttempt.CommitSequence; } public IdentityForDuplicationDetection(Commit commit) { bucketId = commit.BucketId; streamId = commit.StreamId; commitId = commit.CommitId; commitSequence = commit.CommitSequence; } } private class IdentityForConcurrencyConflictDetection { protected bool Equals(IdentityForConcurrencyConflictDetection other) { return this.commitSequence == other.commitSequence && string.Equals(this.streamId, other.streamId); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != this.GetType()) { return false; } return Equals((IdentityForConcurrencyConflictDetection)obj); } public override int GetHashCode() { unchecked { return (this.commitSequence * 397) ^ this.streamId.GetHashCode(); } } private int commitSequence; private string streamId; public IdentityForConcurrencyConflictDetection(Commit commit) { streamId = commit.StreamId; commitSequence = commit.CommitSequence; } } private class Bucket { private readonly IList<InMemoryCommit> _commits = new List<InMemoryCommit>(); private readonly ICollection<IdentityForDuplicationDetection> _potentialDuplicates = new HashSet<IdentityForDuplicationDetection>(); private readonly ICollection<IdentityForConcurrencyConflictDetection> _potentialConflicts = new HashSet<IdentityForConcurrencyConflictDetection>(); public IEnumerable<InMemoryCommit> GetCommits() { lock (_commits) { return _commits.ToArray(); } } private readonly ICollection<IStreamHead> _heads = new LinkedList<IStreamHead>(); private readonly ICollection<ISnapshot> _snapshots = new LinkedList<ISnapshot>(); private readonly IDictionary<Guid, DateTime> _stamps = new Dictionary<Guid, DateTime>(); private readonly ICollection<ICommit> _undispatched = new LinkedList<ICommit>(); public IEnumerable<ICommit> GetFrom(string streamId, int minRevision, int maxRevision) { lock (_commits) { return _commits .Where(x => x.StreamId == streamId && x.StreamRevision >= minRevision && (x.StreamRevision - x.Events.Count + 1) <= maxRevision) .OrderBy(c => c.CommitSequence) .ToArray(); } } public IEnumerable<ICommit> GetFrom(DateTime start) { Guid commitId = _stamps.Where(x => x.Value >= start).Select(x => x.Key).FirstOrDefault(); if (commitId == Guid.Empty) { return Enumerable.Empty<ICommit>(); } InMemoryCommit startingCommit = _commits.FirstOrDefault(x => x.CommitId == commitId); return _commits.Skip(_commits.IndexOf(startingCommit)); } public IEnumerable<ICommit> GetFromTo(DateTime start, DateTime end) { IEnumerable<Guid> selectedCommitIds = _stamps.Where(x => x.Value >= start && x.Value < end).Select(x => x.Key).ToArray(); Guid firstCommitId = selectedCommitIds.FirstOrDefault(); Guid lastCommitId = selectedCommitIds.LastOrDefault(); if (lastCommitId == Guid.Empty && lastCommitId == Guid.Empty) { return Enumerable.Empty<ICommit>(); } InMemoryCommit startingCommit = _commits.FirstOrDefault(x => x.CommitId == firstCommitId); InMemoryCommit endingCommit = _commits.FirstOrDefault(x => x.CommitId == lastCommitId); int startingCommitIndex = (startingCommit == null) ? 0 : _commits.IndexOf(startingCommit); int endingCommitIndex = (endingCommit == null) ? _commits.Count - 1 : _commits.IndexOf(endingCommit); int numberToTake = endingCommitIndex - startingCommitIndex + 1; return _commits.Skip(_commits.IndexOf(startingCommit)).Take(numberToTake); } public ICommit Commit(CommitAttempt attempt, ICheckpoint checkpoint) { lock (_commits) { DetectDuplicate(attempt); var commit = new InMemoryCommit(attempt.BucketId, attempt.StreamId, attempt.StreamRevision, attempt.CommitId, attempt.CommitSequence, attempt.CommitStamp, checkpoint.Value, attempt.Headers, attempt.Events, checkpoint); if (_potentialConflicts.Contains(new IdentityForConcurrencyConflictDetection(commit))) { throw new ConcurrencyException(); } _stamps[commit.CommitId] = commit.CommitStamp; _commits.Add(commit); _potentialDuplicates.Add(new IdentityForDuplicationDetection(commit)); _potentialConflicts.Add(new IdentityForConcurrencyConflictDetection(commit)); _undispatched.Add(commit); IStreamHead head = _heads.FirstOrDefault(x => x.StreamId == commit.StreamId); _heads.Remove(head); Logger.Debug(Resources.UpdatingStreamHead, commit.StreamId); int snapshotRevision = head == null ? 0 : head.SnapshotRevision; _heads.Add(new StreamHead(commit.BucketId, commit.StreamId, commit.StreamRevision, snapshotRevision)); return commit; } } private void DetectDuplicate(CommitAttempt attempt) { if (_potentialDuplicates.Contains(new IdentityForDuplicationDetection(attempt))) { throw new DuplicateCommitException(); } } public IEnumerable<ICommit> GetUndispatchedCommits() { lock (_commits) { Logger.Debug(Resources.RetrievingUndispatchedCommits, _commits.Count); return _commits.Where(c => _undispatched.Contains(c)).OrderBy(c => c.CommitSequence); } } public void MarkCommitAsDispatched(ICommit commit) { lock (_commits) { _undispatched.Remove(commit); } } public IEnumerable<IStreamHead> GetStreamsToSnapshot(int maxThreshold) { lock (_commits) { return _heads .Where(x => x.HeadRevision >= x.SnapshotRevision + maxThreshold) .Select(stream => new StreamHead(stream.BucketId, stream.StreamId, stream.HeadRevision, stream.SnapshotRevision)); } } public ISnapshot GetSnapshot(string streamId, int maxRevision) { lock (_commits) { return _snapshots .Where(x => x.StreamId == streamId && x.StreamRevision <= maxRevision) .OrderByDescending(x => x.StreamRevision) .FirstOrDefault(); } } public bool AddSnapshot(ISnapshot snapshot) { lock (_commits) { IStreamHead currentHead = _heads.FirstOrDefault(h => h.StreamId == snapshot.StreamId); if (currentHead == null) { return false; } _snapshots.Add(snapshot); _heads.Remove(currentHead); _heads.Add(new StreamHead(currentHead.BucketId, currentHead.StreamId, currentHead.HeadRevision, snapshot.StreamRevision)); } return true; } public void Purge() { lock (_commits) { _commits.Clear(); _snapshots.Clear(); _heads.Clear(); _potentialConflicts.Clear(); _potentialDuplicates.Clear(); } } public void DeleteStream(string streamId) { lock (_commits) { InMemoryCommit[] commits = _commits.Where(c => c.StreamId == streamId).ToArray(); foreach (var commit in commits) { _commits.Remove(commit); } ISnapshot[] snapshots = _snapshots.Where(s => s.StreamId == streamId).ToArray(); foreach (var snapshot in snapshots) { _snapshots.Remove(snapshot); } IStreamHead streamHead = _heads.SingleOrDefault(s => s.StreamId == streamId); if (streamHead != null) { _heads.Remove(streamHead); } } } public void DeleteStreams(List<string> streamIds) { lock (_commits) { InMemoryCommit[] commits = _commits.Where(c => streamIds.Contains(c.StreamId)).ToArray(); foreach (var commit in commits) { _commits.Remove(commit); } ISnapshot[] snapshots = _snapshots.Where(s => streamIds.Contains(s.StreamId)).ToArray(); foreach (var snapshot in snapshots) { _snapshots.Remove(snapshot); } IStreamHead[] streamHeads = _heads.Where(s => streamIds.Contains(s.StreamId)).ToArray(); foreach (var streamHead in streamHeads) { _heads.Remove(streamHead); } } } } } }
using System; using NUnit.Framework; using NFluent; namespace FileHelpers.Tests.CommonTests { [TestFixture] public class FieldValueDiscarded { [Test] public void DiscardFirst() { var res = (CustomersTabDiscardedFirst[]) FileTest.Good.CustomersTab.ReadWithEngine<CustomersTabDiscardedFirst>(); Check.That(res.Length).IsEqualTo(Array.FindAll(res, (x) => x.CustomerID == null).Length); } [Test] public void DiscardSecond() { var res = (CustomersTabDiscardedSecond[]) FileTest.Good.CustomersTab.ReadWithEngine<CustomersTabDiscardedSecond>(); Check.That(res.Length).IsEqualTo(Array.FindAll(res, (x) => x.CompanyName == null).Length); } [Test] public void DiscardMiddle() { var res = (CustomersTabDiscardedMiddle[]) FileTest.Good.CustomersTab.ReadWithEngine<CustomersTabDiscardedMiddle>(); Check.That(res.Length).IsEqualTo(Array.FindAll(res, (x) => x.Address == null).Length); } [Test] public void DiscardLast() { var res = (CustomersTabDiscardedLast[]) FileTest.Good.CustomersTab.ReadWithEngine<CustomersTabDiscardedLast>(); Check.That(res.Length).IsEqualTo(Array.FindAll(res, (x) => x.Country == null).Length); } [DelimitedRecord("\t")] public class CustomersTabDiscardedFirst { [FieldValueDiscarded] public string CustomerID; public string CompanyName; public string ContactName; public string ContactTitle; public string Address; public string City; public string Country; } [DelimitedRecord("\t")] public class CustomersTabDiscardedSecond { public string CustomerID; [FieldValueDiscarded] public string CompanyName; public string ContactName; public string ContactTitle; public string Address; public string City; public string Country; } [DelimitedRecord("\t")] public class CustomersTabDiscardedMiddle { public string CustomerID; public string CompanyName; public string ContactName; public string ContactTitle; [FieldValueDiscarded] public string Address; public string City; public string Country; } [DelimitedRecord("\t")] public class CustomersTabDiscardedLast { public string CustomerID; public string CompanyName; public string ContactName; public string ContactTitle; public string Address; public string City; [FieldValueDiscarded] public string Country; } [Test] public void DiscardedBad() { Assert.Throws<BadUsageException>(() => FileTest.Good.OrdersSmallVerticalBar .ReadWithEngine<OrdersDiscardBad>()); } [Test] public void OrdersAllDiscarded() { var res = (OrdersAllDiscard[]) FileTest.Good.OrdersSmallVerticalBar .ReadWithEngine<OrdersAllDiscard>(); Check.That(Array.FindAll(res, (x) => x.CustomerID == null && x.OrderID == -1 && x.OrderDate == new DateTime(2000, 1, 2) && x.Freight == 0).Length).IsEqualTo(res.Length); } [Test] public void OrdersLastNotDiscarded() { var res = (OrdersLastNotDiscard[]) FileTest.Good.OrdersSmallVerticalBar .ReadWithEngine<OrdersLastNotDiscard>(); Check.That(Array.FindAll(res, (x) => x.CustomerID == null && x.OrderID == -1 && x.OrderDate == new DateTime(2000, 1, 2) && x.Freight != 0).Length).IsEqualTo(res.Length); } [Test] public void OrdersLastTwoNotDiscarded() { var res = (OrdersLastTwoNotDiscard[]) FileTest.Good.OrdersSmallVerticalBar .ReadWithEngine<OrdersLastTwoNotDiscard>(); Check.That(Array.FindAll(res, (x) => x.CustomerID == null && x.OrderID == -1 && x.OrderDate != new DateTime(2000, 1, 2) && x.Freight != 0).Length).IsEqualTo(res.Length); } [DelimitedRecord("|")] public class OrdersDiscardBad { [FieldValueDiscarded] public int OrderID; public string CustomerID; [FieldConverter(ConverterKind.Date, "ddMMyyyy")] public DateTime OrderDate; public decimal Freight; } [DelimitedRecord("|")] public class OrdersAllDiscard { [FieldValueDiscarded] [FieldNullValue(-1)] public int OrderID; [FieldValueDiscarded] public string CustomerID; [FieldConverter(ConverterKind.Date, "ddMMyyyy")] [FieldValueDiscarded] [FieldNullValue(typeof (DateTime), "2000-01-02")] public DateTime OrderDate; [FieldValueDiscarded] [FieldNullValue(typeof (decimal), "0")] public decimal Freight; } [DelimitedRecord("|")] public class OrdersLastNotDiscard { [FieldValueDiscarded] [FieldNullValue(-1)] public int OrderID; [FieldValueDiscarded] public string CustomerID; [FieldConverter(ConverterKind.Date, "ddMMyyyy")] [FieldValueDiscarded] [FieldNullValue(typeof (DateTime), "2000-01-02")] public DateTime OrderDate; public decimal Freight; } [DelimitedRecord("|")] public class OrdersLastTwoNotDiscard { [FieldValueDiscarded] [FieldNullValue(-1)] public int OrderID; [FieldValueDiscarded] public string CustomerID; [FieldConverter(ConverterKind.Date, "ddMMyyyy")] public DateTime OrderDate; public decimal Freight; } } }
// Copyright 2015-2016 Google Inc. All Rights Reserved. // Licensed under the Apache License Version 2.0. using Google.Apis.Logging.v2; using Google.Apis.Logging.v2.Data; using Google.PowerShell.Common; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Management.Automation; using System.Net; using System.Xml; namespace Google.PowerShell.Logging { /// <summary> /// Base class for Stackdriver Logging cmdlets. /// </summary> public class GcLogCmdlet : GCloudCmdlet { /// <summary> /// Enum of severity levels for a log entry. /// </summary> public enum LogSeverity { /// <summary> /// The log entry has no assigned severity level. /// </summary> Default, /// <summary> /// Debug or trace information. /// </summary> Debug, /// <summary> /// Routine information, such as ongoing status or performance. /// </summary> Info, /// <summary> /// Normal but significant events, such as start up, shut down, or a configuration change. /// </summary> Notice, /// <summary> /// Warning events might cause problems. /// </summary> Warning, /// <summary> /// Error events are likely to cause problems. /// </summary> Error, /// <summary> /// Critical events cause more severe problems or outages. /// </summary> Critical, /// <summary> /// A person must take an action immediately. /// </summary> Alert, /// <summary> /// One or more systems are unusable. /// </summary> Emergency } public LoggingService Service { get; private set; } public GcLogCmdlet() { Service = new LoggingService(GetBaseClientServiceInitializer()); } /// <summary> /// Prefix projects/{project id}/logs to logName if not present. /// </summary> protected string PrefixProjectToLogName(string logName, string project) { if (!string.IsNullOrWhiteSpace(logName) && !logName.StartsWith($"projects/{project}/logs")) { logName = $"projects/{project}/logs/{logName}"; } return logName; } /// <summary> /// Prefix projects/{project id}/sinks to sinkName if not present. /// </summary> protected string PrefixProjectToSinkName(string sinkName, string project) { if (!string.IsNullOrWhiteSpace(sinkName) && !sinkName.StartsWith($"projects/{project}/sinks")) { sinkName = $"projects/{project}/sinks/{sinkName}"; } return sinkName; } /// <summary> /// Prefix projects/{project id}/metrics to metricName if not present. /// </summary> protected string PrefixProjectToMetricName(string metricName, string project) { if (!string.IsNullOrWhiteSpace(metricName) && !metricName.StartsWith($"projects/{project}/metrics")) { metricName = $"projects/{project}/metrics/{metricName}"; } return metricName; } /// <summary> /// A cache of the list of valid monitored resource descriptors. /// This is used for auto-completion to display possible types of monitored resource. /// </summary> private static Lazy<List<MonitoredResourceDescriptor>> s_monitoredResourceDescriptors = new Lazy<List<MonitoredResourceDescriptor>>(GetResourceDescriptors); /// <summary> /// Gets all possible monitored resource descriptors. /// </summary> private static List<MonitoredResourceDescriptor> GetResourceDescriptors() { List<MonitoredResourceDescriptor> monitoredResourceDescriptors = new List<MonitoredResourceDescriptor>(); LoggingService service = new LoggingService(GetBaseClientServiceInitializer()); MonitoredResourceDescriptorsResource.ListRequest request = service.MonitoredResourceDescriptors.List(); do { ListMonitoredResourceDescriptorsResponse response = request.Execute(); if (response.ResourceDescriptors != null) { monitoredResourceDescriptors.AddRange(response.ResourceDescriptors); } request.PageToken = response.NextPageToken; } while (request.PageToken != null); return monitoredResourceDescriptors; } /// <summary> /// Returns a monitored resource descriptor based on a given type. /// </summary> protected MonitoredResourceDescriptor GetResourceDescriptor(string descriptorType) { return s_monitoredResourceDescriptors.Value.First( descriptor => string.Equals(descriptor.Type.ToLower(), descriptorType.ToLower())); } /// <summary> /// Returns all valid resource types. /// </summary> protected string[] AllResourceTypes => s_monitoredResourceDescriptors.Value.Select(descriptor => descriptor.Type).ToArray(); /// <summary> /// Generate -ResourceType dynamic parameter. Cmdlets can use this parameter to filter log entries based on resource types /// such as "gce_instance". For a full list of resource types, see https://cloud.google.com/logging/docs/api/v2/resource-list /// </summary> protected RuntimeDefinedParameter GenerateResourceTypeParameter(bool mandatory) { return GenerateRuntimeParameter( parameterName: "ResourceType", helpMessage: "If specified, the cmdlet will filter out log entries based on the resource type.", validSet: AllResourceTypes, isMandatory: mandatory); } /// <summary> /// Constructs a filter string based on log name, severity, type of log, before and after timestamps /// and other advanced filter. /// </summary> protected string ConstructLogFilterString(string logName, LogSeverity? logSeverity, string selectedType, DateTime? before, DateTime? after, string otherFilter) { string andOp = " AND "; string filterString = ""; if (!string.IsNullOrWhiteSpace(logName)) { // By setting logName = LogName in the filter, the list request // will only return log entry that belongs to LogName. // Example: logName = "Name of log". filterString = $"logName = '{logName}'{andOp}".Replace('\'', '"'); } if (logSeverity.HasValue) { // Example: severity >= ERROR. string severityString = Enum.GetName(typeof(LogSeverity), logSeverity.Value).ToUpper(); filterString += $"severity = {severityString}{andOp}"; } if (selectedType != null) { // Example: resource.type = "gce_instance". filterString += $"resource.type = '{selectedType}'{andOp}".Replace('\'', '"'); } if (before.HasValue) { // Example: timestamp <= "2016-06-27T14:40:00-04:00". string beforeTimestamp = XmlConvert.ToString(before.Value, XmlDateTimeSerializationMode.Local); filterString += $"timestamp <= '{beforeTimestamp}'{andOp}".Replace('\'', '"'); } if (after.HasValue) { // Example: timestamp >= "2016-06-27T14:40:00-04:00". string afterTimestamp = XmlConvert.ToString(after.Value, XmlDateTimeSerializationMode.Local); filterString += $"timestamp >= '{afterTimestamp}'{andOp}".Replace('\'', '"'); } if (otherFilter != null) { filterString += otherFilter; } // Strip the "AND " at the end if we have it. if (filterString.EndsWith(andOp)) { filterString = filterString.Substring(0, filterString.Length - andOp.Length); } return filterString; } } /// <summary> /// Base class for GcLog cmdlet that uses log filter. /// </summary> public class GcLogEntryCmdletWithLogFilter : GcLogCmdlet, IDynamicParameters { /// <summary> /// <para type="description"> /// If specified, the cmdlet will filter out log entries that are in the log LogName. /// </para> /// </summary> [Parameter(Mandatory = false)] public string LogName { get; set; } /// <summary> /// <para type="description"> /// If specified, the cmdlet will filter out log entries with the specified severity. /// </para> /// </summary> [Parameter(Mandatory = false)] public LogSeverity? Severity { get; set; } /// <summary> /// <para type="description"> /// If specified, the cmdlet will filter out log entries that occur before this datetime. /// </para> /// </summary> [Parameter(Mandatory = false)] public DateTime? Before { get; set; } /// <summary> /// <para type="description"> /// If specified, the cmdlet will filter out log entries that occur after this datetime. /// </para> /// </summary> [Parameter(Mandatory = false)] public DateTime? After { get; set; } /// <summary> /// <para type="description"> /// If specified, the cmdlet will filter out log entries that satisfy the filter. /// </para> /// </summary> [Parameter(Mandatory = false)] [ValidateNotNullOrEmpty] public string Filter { get; set; } /// <summary> /// This dynamic parameter dictionary is used by PowerShell to generate parameters dynamically. /// </summary> private RuntimeDefinedParameterDictionary _dynamicParameters; /// <summary> /// This function is part of the IDynamicParameters interface. /// PowerShell uses it to generate parameters dynamically. /// We have to generate -ResourceType parameter dynamically because the array /// of resources that we used to validate against are not generated before compile time, /// i.e. [ValidateSet(ArrayGeneratedAtRunTime)] will throw an error for parameters /// that are not generated dynamically. /// </summary> public object GetDynamicParameters() { if (_dynamicParameters == null) { _dynamicParameters = new RuntimeDefinedParameterDictionary(); _dynamicParameters.Add("ResourceType", GenerateResourceTypeParameter(mandatory: false)); } return _dynamicParameters; } /// <summary> /// The value of the dynamic parameter -ResourceType. For example, if user types -ResourceType gce_instance, /// then this will be gce_instance. /// </summary> public string SelectedResourceType { get { if (_dynamicParameters != null && _dynamicParameters.ContainsKey("ResourceType")) { return _dynamicParameters["ResourceType"].Value?.ToString().ToLower(); } return null; } } } /// <summary> /// <para type="synopsis"> /// Gets log entries. /// </para> /// <para type="description"> /// Gets all log entries from a project or gets the entries from a specific log. /// Log entries can be filtered using -LogName, -Severity, -After or -Before parameter. /// For advanced filtering, please use -Filter parameter. /// </para> /// <example> /// <code>PS C:\> Get-GcLogEntry</code> /// <para>This command gets all the log entries for the default project.</para> /// </example> /// <example> /// <code>PS C:\> Get-GcLogEntry -Project "my-project"</code> /// <para>This command gets all the log entries from the project "my-project".</para> /// </example> /// <example> /// <code>PS C:\> Get-GcLogEntry -LogName "my-log"</code> /// <para>This command gets all the log entries from the log named "my-backendservice".</para> /// </example> /// <example> /// <code>PS C:\> Get-GcLogEntry -LogName "my-log"</code> /// <para>This command gets all the log entries from the log named "my-backendservice".</para> /// </example> /// <example> /// <code>PS C:\> Get-GcLogEntry -LogName "my-log" -Severity Error</code> /// <para>This command gets all the log entries with severity ERROR from the log named "my-backendservice".</para> /// </example> /// <example> /// <code>PS C:\> Get-GcLogEntry -LogName "my-log" -Before [DateTime]::Now.AddMinutes(30)</code> /// <para> /// This command gets all the log entries from the log named "my-backendservice" created before 30 minutes ago. /// </para> /// </example> /// <example> /// <code>PS C:\> Get-GcLogEntry -LogName "my-log" -After [DateTime]::Now.AddMinutes(30)</code> /// <para> /// This command gets all the log entries from the log named "my-backendservice" created after 30 minutes ago. /// </para> /// </example> /// <example> /// <code>PS C:\> Get-GcLogEntry -Filter 'resource.type="gce_instance" AND severity >= ERROR'</code> /// <para>This command gets all the log entries that satisfy filter.</para> /// </example> /// <para type="link" uri="(https://cloud.google.com/logging/docs/view/logs_index)"> /// [Log Entries and Logs] /// </para> /// <para type="link" uri="(https://cloud.google.com/logging/docs/view/advanced_filters)"> /// [Logs Filters] /// </para> /// </summary> [Cmdlet(VerbsCommon.Get, "GcLogEntry")] [OutputType(typeof(LogEntry))] public class GetGcLogEntryCmdlet : GcLogEntryCmdletWithLogFilter { /// <summary> /// <para type="description"> /// The project to check for log entries. If not set via PowerShell parameter processing, will /// default to the Cloud SDK's DefaultProject property. /// </para> /// </summary> [Parameter(Mandatory = false)] [ConfigPropertyName(CloudSdkSettings.CommonProperties.Project)] public override string Project { get; set; } protected override void ProcessRecord() { ListLogEntriesRequest logEntriesRequest = new ListLogEntriesRequest(); // Set resource to "projects/{Project}" so we will only find log entries in project Project. logEntriesRequest.ResourceNames = new List<string> { $"projects/{Project}" }; string logName = PrefixProjectToLogName(LogName, Project); logEntriesRequest.Filter = ConstructLogFilterString( logName: logName, logSeverity: Severity, selectedType: SelectedResourceType, before: Before, after: After, otherFilter: Filter); do { EntriesResource.ListRequest listLogRequest = Service.Entries.List(logEntriesRequest); ListLogEntriesResponse response = listLogRequest.Execute(); if (response.Entries != null) { foreach (LogEntry logEntry in response.Entries) { WriteObject(logEntry); } } logEntriesRequest.PageToken = response.NextPageToken; } while (!Stopping && logEntriesRequest.PageToken != null); } } /// <summary> /// <para type="synopsis"> /// Creates new monitored resources. /// </para> /// <para type="description"> /// Creates new monitored resources. These resources are used in the Logging cmdlets such as New-GcLogEntry /// </para> /// <example> /// <code> /// PS C:\> New-GcLogMonitoredResource -ResourceType "gce_instance" ` /// -Labels @{"project_id" = "my-project"; "instance_id" = "my-instance"}. /// </code> /// <para>This command creates a new monitored resource of type "gce_instance" with specified labels.</para> /// </example> /// <para type="link" uri="(https://cloud.google.com/logging/docs/api/v2/resource-list)"> /// [Monitored Resources and Labels] /// </para> /// </summary> [Cmdlet(VerbsCommon.New, "GcLogMonitoredResource")] public class NewGcLogMonitoredResource : GcLogCmdlet, IDynamicParameters { /// <summary> /// <para type="description"> /// The label that applies to resource type. /// For a complete list, see https://cloud.google.com/logging/docs/api/v2/resource-list. /// </para> /// </summary> [Parameter(Mandatory = true)] [ValidateNotNullOrEmpty] public Hashtable Labels { get; set; } /// <summary> /// This dynamic parameter dictionary is used by PowerShell to generate parameters dynamically. /// </summary> private RuntimeDefinedParameterDictionary _dynamicParameters; /// <summary> /// This function is part of the IDynamicParameters interface. /// PowerShell uses it to generate parameters dynamically. /// We have to generate -ResourceType parameter dynamically because the array /// of resources that we used to validate against are not generated before compile time, /// i.e. [ValidateSet(ArrayGeneratedAtRunTime)] will throw an error for parameters /// that are not generated dynamically. /// </summary> public object GetDynamicParameters() { if (_dynamicParameters == null) { _dynamicParameters = new RuntimeDefinedParameterDictionary(); _dynamicParameters.Add("ResourceType", GenerateResourceTypeParameter(mandatory: true)); } return _dynamicParameters; } protected override void ProcessRecord() { string selectedType = _dynamicParameters["ResourceType"].Value.ToString().ToLower(); MonitoredResourceDescriptor selectedDescriptor = GetResourceDescriptor(selectedType); IEnumerable<string> descriptorLabels = selectedDescriptor.Labels.Select(label => label.Key); // Validate that the Labels passed in match what is found in the labels of the selected descriptor. foreach (string labelKey in Labels.Keys) { if (!descriptorLabels.Contains(labelKey)) { string descriptorLabelsString = string.Join(", ", descriptorLabels); string errorMessage = $"Label '{labelKey}' cannot be found for monitored resource of type '{selectedType}'." + $"The available lables are '{descriptorLabelsString}'."; ErrorRecord errorRecord = new ErrorRecord( new ArgumentException(errorMessage), "InvalidLabel", ErrorCategory.InvalidData, labelKey); ThrowTerminatingError(errorRecord); } } MonitoredResource createdResource = new MonitoredResource() { Type = selectedType, Labels = ConvertToDictionary<string, string>(Labels) }; WriteObject(createdResource); } } /// <summary> /// <para type="synopsis"> /// Creates new log entries. /// </para> /// <para type="description"> /// Creates new log entries in a log. The cmdlet will create the log if it doesn't exist. /// By default, the log is associated with the "global" resource type ("custom.googleapis.com" in v1 service). /// </para> /// <example> /// <code>PS C:\> New-GcLogEntry -TextPayload "This is a log entry." -LogName "test-log"</code> /// <para>This command creates a log entry with the specified text payload in the log "test-log".</para> /// </example> /// <example> /// <code>PS C:\> New-GcLogEntry -TextPayload "Entry 1", "Entry 2" -LogName "test-log"</code> /// <para> /// This command creates 2 log entries with text payload "Entry 1" and "Entry 2" respectively in the log "test-log". /// </para> /// </example> /// <example> /// <code>PS C:\> New-GcLogEntry -JsonPayload @{"a" = "b"} -LogName "test-log" -Severity Error</code> /// <para>This command creates a log entry with a json payload and severity level Error in the log "test-log".</para> /// </example> /// <example> /// <code> /// PS C:\> New-GcLogEntry -MonitoredResource (New-GcLogMonitoredResource -ResourceType global -Labels @{"project_id" = "my-project"}) ` /// -TextPayload "This is a log entry." /// </code> /// <para> /// This command creates a log entry directly from the LogEntry object. /// The command also associates it with a resource type created from New-GcLogMonitoredResource /// </para> /// </example> /// <para type="link" uri="(https://cloud.google.com/logging/docs/view/logs_index)"> /// [Log Entries and Logs] /// </para> /// <para type="link" uri="(https://cloud.google.com/logging/docs/api/v2/resource-list)"> /// [Monitored Resources] /// </para> /// </summary> [Cmdlet(VerbsCommon.New, "GcLogEntry", DefaultParameterSetName = ParameterSetNames.TextPayload)] public class NewGcLogEntryCmdlet : GcLogCmdlet { private class ParameterSetNames { public const string TextPayload = "TextPayload"; public const string JsonPayload = "JsonPayload"; public const string ProtoPayload = "ProtoPayload"; } /// <summary> /// <para type="description"> /// The project to where the log entry will be written to. If not set via PowerShell parameter processing, /// will default to the Cloud SDK's DefaultProject property. /// </para> /// </summary> [Parameter] [ConfigPropertyName(CloudSdkSettings.CommonProperties.Project)] public override string Project { get; set; } /// <summary> /// <para type="description"> /// The name of the log that this entry will be written to. /// If the log does not exist, it will be created. /// </para> /// </summary> [Parameter(Position = 0, Mandatory = true)] public string LogName { get; set; } /// <summary> /// <para type="description"> /// The text payload of the log entry. Each value in the array will be written to a single entry in the log. /// </para> /// </summary> [Parameter(ParameterSetName = ParameterSetNames.TextPayload, Mandatory = true, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public string[] TextPayload { get; set; } /// <summary> /// <para type="description"> /// The JSON payload of the log entry. Each value in the array will be written to a single entry in the log. /// </para> /// </summary> [Parameter(ParameterSetName = ParameterSetNames.JsonPayload, Mandatory = true, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public Hashtable[] JsonPayload { get; set; } /// <summary> /// <para type="description"> /// The proto payload of the log entry. Each value in the array will be written to a single entry in the log. /// </para> /// </summary> [Parameter(ParameterSetName = ParameterSetNames.ProtoPayload, Mandatory = true)] [ValidateNotNullOrEmpty] public Hashtable[] ProtoPayload { get; set; } /// <summary> /// <para type="description"> /// The severity of the log entry. Default value is Default. /// </para> /// </summary> [Parameter(Mandatory = false)] public LogSeverity Severity { get; set; } /// <summary> /// <para type="description"> /// Monitored Resource associated with the log. If not provided, we will default to "global" resource type /// ("custom.googleapis.com" in v1 service). This is what gcloud beta logging write uses. /// This indicates that the log is not associated with any specific resource. /// More information can be found at https://cloud.google.com/logging/docs/api/v2/resource-list /// </para> /// </summary> [Parameter(Mandatory = false)] public MonitoredResource MonitoredResource { get; set; } protected override void ProcessRecord() { LogName = PrefixProjectToLogName(LogName, Project); if (MonitoredResource == null) { MonitoredResource = new MonitoredResource() { Type = "global", Labels = new Dictionary<string, string>() { { "project_id", Project } } }; } List<LogEntry> entries = new List<LogEntry>(); switch (ParameterSetName) { case ParameterSetNames.TextPayload: foreach (string text in TextPayload) { LogEntry entry = new LogEntry() { LogName = LogName, Severity = Enum.GetName(typeof(LogSeverity), Severity), Resource = MonitoredResource, TextPayload = text }; entries.Add(entry); } break; case ParameterSetNames.ProtoPayload: foreach (Hashtable hashTable in ProtoPayload) { LogEntry entry = new LogEntry() { LogName = LogName, Severity = Enum.GetName(typeof(LogSeverity), Severity), Resource = MonitoredResource, ProtoPayload = ConvertToDictionary<string, object>(hashTable) }; entries.Add(entry); } break; case ParameterSetNames.JsonPayload: foreach (Hashtable hashTable in JsonPayload) { LogEntry entry = new LogEntry() { LogName = LogName, Severity = Enum.GetName(typeof(LogSeverity), Severity), Resource = MonitoredResource, JsonPayload = ConvertToDictionary<string, object>(hashTable) }; entries.Add(entry); } break; default: throw UnknownParameterSetException; } WriteLogEntriesRequest writeRequest = new WriteLogEntriesRequest() { Entries = entries, LogName = LogName, Resource = MonitoredResource }; EntriesResource.WriteRequest request = Service.Entries.Write(writeRequest); WriteLogEntriesResponse response = request.Execute(); } } /// <summary> /// <para type="synopsis"> /// Lists Stackdriver logs' names from a project. /// </para> /// <para type="description"> /// Lists Stackdriver logs' names from a project. Will display logs' names from the default project if -Project is not used. /// A log is a named collection of log entries within the project (any log mus thave at least 1 log entry). /// To get log entries from a particular log, use Get-GcLogEntry cmdlet instead. /// </para> /// <example> /// <code>PS C:\> Get-GcLog</code> /// <para>This command gets logs from the default project.</para> /// </example> /// <example> /// <code>PS C:\> Get-GcLog -Project "my-project"</code> /// <para>This command gets logs from project "my-project".</para> /// </example> /// <para type="link" uri="(https://cloud.google.com/logging/docs/basic-concepts#logs)"> /// [Logs] /// </para> /// </summary> [Cmdlet(VerbsCommon.Get, "GcLog")] public class GetGcLogCmdlet : GcLogCmdlet { /// <summary> /// <para type="description"> /// The project to check for logs in. If not set via PowerShell parameter processing, will /// default to the Cloud SDK's DefaultProject property. /// </para> /// </summary> [Parameter] [ConfigPropertyName(CloudSdkSettings.CommonProperties.Project)] public override string Project { get; set; } protected override void ProcessRecord() { ProjectsResource.LogsResource.ListRequest listRequest = Service.Projects.Logs.List($"projects/{Project}"); do { try { ListLogsResponse response = listRequest.Execute(); if (response.LogNames != null) { WriteObject(response.LogNames, true); } listRequest.PageToken = response.NextPageToken; } catch (GoogleApiException ex) when (ex.HttpStatusCode == System.Net.HttpStatusCode.NotFound) { throw new PSArgumentException($"Project {Project} does not exist."); } } while (!Stopping && listRequest.PageToken != null); } } /// <summary> /// <para type="synopsis"> /// Removes one or more Stackdriver logs from a project. /// </para> /// <para type="description"> /// Removes one or more StackDrive logs from a project based on the names of the logs. /// All the entries in the logs will be deleted (a log have multiple log entries). /// </para> /// <example> /// <code>PS C:\> Remove-GcLog -LogName "test-log"</code> /// <para>This command removes "test-log" from the default project.</para> /// </example> /// <example> /// <code>PS C:\> Remove-GcLog -LogName "test-log" -Project "my-project"</code> /// <para>This command removes "test-log" from project "my-project".</para> /// </example> /// <example> /// <code>PS C:\> Remove-GcLog -LogName "log1", "log2"</code> /// <para>This command removes "log1" and "log2" from the default project.</para> /// </example> /// <para type="link" uri="(https://cloud.google.com/logging/docs/view/logs_index)"> /// [Log Entries and Logs] /// </para> /// </summary> [Cmdlet(VerbsCommon.Remove, "GcLog", SupportsShouldProcess = true)] public class RemoveGcLogCmdlet : GcLogCmdlet { /// <summary> /// <para type="description"> /// The project to check for log entries. If not set via PowerShell parameter processing, will /// default to the Cloud SDK's DefaultProject property. /// </para> /// </summary> [Parameter] [ConfigPropertyName(CloudSdkSettings.CommonProperties.Project)] public override string Project { get; set; } /// <summary> /// <para type="description"> /// The names of the logs to be removed. /// </para> /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public string[] LogName { get; set; } protected override void ProcessRecord() { foreach (string log in LogName) { string formattedLogName = PrefixProjectToLogName(log, Project); try { if (ShouldProcess(formattedLogName, "Remove Log")) { ProjectsResource.LogsResource.DeleteRequest deleteRequest = Service.Projects.Logs.Delete(formattedLogName); deleteRequest.Execute(); } } catch (GoogleApiException ex) when (ex.HttpStatusCode == HttpStatusCode.NotFound) { WriteResourceMissingError( exceptionMessage: $"Log '{log}' does not exist in project '{Project}'.", errorId: "LogNotFound", targetObject: log); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryNullableSubtractTests { #region Test methods [Fact] public static void CheckNullableByteSubtractTest() { byte?[] array = { 0, 1, byte.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableByteSubtract(array[i], array[j]); } } } [Fact] public static void CheckNullableSByteSubtractTest() { sbyte?[] array = { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableSByteSubtract(array[i], array[j]); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableUShortSubtractTest(bool useInterpreter) { ushort?[] array = { 0, 1, ushort.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUShortSubtract(array[i], array[j], useInterpreter); VerifyNullableUShortSubtractOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableShortSubtractTest(bool useInterpreter) { short?[] array = { 0, 1, -1, short.MinValue, short.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableShortSubtract(array[i], array[j], useInterpreter); VerifyNullableShortSubtractOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableUIntSubtractTest(bool useInterpreter) { uint?[] array = { 0, 1, uint.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUIntSubtract(array[i], array[j], useInterpreter); VerifyNullableUIntSubtractOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableIntSubtractTest(bool useInterpreter) { int?[] array = { 0, 1, -1, int.MinValue, int.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableIntSubtract(array[i], array[j], useInterpreter); VerifyNullableIntSubtractOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableULongSubtractTest(bool useInterpreter) { ulong?[] array = { 0, 1, ulong.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableULongSubtract(array[i], array[j], useInterpreter); VerifyNullableULongSubtractOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableLongSubtractTest(bool useInterpreter) { long?[] array = { 0, 1, -1, long.MinValue, long.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableLongSubtract(array[i], array[j], useInterpreter); VerifyNullableLongSubtractOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableFloatSubtractTest(bool useInterpreter) { float?[] array = { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableFloatSubtract(array[i], array[j], useInterpreter); VerifyNullableFloatSubtractOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableDoubleSubtractTest(bool useInterpreter) { double?[] array = { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDoubleSubtract(array[i], array[j], useInterpreter); VerifyNullableDoubleSubtractOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableDecimalSubtractTest(bool useInterpreter) { decimal?[] array = { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDecimalSubtract(array[i], array[j], useInterpreter); VerifyNullableDecimalSubtractOvf(array[i], array[j], useInterpreter); } } } [Fact] public static void CheckNullableCharSubtractTest() { char?[] array = { '\0', '\b', 'A', '\uffff', null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableCharSubtract(array[i], array[j]); } } } #endregion #region Test verifiers private static void VerifyNullableByteSubtract(byte? a, byte? b) { Expression aExp = Expression.Constant(a, typeof(byte?)); Expression bExp = Expression.Constant(b, typeof(byte?)); Assert.Throws<InvalidOperationException>(() => Expression.Subtract(aExp, bExp)); Assert.Throws<InvalidOperationException>(() => Expression.SubtractChecked(aExp, bExp)); } private static void VerifyNullableSByteSubtract(sbyte? a, sbyte? b) { Expression aExp = Expression.Constant(a, typeof(sbyte?)); Expression bExp = Expression.Constant(b, typeof(sbyte?)); Assert.Throws<InvalidOperationException>(() => Expression.Subtract(aExp, bExp)); Assert.Throws<InvalidOperationException>(() => Expression.SubtractChecked(aExp, bExp)); } private static void VerifyNullableUShortSubtract(ushort? a, ushort? b, bool useInterpreter) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.Subtract( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?))), Enumerable.Empty<ParameterExpression>()); Func<ushort?> f = e.Compile(useInterpreter); Assert.Equal((ushort?)(a - b), f()); } private static void VerifyNullableUShortSubtractOvf(ushort? a, ushort? b, bool useInterpreter) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?))), Enumerable.Empty<ParameterExpression>()); Func<ushort?> f = e.Compile(useInterpreter); ushort? expected; try { expected = checked((ushort?)(a - b)); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyNullableShortSubtract(short? a, short? b, bool useInterpreter) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.Subtract( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?))), Enumerable.Empty<ParameterExpression>()); Func<short?> f = e.Compile(useInterpreter); Assert.Equal((short?)(a - b), f()); } private static void VerifyNullableShortSubtractOvf(short? a, short? b, bool useInterpreter) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?))), Enumerable.Empty<ParameterExpression>()); Func<short?> f = e.Compile(useInterpreter); short? expected; try { expected = checked((short?)(a - b)); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyNullableUIntSubtract(uint? a, uint? b, bool useInterpreter) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.Subtract( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?))), Enumerable.Empty<ParameterExpression>()); Func<uint?> f = e.Compile(useInterpreter); Assert.Equal(a - b, f()); } private static void VerifyNullableUIntSubtractOvf(uint? a, uint? b, bool useInterpreter) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?))), Enumerable.Empty<ParameterExpression>()); Func<uint?> f = e.Compile(useInterpreter); uint? expected; try { expected = checked(a - b); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyNullableIntSubtract(int? a, int? b, bool useInterpreter) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.Subtract( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?))), Enumerable.Empty<ParameterExpression>()); Func<int?> f = e.Compile(useInterpreter); Assert.Equal(a - b, f()); } private static void VerifyNullableIntSubtractOvf(int? a, int? b, bool useInterpreter) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?))), Enumerable.Empty<ParameterExpression>()); Func<int?> f = e.Compile(useInterpreter); int? expected; try { expected = checked(a - b); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyNullableULongSubtract(ulong? a, ulong? b, bool useInterpreter) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.Subtract( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?))), Enumerable.Empty<ParameterExpression>()); Func<ulong?> f = e.Compile(useInterpreter); Assert.Equal(a - b, f()); } private static void VerifyNullableULongSubtractOvf(ulong? a, ulong? b, bool useInterpreter) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?))), Enumerable.Empty<ParameterExpression>()); Func<ulong?> f = e.Compile(useInterpreter); ulong? expected; try { expected = checked(a - b); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyNullableLongSubtract(long? a, long? b, bool useInterpreter) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.Subtract( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?))), Enumerable.Empty<ParameterExpression>()); Func<long?> f = e.Compile(useInterpreter); Assert.Equal(a - b, f()); } private static void VerifyNullableLongSubtractOvf(long? a, long? b, bool useInterpreter) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?))), Enumerable.Empty<ParameterExpression>()); Func<long?> f = e.Compile(useInterpreter); long? expected; try { expected = checked(a - b); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyNullableFloatSubtract(float? a, float? b, bool useInterpreter) { Expression<Func<float?>> e = Expression.Lambda<Func<float?>>( Expression.Subtract( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?))), Enumerable.Empty<ParameterExpression>()); Func<float?> f = e.Compile(useInterpreter); Assert.Equal(a - b, f()); } private static void VerifyNullableFloatSubtractOvf(float? a, float? b, bool useInterpreter) { Expression<Func<float?>> e = Expression.Lambda<Func<float?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?))), Enumerable.Empty<ParameterExpression>()); Func<float?> f = e.Compile(useInterpreter); Assert.Equal(a - b, f()); } private static void VerifyNullableDoubleSubtract(double? a, double? b, bool useInterpreter) { Expression<Func<double?>> e = Expression.Lambda<Func<double?>>( Expression.Subtract( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?))), Enumerable.Empty<ParameterExpression>()); Func<double?> f = e.Compile(useInterpreter); Assert.Equal(a - b, f()); } private static void VerifyNullableDoubleSubtractOvf(double? a, double? b, bool useInterpreter) { Expression<Func<double?>> e = Expression.Lambda<Func<double?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?))), Enumerable.Empty<ParameterExpression>()); Func<double?> f = e.Compile(useInterpreter); Assert.Equal(a - b, f()); } private static void VerifyNullableDecimalSubtract(decimal? a, decimal? b, bool useInterpreter) { Expression<Func<decimal?>> e = Expression.Lambda<Func<decimal?>>( Expression.Subtract( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?))), Enumerable.Empty<ParameterExpression>()); Func<decimal?> f = e.Compile(useInterpreter); if (a.HasValue & b.HasValue) { decimal? expected; try { expected = a - b; } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } else Assert.Null(f()); } private static void VerifyNullableDecimalSubtractOvf(decimal? a, decimal? b, bool useInterpreter) { Expression<Func<decimal?>> e = Expression.Lambda<Func<decimal?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?))), Enumerable.Empty<ParameterExpression>()); Func<decimal?> f = e.Compile(useInterpreter); if (a.HasValue & b.HasValue) { decimal? expected; try { expected = a - b; } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } else Assert.Null(f()); } private static void VerifyNullableCharSubtract(char? a, char? b) { Expression aExp = Expression.Constant(a, typeof(char?)); Expression bExp = Expression.Constant(b, typeof(char?)); Assert.Throws<InvalidOperationException>(() => Expression.Subtract(aExp, bExp)); Assert.Throws<InvalidOperationException>(() => Expression.SubtractChecked(aExp, bExp)); } #endregion } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Web; using System.Web.Hosting; using System.Web.Mvc; using System.Web.Routing; //Dummy namespaces to keep compiler happy when MVC isn't referenced namespace System.Web.Mvc { } namespace System.Web.Routing { } namespace ServiceStack.Html { public enum BundleOptions { Normal, Minified, Combined, MinifiedAndCombined } public static class Bundler { public static Func<bool> CachePaths = IsProduction; public static Func<string, BundleOptions, string> DefaultUrlFilter = ProcessVirtualPathDefault; public static bool UseMvc; static Bundler() { var mvcControllerExists = AppDomain.CurrentDomain.GetAssemblies().Any(x => x.GetType("System.Web.Mvc.Controller") != null); UseMvc = mvcControllerExists; } // Logic to determine if the app is running in production or dev environment public static bool IsProduction() { return (HttpContext.Current != null && !HttpContext.Current.IsDebuggingEnabled); } public static bool FileExists(string virtualPath) { if (!HostingEnvironment.IsHosted) return false; var filePath = HostingEnvironment.MapPath(virtualPath); return File.Exists(filePath); } static DateTime centuryBegin = new DateTime(2001, 1, 1); public static string TimestampString(string virtualPath) { try { if (HostingEnvironment.IsHosted) { var filePath = HostingEnvironment.MapPath(virtualPath); return Convert.ToString((File.GetLastWriteTimeUtc(filePath).Ticks - centuryBegin.Ticks) / 1000000000, 16); } } catch { } //ignore return string.Empty; } private static TVal GetOrAdd<TKey, TVal>(this Dictionary<TKey, TVal> map, TKey key, Func<TKey, TVal> factoryFn) { lock (map) { TVal ret; if (!map.TryGetValue(key, out ret)) { map[key] = ret = factoryFn(key); } return ret; } } private static void SafeClear<TKey, TVal>(this Dictionary<TKey, TVal> map) { lock (map) map.Clear(); } static readonly Dictionary<string, string> VirutalPathCache = new Dictionary<string, string>(); private static string ProcessVirtualPathDefault(string virtualPath, BundleOptions options) { if (!CachePaths()) VirutalPathCache.SafeClear(); return VirutalPathCache.GetOrAdd(virtualPath, str => { // The path that comes in starts with ~/ and must first be made absolute if (options == BundleOptions.Minified || options == BundleOptions.MinifiedAndCombined) { if (virtualPath.EndsWith(".js") && !virtualPath.EndsWith(".min.js")) { var minPath = virtualPath.Replace(".js", ".min.js"); if (FileExists(minPath)) virtualPath = minPath; } else if (virtualPath.EndsWith(".css") && !virtualPath.EndsWith(".min.css")) { var minPath = virtualPath.Replace(".css", ".min.css"); if (FileExists(minPath)) virtualPath = minPath; } } var path = virtualPath; if (virtualPath.IndexOf("://", StringComparison.Ordinal) == -1) { path = VirtualPathUtility.ToAbsolute(virtualPath); var cacheBreaker = TimestampString(virtualPath); if (!string.IsNullOrEmpty(cacheBreaker)) { path += path.IndexOf('?') == -1 ? "?" + cacheBreaker : "&" + cacheBreaker; } } // Add your own modifications here before returning the path return path; }); } private static string RewriteUrl(this string relativePath, BundleOptions options = BundleOptions.Normal) { return DefaultUrlFilter(relativePath, options); } public static MvcHtmlString ToMvcHtmlString(this string s) { return MvcHtmlString.Create(s); } public static MvcHtmlString ToMvcHtmlString(this TagBuilder t) { return t.ToString().ToMvcHtmlString(); } public static MvcHtmlString ToMvcHtmlString(this TagBuilder t, TagRenderMode mode) { return t.ToString(mode).ToMvcHtmlString(); } public delegate T ObjectActivator<T>(params object[] args); private static ObjectActivator<object> RouteValueDictionaryFactoryFn; public static ObjectActivator<T> GetActivator<T>(ConstructorInfo ctor) { var pis = ctor.GetParameters(); var param = Expression.Parameter(typeof(object[]), "args"); var argsExpr = new Expression[pis.Length]; for (int i = 0; i < pis.Length; i++) { var index = Expression.Constant(i); var paramType = pis[i].ParameterType; var paramAccessorExp = Expression.ArrayIndex(param, index); var paramCastExp = Expression.Convert(paramAccessorExp, paramType); argsExpr[i] = paramCastExp; } var newExpr = Expression.New(ctor, argsExpr); var lambda = Expression.Lambda(typeof(ObjectActivator<T>), newExpr, param); var compiled = (ObjectActivator<T>)lambda.Compile(); return compiled; } public static IDictionary<string, object> ToRouteValueDictionary(this object attrs) { if (RouteValueDictionaryFactoryFn == null) { var typeName = UseMvc ? "System.Web.Routing.RouteValueDictionary" : "ServiceStack.Html.RouteValueDictionary"; var assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.GetType(typeName) != null); if (assembly == null) throw new Exception(string.Format("Could not find type '{0}' in loaded assemblies", typeName)); var type = assembly.GetType(typeName); var ci = type.GetConstructor(new[] { typeof(object) }); RouteValueDictionaryFactoryFn = GetActivator<object>(ci); } return (IDictionary<string, object>)RouteValueDictionaryFactoryFn(attrs); } public static MvcHtmlString Link(this HtmlHelper html, string rel, string href, object htmlAttributes = null, BundleOptions options = BundleOptions.Normal) { if (string.IsNullOrEmpty(href)) return MvcHtmlString.Empty; if (href.StartsWith("~/")) href = href.Replace("~/", VirtualPathUtility.ToAbsolute("~")); var tag = new TagBuilder("link"); tag.MergeAttribute("rel", rel); tag.MergeAttribute("href", href.RewriteUrl(options)); if (htmlAttributes != null) tag.MergeAttributes(htmlAttributes.ToRouteValueDictionary()); return tag.ToString(TagRenderMode.SelfClosing).ToMvcHtmlString(); } public static MvcHtmlString Css(this HtmlHelper html, string href, string media = null, BundleOptions options = BundleOptions.Minified) { return media != null ? html.Link("stylesheet", href, new { media }, options) : html.Link("stylesheet", href, null, options); } public static T If<T>(this HtmlHelper html, bool predicate, T whenTrue, T whenFalse) { return predicate ? whenTrue : whenFalse; } public static MvcHtmlString Img(this HtmlHelper html, string src, string alt, string link = null, object htmlAttributes = null) { if (string.IsNullOrEmpty(src)) return MvcHtmlString.Empty; if (src.StartsWith("~/")) src = src.Replace("~/", VirtualPathUtility.ToAbsolute("~")); var tag = new TagBuilder("img"); tag.MergeAttribute("src", src.RewriteUrl()); tag.MergeAttribute("alt", alt); if (htmlAttributes != null) tag.MergeAttributes(htmlAttributes.ToRouteValueDictionary()); if (!string.IsNullOrEmpty(link)) { var a = new TagBuilder("a"); a.MergeAttribute("href", link); a.InnerHtml = tag.ToString(TagRenderMode.Normal); return a.ToMvcHtmlString(); } return tag.ToString(TagRenderMode.SelfClosing).ToMvcHtmlString(); } public static MvcHtmlString Js(this HtmlHelper html, string src, BundleOptions options = BundleOptions.Minified) { if (string.IsNullOrEmpty(src)) return MvcHtmlString.Empty; if (src.StartsWith("~/")) src = src.Replace("~/", VirtualPathUtility.ToAbsolute("~")); var tag = new TagBuilder("script"); tag.MergeAttribute("type", "text/javascript"); tag.MergeAttribute("src", src.RewriteUrl(options)); return tag.ToString(TagRenderMode.Normal).ToMvcHtmlString(); } public static MvcHtmlString Img(this HtmlHelper html, Uri url, string alt, Uri link = null, object htmlAttributes = null) { return html.Img(url.ToString(), alt, link != null ? link.ToString() : "", htmlAttributes); } public static string ToJsBool(this bool value) { return value.ToString(CultureInfo.InvariantCulture).ToLower(); } static readonly Dictionary<string, MvcHtmlString> BundleCache = new Dictionary<string, MvcHtmlString>(); public static MvcHtmlString RenderJsBundle(this HtmlHelper html, string bundlePath, BundleOptions options = BundleOptions.Minified) { if (string.IsNullOrEmpty(bundlePath)) return MvcHtmlString.Empty; if (!CachePaths()) BundleCache.SafeClear(); return BundleCache.GetOrAdd(bundlePath, str => { var filePath = HostingEnvironment.MapPath(bundlePath); var baseUrl = VirtualPathUtility.GetDirectory(bundlePath); if (options == BundleOptions.Combined) return html.Js(bundlePath.Replace(".bundle", ""), options); if (options == BundleOptions.MinifiedAndCombined) return html.Js(bundlePath.Replace(".js.bundle", ".min.js"), options); var jsFiles = File.ReadAllLines(filePath); var scripts = new StringBuilder(); foreach (var file in jsFiles) { var jsFile = file.Trim() .Replace(".coffee", ".js") .Replace(".ls", ".js"); var jsSrc = Path.Combine(baseUrl, jsFile); scripts.AppendLine( html.Js(jsSrc, options).ToString() ); } return scripts.ToString().ToMvcHtmlString(); }); } public static MvcHtmlString RenderCssBundle(this HtmlHelper html, string bundlePath, BundleOptions options = BundleOptions.Minified, string media = null) { if (string.IsNullOrEmpty(bundlePath)) return MvcHtmlString.Empty; if (!CachePaths()) BundleCache.SafeClear(); return BundleCache.GetOrAdd(bundlePath, str => { var filePath = HostingEnvironment.MapPath(bundlePath); var baseUrl = VirtualPathUtility.GetDirectory(bundlePath); if (options == BundleOptions.Combined) return html.Css(bundlePath.Replace(".bundle", ""), media, options); if (options == BundleOptions.MinifiedAndCombined) return html.Css(bundlePath.Replace(".css.bundle", ".min.css"), media, options); var cssFiles = File.ReadAllLines(filePath); var styles = new StringBuilder(); foreach (var file in cssFiles) { var cssFile = file.Trim() .Replace(".less", ".css") .Replace(".sass", ".css") .Replace(".scss", ".css") .Replace(".styl", ".css"); var cssSrc = Path.Combine(baseUrl, cssFile); styles.AppendLine( html.Css(cssSrc, media, options).ToString() ); } return styles.ToString().ToMvcHtmlString(); }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Providers; using Orleans.Runtime.Versions; using Orleans.Runtime.Versions.Compatibility; using Orleans.Runtime.Versions.Selector; using Orleans.Statistics; using Orleans.Versions.Compatibility; using Orleans.Versions.Selector; namespace Orleans.Runtime { internal class SiloControl : SystemTarget, ISiloControl { private readonly ILogger logger; private readonly ILocalSiloDetails localSiloDetails; private readonly DeploymentLoadPublisher deploymentLoadPublisher; private readonly Catalog catalog; private readonly CachedVersionSelectorManager cachedVersionSelectorManager; private readonly CompatibilityDirectorManager compatibilityDirectorManager; private readonly VersionSelectorManager selectorManager; private readonly IMessageCenter messageCenter; private readonly ActivationDirectory activationDirectory; private readonly ActivationCollector activationCollector; private readonly IAppEnvironmentStatistics appEnvironmentStatistics; private readonly IHostEnvironmentStatistics hostEnvironmentStatistics; private readonly IOptions<LoadSheddingOptions> loadSheddingOptions; private readonly Dictionary<Tuple<string,string>, IControllable> controllables; public SiloControl( ILocalSiloDetails localSiloDetails, DeploymentLoadPublisher deploymentLoadPublisher, Catalog catalog, CachedVersionSelectorManager cachedVersionSelectorManager, CompatibilityDirectorManager compatibilityDirectorManager, VersionSelectorManager selectorManager, IServiceProvider services, ILoggerFactory loggerFactory, IMessageCenter messageCenter, ActivationDirectory activationDirectory, ActivationCollector activationCollector, IAppEnvironmentStatistics appEnvironmentStatistics, IHostEnvironmentStatistics hostEnvironmentStatistics, IOptions<LoadSheddingOptions> loadSheddingOptions) : base(Constants.SiloControlType, localSiloDetails.SiloAddress, loggerFactory) { this.localSiloDetails = localSiloDetails; this.logger = loggerFactory.CreateLogger<SiloControl>(); this.deploymentLoadPublisher = deploymentLoadPublisher; this.catalog = catalog; this.cachedVersionSelectorManager = cachedVersionSelectorManager; this.compatibilityDirectorManager = compatibilityDirectorManager; this.selectorManager = selectorManager; this.messageCenter = messageCenter; this.activationDirectory = activationDirectory; this.activationCollector = activationCollector; this.appEnvironmentStatistics = appEnvironmentStatistics; this.hostEnvironmentStatistics = hostEnvironmentStatistics; this.loadSheddingOptions = loadSheddingOptions; this.controllables = new Dictionary<Tuple<string, string>, IControllable>(); IEnumerable<IKeyedServiceCollection<string, IControllable>> namedIControllableCollections = services.GetServices<IKeyedServiceCollection<string, IControllable>>(); foreach (IKeyedService<string, IControllable> keyedService in namedIControllableCollections.SelectMany(c => c.GetServices(services))) { IControllable controllable = keyedService.GetService(services); if(controllable != null) { this.controllables.Add(Tuple.Create(controllable.GetType().FullName, keyedService.Key), controllable); } } } public Task Ping(string message) { logger.Info("Ping"); return Task.CompletedTask; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.GC.Collect")] public Task ForceGarbageCollection() { logger.Info("ForceGarbageCollection"); GC.Collect(); return Task.CompletedTask; } public Task ForceActivationCollection(TimeSpan ageLimit) { logger.Info("ForceActivationCollection"); return this.catalog.CollectActivations(ageLimit); } public Task ForceRuntimeStatisticsCollection() { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("ForceRuntimeStatisticsCollection"); return this.deploymentLoadPublisher.RefreshStatistics(); } public Task<SiloRuntimeStatistics> GetRuntimeStatistics() { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("GetRuntimeStatistics"); var activationCount = this.activationDirectory.Count; var recentlyUsedActivationCount = this.activationCollector.GetNumRecentlyUsed(TimeSpan.FromMinutes(10)); var stats = new SiloRuntimeStatistics( activationCount, recentlyUsedActivationCount, this.appEnvironmentStatistics, this.hostEnvironmentStatistics, this.loadSheddingOptions, DateTime.UtcNow); return Task.FromResult(stats); } public Task<List<Tuple<GrainId, string, int>>> GetGrainStatistics() { logger.Info("GetGrainStatistics"); return Task.FromResult(this.catalog.GetGrainStatistics()); } public Task<List<DetailedGrainStatistic>> GetDetailedGrainStatistics(string[] types=null) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("GetDetailedGrainStatistics"); return Task.FromResult(this.catalog.GetDetailedGrainStatistics(types)); } public Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics() { logger.Info("GetSimpleGrainStatistics"); return Task.FromResult( this.catalog.GetSimpleGrainStatistics().Select(p => new SimpleGrainStatistic { SiloAddress = this.localSiloDetails.SiloAddress, GrainType = p.Key, ActivationCount = (int)p.Value }).ToArray()); } public Task<DetailedGrainReport> GetDetailedGrainReport(GrainId grainId) { logger.Info("DetailedGrainReport for grain id {0}", grainId); return Task.FromResult( this.catalog.GetDetailedGrainReport(grainId)); } public Task<int> GetActivationCount() { return Task.FromResult(this.catalog.ActivationCount); } public Task<object> SendControlCommandToProvider(string providerTypeFullName, string providerName, int command, object arg) { IControllable controllable; if(!this.controllables.TryGetValue(Tuple.Create(providerTypeFullName, providerName), out controllable)) { string error = $"Could not find a controllable service for type {providerTypeFullName} and name {providerName}."; logger.Error(ErrorCode.Provider_ProviderNotFound, error); throw new ArgumentException(error); } return controllable.ExecuteCommand(command, arg); } public Task SetCompatibilityStrategy(CompatibilityStrategy strategy) { this.compatibilityDirectorManager.SetStrategy(strategy); this.cachedVersionSelectorManager.ResetCache(); return Task.CompletedTask; } public Task SetSelectorStrategy(VersionSelectorStrategy strategy) { this.selectorManager.SetSelector(strategy); this.cachedVersionSelectorManager.ResetCache(); return Task.CompletedTask; } public Task SetCompatibilityStrategy(GrainInterfaceType interfaceId, CompatibilityStrategy strategy) { this.compatibilityDirectorManager.SetStrategy(interfaceId, strategy); this.cachedVersionSelectorManager.ResetCache(); return Task.CompletedTask; } public Task SetSelectorStrategy(GrainInterfaceType interfaceType, VersionSelectorStrategy strategy) { this.selectorManager.SetSelector(interfaceType, strategy); this.cachedVersionSelectorManager.ResetCache(); return Task.CompletedTask; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml { public enum ConformanceLevel { Auto = 0, Document = 2, Fragment = 1, } public enum DtdProcessing { Ignore = 1, Prohibit = 0, } public partial interface IXmlLineInfo { int LineNumber { get; } int LinePosition { get; } bool HasLineInfo(); } public partial interface IXmlNamespaceResolver { System.Collections.Generic.IDictionary<string, string> GetNamespacesInScope(System.Xml.XmlNamespaceScope scope); string LookupNamespace(string prefix); string LookupPrefix(string namespaceName); } [System.FlagsAttribute] public enum NamespaceHandling { Default = 0, OmitDuplicates = 1, } public partial class NameTable : System.Xml.XmlNameTable { public NameTable() { } public override string Add(char[] key, int start, int len) { return default(string); } public override string Add(string key) { return default(string); } public override string Get(char[] key, int start, int len) { return default(string); } public override string Get(string value) { return default(string); } } public enum NewLineHandling { Entitize = 1, None = 2, Replace = 0, } public enum ReadState { Closed = 4, EndOfFile = 3, Error = 2, Initial = 0, Interactive = 1, } public enum WriteState { Attribute = 3, Closed = 5, Content = 4, Element = 2, Error = 6, Prolog = 1, Start = 0, } public static partial class XmlConvert { public static string DecodeName(string name) { return default(string); } public static string EncodeLocalName(string name) { return default(string); } public static string EncodeName(string name) { return default(string); } public static string EncodeNmToken(string name) { return default(string); } public static bool ToBoolean(string s) { return default(bool); } public static byte ToByte(string s) { return default(byte); } public static char ToChar(string s) { return default(char); } public static System.DateTime ToDateTime(string s, System.Xml.XmlDateTimeSerializationMode dateTimeOption) { return default(System.DateTime); } public static System.DateTimeOffset ToDateTimeOffset(string s) { return default(System.DateTimeOffset); } public static System.DateTimeOffset ToDateTimeOffset(string s, string format) { return default(System.DateTimeOffset); } public static System.DateTimeOffset ToDateTimeOffset(string s, string[] formats) { return default(System.DateTimeOffset); } public static decimal ToDecimal(string s) { return default(decimal); } public static double ToDouble(string s) { return default(double); } public static System.Guid ToGuid(string s) { return default(System.Guid); } public static short ToInt16(string s) { return default(short); } public static int ToInt32(string s) { return default(int); } public static long ToInt64(string s) { return default(long); } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(string s) { return default(sbyte); } public static float ToSingle(string s) { return default(float); } public static string ToString(bool value) { return default(string); } public static string ToString(byte value) { return default(string); } public static string ToString(char value) { return default(string); } public static string ToString(System.DateTime value, System.Xml.XmlDateTimeSerializationMode dateTimeOption) { return default(string); } public static string ToString(System.DateTimeOffset value) { return default(string); } public static string ToString(System.DateTimeOffset value, string format) { return default(string); } public static string ToString(decimal value) { return default(string); } public static string ToString(double value) { return default(string); } public static string ToString(System.Guid value) { return default(string); } public static string ToString(short value) { return default(string); } public static string ToString(int value) { return default(string); } public static string ToString(long value) { return default(string); } [System.CLSCompliantAttribute(false)] public static string ToString(sbyte value) { return default(string); } public static string ToString(float value) { return default(string); } public static string ToString(System.TimeSpan value) { return default(string); } [System.CLSCompliantAttribute(false)] public static string ToString(ushort value) { return default(string); } [System.CLSCompliantAttribute(false)] public static string ToString(uint value) { return default(string); } [System.CLSCompliantAttribute(false)] public static string ToString(ulong value) { return default(string); } public static System.TimeSpan ToTimeSpan(string s) { return default(System.TimeSpan); } [System.CLSCompliantAttribute(false)] public static ushort ToUInt16(string s) { return default(ushort); } [System.CLSCompliantAttribute(false)] public static uint ToUInt32(string s) { return default(uint); } [System.CLSCompliantAttribute(false)] public static ulong ToUInt64(string s) { return default(ulong); } public static string VerifyName(string name) { return default(string); } public static string VerifyNCName(string name) { return default(string); } public static string VerifyNMTOKEN(string name) { return default(string); } public static string VerifyPublicId(string publicId) { return default(string); } public static string VerifyWhitespace(string content) { return default(string); } public static string VerifyXmlChars(string content) { return default(string); } } public enum XmlDateTimeSerializationMode { Local = 0, RoundtripKind = 3, Unspecified = 2, Utc = 1, } public partial class XmlException : System.Exception { public XmlException() { } public XmlException(string message) { } public XmlException(string message, System.Exception innerException) { } public XmlException(string message, System.Exception innerException, int lineNumber, int linePosition) { } public int LineNumber { get { return default(int); } } public int LinePosition { get { return default(int); } } public override string Message { get { return default(string); } } } public partial class XmlNamespaceManager : System.Collections.IEnumerable, System.Xml.IXmlNamespaceResolver { public XmlNamespaceManager(System.Xml.XmlNameTable nameTable) { } public virtual string DefaultNamespace { get { return default(string); } } public virtual System.Xml.XmlNameTable NameTable { get { return default(System.Xml.XmlNameTable); } } public virtual void AddNamespace(string prefix, string uri) { } public virtual System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); } public virtual System.Collections.Generic.IDictionary<string, string> GetNamespacesInScope(System.Xml.XmlNamespaceScope scope) { return default(System.Collections.Generic.IDictionary<string, string>); } public virtual bool HasNamespace(string prefix) { return default(bool); } public virtual string LookupNamespace(string prefix) { return default(string); } public virtual string LookupPrefix(string uri) { return default(string); } public virtual bool PopScope() { return default(bool); } public virtual void PushScope() { } public virtual void RemoveNamespace(string prefix, string uri) { } } public enum XmlNamespaceScope { All = 0, ExcludeXml = 1, Local = 2, } public abstract partial class XmlNameTable { protected XmlNameTable() { } public abstract string Add(char[] array, int offset, int length); public abstract string Add(string array); public abstract string Get(char[] array, int offset, int length); public abstract string Get(string array); } public enum XmlNodeType { Attribute = 2, CDATA = 4, Comment = 8, Document = 9, DocumentFragment = 11, DocumentType = 10, Element = 1, EndElement = 15, EndEntity = 16, Entity = 6, EntityReference = 5, None = 0, Notation = 12, ProcessingInstruction = 7, SignificantWhitespace = 14, Text = 3, Whitespace = 13, XmlDeclaration = 17, } public partial class XmlParserContext { public XmlParserContext(System.Xml.XmlNameTable nt, System.Xml.XmlNamespaceManager nsMgr, string docTypeName, string pubId, string sysId, string internalSubset, string baseURI, string xmlLang, System.Xml.XmlSpace xmlSpace) { } public XmlParserContext(System.Xml.XmlNameTable nt, System.Xml.XmlNamespaceManager nsMgr, string docTypeName, string pubId, string sysId, string internalSubset, string baseURI, string xmlLang, System.Xml.XmlSpace xmlSpace, System.Text.Encoding enc) { } public XmlParserContext(System.Xml.XmlNameTable nt, System.Xml.XmlNamespaceManager nsMgr, string xmlLang, System.Xml.XmlSpace xmlSpace) { } public XmlParserContext(System.Xml.XmlNameTable nt, System.Xml.XmlNamespaceManager nsMgr, string xmlLang, System.Xml.XmlSpace xmlSpace, System.Text.Encoding enc) { } public string BaseURI { get { return default(string); } set { } } public string DocTypeName { get { return default(string); } set { } } public System.Text.Encoding Encoding { get { return default(System.Text.Encoding); } set { } } public string InternalSubset { get { return default(string); } set { } } public System.Xml.XmlNamespaceManager NamespaceManager { get { return default(System.Xml.XmlNamespaceManager); } set { } } public System.Xml.XmlNameTable NameTable { get { return default(System.Xml.XmlNameTable); } set { } } public string PublicId { get { return default(string); } set { } } public string SystemId { get { return default(string); } set { } } public string XmlLang { get { return default(string); } set { } } public System.Xml.XmlSpace XmlSpace { get { return default(System.Xml.XmlSpace); } set { } } } public partial class XmlQualifiedName { public static readonly System.Xml.XmlQualifiedName Empty; public XmlQualifiedName() { } public XmlQualifiedName(string name) { } public XmlQualifiedName(string name, string ns) { } public bool IsEmpty { get { return default(bool); } } public string Name { get { return default(string); } } public string Namespace { get { return default(string); } } public override bool Equals(object other) { return default(bool); } public override int GetHashCode() { return default(int); } public static bool operator ==(System.Xml.XmlQualifiedName a, System.Xml.XmlQualifiedName b) { return default(bool); } public static bool operator !=(System.Xml.XmlQualifiedName a, System.Xml.XmlQualifiedName b) { return default(bool); } public override string ToString() { return default(string); } public static string ToString(string name, string ns) { return default(string); } } public abstract partial class XmlReader : System.IDisposable { protected XmlReader() { } public abstract int AttributeCount { get; } public abstract string BaseURI { get; } public virtual bool CanReadBinaryContent { get { return default(bool); } } public virtual bool CanReadValueChunk { get { return default(bool); } } public virtual bool CanResolveEntity { get { return default(bool); } } public abstract int Depth { get; } public abstract bool EOF { get; } public virtual bool HasAttributes { get { return default(bool); } } public virtual bool HasValue { get { return default(bool); } } public virtual bool IsDefault { get { return default(bool); } } public abstract bool IsEmptyElement { get; } public virtual string this[int i] { get { return default(string); } } public virtual string this[string name] { get { return default(string); } } public virtual string this[string name, string namespaceURI] { get { return default(string); } } public abstract string LocalName { get; } public virtual string Name { get { return default(string); } } public abstract string NamespaceURI { get; } public abstract System.Xml.XmlNameTable NameTable { get; } public abstract System.Xml.XmlNodeType NodeType { get; } public abstract string Prefix { get; } public abstract System.Xml.ReadState ReadState { get; } public virtual System.Xml.XmlReaderSettings Settings { get { return default(System.Xml.XmlReaderSettings); } } public abstract string Value { get; } public virtual System.Type ValueType { get { return default(System.Type); } } public virtual string XmlLang { get { return default(string); } } public virtual System.Xml.XmlSpace XmlSpace { get { return default(System.Xml.XmlSpace); } } public static System.Xml.XmlReader Create(System.IO.Stream input) { return default(System.Xml.XmlReader); } public static System.Xml.XmlReader Create(System.IO.Stream input, System.Xml.XmlReaderSettings settings) { return default(System.Xml.XmlReader); } public static System.Xml.XmlReader Create(System.IO.Stream input, System.Xml.XmlReaderSettings settings, System.Xml.XmlParserContext inputContext) { return default(System.Xml.XmlReader); } public static System.Xml.XmlReader Create(System.IO.TextReader input) { return default(System.Xml.XmlReader); } public static System.Xml.XmlReader Create(System.IO.TextReader input, System.Xml.XmlReaderSettings settings) { return default(System.Xml.XmlReader); } public static System.Xml.XmlReader Create(System.IO.TextReader input, System.Xml.XmlReaderSettings settings, System.Xml.XmlParserContext inputContext) { return default(System.Xml.XmlReader); } public static System.Xml.XmlReader Create(string inputUri) { return default(System.Xml.XmlReader); } public static System.Xml.XmlReader Create(string inputUri, System.Xml.XmlReaderSettings settings) { return default(System.Xml.XmlReader); } public static System.Xml.XmlReader Create(System.Xml.XmlReader reader, System.Xml.XmlReaderSettings settings) { return default(System.Xml.XmlReader); } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public abstract string GetAttribute(int i); public abstract string GetAttribute(string name); public abstract string GetAttribute(string name, string namespaceURI); public virtual System.Threading.Tasks.Task<string> GetValueAsync() { return default(System.Threading.Tasks.Task<string>); } public static bool IsName(string str) { return default(bool); } public static bool IsNameToken(string str) { return default(bool); } public virtual bool IsStartElement() { return default(bool); } public virtual bool IsStartElement(string name) { return default(bool); } public virtual bool IsStartElement(string localname, string ns) { return default(bool); } public abstract string LookupNamespace(string prefix); public virtual void MoveToAttribute(int i) { } public abstract bool MoveToAttribute(string name); public abstract bool MoveToAttribute(string name, string ns); public virtual System.Xml.XmlNodeType MoveToContent() { return default(System.Xml.XmlNodeType); } public virtual System.Threading.Tasks.Task<System.Xml.XmlNodeType> MoveToContentAsync() { return default(System.Threading.Tasks.Task<System.Xml.XmlNodeType>); } public abstract bool MoveToElement(); public abstract bool MoveToFirstAttribute(); public abstract bool MoveToNextAttribute(); public abstract bool Read(); public virtual System.Threading.Tasks.Task<bool> ReadAsync() { return default(System.Threading.Tasks.Task<bool>); } public abstract bool ReadAttributeValue(); public virtual object ReadContentAs(System.Type returnType, System.Xml.IXmlNamespaceResolver namespaceResolver) { return default(object); } public virtual System.Threading.Tasks.Task<object> ReadContentAsAsync(System.Type returnType, System.Xml.IXmlNamespaceResolver namespaceResolver) { return default(System.Threading.Tasks.Task<object>); } public virtual int ReadContentAsBase64(byte[] buffer, int index, int count) { return default(int); } public virtual System.Threading.Tasks.Task<int> ReadContentAsBase64Async(byte[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); } public virtual int ReadContentAsBinHex(byte[] buffer, int index, int count) { return default(int); } public virtual System.Threading.Tasks.Task<int> ReadContentAsBinHexAsync(byte[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); } public virtual bool ReadContentAsBoolean() { return default(bool); } public virtual System.DateTimeOffset ReadContentAsDateTimeOffset() { return default(System.DateTimeOffset); } public virtual decimal ReadContentAsDecimal() { return default(decimal); } public virtual double ReadContentAsDouble() { return default(double); } public virtual float ReadContentAsFloat() { return default(float); } public virtual int ReadContentAsInt() { return default(int); } public virtual long ReadContentAsLong() { return default(long); } public virtual object ReadContentAsObject() { return default(object); } public virtual System.Threading.Tasks.Task<object> ReadContentAsObjectAsync() { return default(System.Threading.Tasks.Task<object>); } public virtual string ReadContentAsString() { return default(string); } public virtual System.Threading.Tasks.Task<string> ReadContentAsStringAsync() { return default(System.Threading.Tasks.Task<string>); } public virtual object ReadElementContentAs(System.Type returnType, System.Xml.IXmlNamespaceResolver namespaceResolver) { return default(object); } public virtual object ReadElementContentAs(System.Type returnType, System.Xml.IXmlNamespaceResolver namespaceResolver, string localName, string namespaceURI) { return default(object); } public virtual System.Threading.Tasks.Task<object> ReadElementContentAsAsync(System.Type returnType, System.Xml.IXmlNamespaceResolver namespaceResolver) { return default(System.Threading.Tasks.Task<object>); } public virtual int ReadElementContentAsBase64(byte[] buffer, int index, int count) { return default(int); } public virtual System.Threading.Tasks.Task<int> ReadElementContentAsBase64Async(byte[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); } public virtual int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { return default(int); } public virtual System.Threading.Tasks.Task<int> ReadElementContentAsBinHexAsync(byte[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); } public virtual bool ReadElementContentAsBoolean() { return default(bool); } public virtual bool ReadElementContentAsBoolean(string localName, string namespaceURI) { return default(bool); } public virtual decimal ReadElementContentAsDecimal() { return default(decimal); } public virtual decimal ReadElementContentAsDecimal(string localName, string namespaceURI) { return default(decimal); } public virtual double ReadElementContentAsDouble() { return default(double); } public virtual double ReadElementContentAsDouble(string localName, string namespaceURI) { return default(double); } public virtual float ReadElementContentAsFloat() { return default(float); } public virtual float ReadElementContentAsFloat(string localName, string namespaceURI) { return default(float); } public virtual int ReadElementContentAsInt() { return default(int); } public virtual int ReadElementContentAsInt(string localName, string namespaceURI) { return default(int); } public virtual long ReadElementContentAsLong() { return default(long); } public virtual long ReadElementContentAsLong(string localName, string namespaceURI) { return default(long); } public virtual object ReadElementContentAsObject() { return default(object); } public virtual object ReadElementContentAsObject(string localName, string namespaceURI) { return default(object); } public virtual System.Threading.Tasks.Task<object> ReadElementContentAsObjectAsync() { return default(System.Threading.Tasks.Task<object>); } public virtual string ReadElementContentAsString() { return default(string); } public virtual string ReadElementContentAsString(string localName, string namespaceURI) { return default(string); } public virtual System.Threading.Tasks.Task<string> ReadElementContentAsStringAsync() { return default(System.Threading.Tasks.Task<string>); } public virtual void ReadEndElement() { } public virtual string ReadInnerXml() { return default(string); } public virtual System.Threading.Tasks.Task<string> ReadInnerXmlAsync() { return default(System.Threading.Tasks.Task<string>); } public virtual string ReadOuterXml() { return default(string); } public virtual System.Threading.Tasks.Task<string> ReadOuterXmlAsync() { return default(System.Threading.Tasks.Task<string>); } public virtual void ReadStartElement() { } public virtual void ReadStartElement(string name) { } public virtual void ReadStartElement(string localname, string ns) { } public virtual System.Xml.XmlReader ReadSubtree() { return default(System.Xml.XmlReader); } public virtual bool ReadToDescendant(string name) { return default(bool); } public virtual bool ReadToDescendant(string localName, string namespaceURI) { return default(bool); } public virtual bool ReadToFollowing(string name) { return default(bool); } public virtual bool ReadToFollowing(string localName, string namespaceURI) { return default(bool); } public virtual bool ReadToNextSibling(string name) { return default(bool); } public virtual bool ReadToNextSibling(string localName, string namespaceURI) { return default(bool); } public virtual int ReadValueChunk(char[] buffer, int index, int count) { return default(int); } public virtual System.Threading.Tasks.Task<int> ReadValueChunkAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); } public abstract void ResolveEntity(); public virtual void Skip() { } public virtual System.Threading.Tasks.Task SkipAsync() { return default(System.Threading.Tasks.Task); } } public sealed partial class XmlReaderSettings { public XmlReaderSettings() { } public bool Async { get { return default(bool); } set { } } public bool CheckCharacters { get { return default(bool); } set { } } public bool CloseInput { get { return default(bool); } set { } } public System.Xml.ConformanceLevel ConformanceLevel { get { return default(System.Xml.ConformanceLevel); } set { } } public System.Xml.DtdProcessing DtdProcessing { get { return default(System.Xml.DtdProcessing); } set { } } public bool IgnoreComments { get { return default(bool); } set { } } public bool IgnoreProcessingInstructions { get { return default(bool); } set { } } public bool IgnoreWhitespace { get { return default(bool); } set { } } public int LineNumberOffset { get { return default(int); } set { } } public int LinePositionOffset { get { return default(int); } set { } } public long MaxCharactersFromEntities { get { return default(long); } set { } } public long MaxCharactersInDocument { get { return default(long); } set { } } public System.Xml.XmlNameTable NameTable { get { return default(System.Xml.XmlNameTable); } set { } } public System.Xml.XmlReaderSettings Clone() { return default(System.Xml.XmlReaderSettings); } public void Reset() { } } public enum XmlSpace { Default = 1, None = 0, Preserve = 2, } public abstract partial class XmlWriter : System.IDisposable { protected XmlWriter() { } public virtual System.Xml.XmlWriterSettings Settings { get { return default(System.Xml.XmlWriterSettings); } } public abstract System.Xml.WriteState WriteState { get; } public virtual string XmlLang { get { return default(string); } } public virtual System.Xml.XmlSpace XmlSpace { get { return default(System.Xml.XmlSpace); } } public static System.Xml.XmlWriter Create(System.IO.Stream output) { return default(System.Xml.XmlWriter); } public static System.Xml.XmlWriter Create(System.IO.Stream output, System.Xml.XmlWriterSettings settings) { return default(System.Xml.XmlWriter); } public static System.Xml.XmlWriter Create(System.IO.TextWriter output) { return default(System.Xml.XmlWriter); } public static System.Xml.XmlWriter Create(System.IO.TextWriter output, System.Xml.XmlWriterSettings settings) { return default(System.Xml.XmlWriter); } public static System.Xml.XmlWriter Create(System.Text.StringBuilder output) { return default(System.Xml.XmlWriter); } public static System.Xml.XmlWriter Create(System.Text.StringBuilder output, System.Xml.XmlWriterSettings settings) { return default(System.Xml.XmlWriter); } public static System.Xml.XmlWriter Create(System.Xml.XmlWriter output) { return default(System.Xml.XmlWriter); } public static System.Xml.XmlWriter Create(System.Xml.XmlWriter output, System.Xml.XmlWriterSettings settings) { return default(System.Xml.XmlWriter); } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public abstract void Flush(); public virtual System.Threading.Tasks.Task FlushAsync() { return default(System.Threading.Tasks.Task); } public abstract string LookupPrefix(string ns); public virtual void WriteAttributes(System.Xml.XmlReader reader, bool defattr) { } public virtual System.Threading.Tasks.Task WriteAttributesAsync(System.Xml.XmlReader reader, bool defattr) { return default(System.Threading.Tasks.Task); } public void WriteAttributeString(string localName, string value) { } public void WriteAttributeString(string localName, string ns, string value) { } public void WriteAttributeString(string prefix, string localName, string ns, string value) { } public System.Threading.Tasks.Task WriteAttributeStringAsync(string prefix, string localName, string ns, string value) { return default(System.Threading.Tasks.Task); } public abstract void WriteBase64(byte[] buffer, int index, int count); public virtual System.Threading.Tasks.Task WriteBase64Async(byte[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); } public virtual void WriteBinHex(byte[] buffer, int index, int count) { } public virtual System.Threading.Tasks.Task WriteBinHexAsync(byte[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); } public abstract void WriteCData(string text); public virtual System.Threading.Tasks.Task WriteCDataAsync(string text) { return default(System.Threading.Tasks.Task); } public abstract void WriteCharEntity(char ch); public virtual System.Threading.Tasks.Task WriteCharEntityAsync(char ch) { return default(System.Threading.Tasks.Task); } public abstract void WriteChars(char[] buffer, int index, int count); public virtual System.Threading.Tasks.Task WriteCharsAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); } public abstract void WriteComment(string text); public virtual System.Threading.Tasks.Task WriteCommentAsync(string text) { return default(System.Threading.Tasks.Task); } public abstract void WriteDocType(string name, string pubid, string sysid, string subset); public virtual System.Threading.Tasks.Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset) { return default(System.Threading.Tasks.Task); } public void WriteElementString(string localName, string value) { } public void WriteElementString(string localName, string ns, string value) { } public void WriteElementString(string prefix, string localName, string ns, string value) { } public System.Threading.Tasks.Task WriteElementStringAsync(string prefix, string localName, string ns, string value) { return default(System.Threading.Tasks.Task); } public abstract void WriteEndAttribute(); protected internal virtual System.Threading.Tasks.Task WriteEndAttributeAsync() { return default(System.Threading.Tasks.Task); } public abstract void WriteEndDocument(); public virtual System.Threading.Tasks.Task WriteEndDocumentAsync() { return default(System.Threading.Tasks.Task); } public abstract void WriteEndElement(); public virtual System.Threading.Tasks.Task WriteEndElementAsync() { return default(System.Threading.Tasks.Task); } public abstract void WriteEntityRef(string name); public virtual System.Threading.Tasks.Task WriteEntityRefAsync(string name) { return default(System.Threading.Tasks.Task); } public abstract void WriteFullEndElement(); public virtual System.Threading.Tasks.Task WriteFullEndElementAsync() { return default(System.Threading.Tasks.Task); } public virtual void WriteName(string name) { } public virtual System.Threading.Tasks.Task WriteNameAsync(string name) { return default(System.Threading.Tasks.Task); } public virtual void WriteNmToken(string name) { } public virtual System.Threading.Tasks.Task WriteNmTokenAsync(string name) { return default(System.Threading.Tasks.Task); } public virtual void WriteNode(System.Xml.XmlReader reader, bool defattr) { } public virtual System.Threading.Tasks.Task WriteNodeAsync(System.Xml.XmlReader reader, bool defattr) { return default(System.Threading.Tasks.Task); } public abstract void WriteProcessingInstruction(string name, string text); public virtual System.Threading.Tasks.Task WriteProcessingInstructionAsync(string name, string text) { return default(System.Threading.Tasks.Task); } public virtual void WriteQualifiedName(string localName, string ns) { } public virtual System.Threading.Tasks.Task WriteQualifiedNameAsync(string localName, string ns) { return default(System.Threading.Tasks.Task); } public abstract void WriteRaw(char[] buffer, int index, int count); public abstract void WriteRaw(string data); public virtual System.Threading.Tasks.Task WriteRawAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); } public virtual System.Threading.Tasks.Task WriteRawAsync(string data) { return default(System.Threading.Tasks.Task); } public void WriteStartAttribute(string localName) { } public void WriteStartAttribute(string localName, string ns) { } public abstract void WriteStartAttribute(string prefix, string localName, string ns); protected internal virtual System.Threading.Tasks.Task WriteStartAttributeAsync(string prefix, string localName, string ns) { return default(System.Threading.Tasks.Task); } public abstract void WriteStartDocument(); public abstract void WriteStartDocument(bool standalone); public virtual System.Threading.Tasks.Task WriteStartDocumentAsync() { return default(System.Threading.Tasks.Task); } public virtual System.Threading.Tasks.Task WriteStartDocumentAsync(bool standalone) { return default(System.Threading.Tasks.Task); } public void WriteStartElement(string localName) { } public void WriteStartElement(string localName, string ns) { } public abstract void WriteStartElement(string prefix, string localName, string ns); public virtual System.Threading.Tasks.Task WriteStartElementAsync(string prefix, string localName, string ns) { return default(System.Threading.Tasks.Task); } public abstract void WriteString(string text); public virtual System.Threading.Tasks.Task WriteStringAsync(string text) { return default(System.Threading.Tasks.Task); } public abstract void WriteSurrogateCharEntity(char lowChar, char highChar); public virtual System.Threading.Tasks.Task WriteSurrogateCharEntityAsync(char lowChar, char highChar) { return default(System.Threading.Tasks.Task); } public virtual void WriteValue(bool value) { } public virtual void WriteValue(System.DateTimeOffset value) { } public virtual void WriteValue(decimal value) { } public virtual void WriteValue(double value) { } public virtual void WriteValue(int value) { } public virtual void WriteValue(long value) { } public virtual void WriteValue(object value) { } public virtual void WriteValue(float value) { } public virtual void WriteValue(string value) { } public abstract void WriteWhitespace(string ws); public virtual System.Threading.Tasks.Task WriteWhitespaceAsync(string ws) { return default(System.Threading.Tasks.Task); } } public sealed partial class XmlWriterSettings { public XmlWriterSettings() { } public bool Async { get { return default(bool); } set { } } public bool CheckCharacters { get { return default(bool); } set { } } public bool CloseOutput { get { return default(bool); } set { } } public System.Xml.ConformanceLevel ConformanceLevel { get { return default(System.Xml.ConformanceLevel); } set { } } public System.Text.Encoding Encoding { get { return default(System.Text.Encoding); } set { } } public bool Indent { get { return default(bool); } set { } } public string IndentChars { get { return default(string); } set { } } public System.Xml.NamespaceHandling NamespaceHandling { get { return default(System.Xml.NamespaceHandling); } set { } } public string NewLineChars { get { return default(string); } set { } } public System.Xml.NewLineHandling NewLineHandling { get { return default(System.Xml.NewLineHandling); } set { } } public bool NewLineOnAttributes { get { return default(bool); } set { } } public bool OmitXmlDeclaration { get { return default(bool); } set { } } public bool WriteEndDocumentOnClose { get { return default(bool); } set { } } public System.Xml.XmlWriterSettings Clone() { return default(System.Xml.XmlWriterSettings); } public void Reset() { } } } namespace System.Xml.Schema { [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public partial class XmlSchema { internal XmlSchema() { } } public enum XmlSchemaForm { None = 0, Qualified = 1, Unqualified = 2, } } namespace System.Xml.Serialization { public partial interface IXmlSerializable { [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] System.Xml.Schema.XmlSchema GetSchema(); void ReadXml(System.Xml.XmlReader reader); void WriteXml(System.Xml.XmlWriter writer); } [System.AttributeUsageAttribute((System.AttributeTargets)(1036))] public sealed partial class XmlSchemaProviderAttribute : System.Attribute { public XmlSchemaProviderAttribute(string methodName) { } public bool IsAny { get { return default(bool); } set { } } public string MethodName { get { return default(string); } } } }
using AutoFixture; using FluentAssertions; using MediatR; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.Logging; using Moq; using NUnit.Framework; using SFA.DAS.CommitmentsV2.Application.Commands.ResolveDataLocks; using SFA.DAS.CommitmentsV2.Authentication; using SFA.DAS.CommitmentsV2.Data; using SFA.DAS.CommitmentsV2.Domain.Interfaces; using SFA.DAS.CommitmentsV2.Messages.Events; using SFA.DAS.CommitmentsV2.Models; using SFA.DAS.CommitmentsV2.Shared.Interfaces; using SFA.DAS.CommitmentsV2.Types; using SFA.DAS.Testing.Builders; using SFA.DAS.UnitOfWork.Context; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SFA.DAS.CommitmentsV2.UnitTests.Application.Commands { using TestsFixture = AcceptDataLockRequestChangesCommandHandlerTestsFixture; [TestFixture] [Parallelizable] public class AcceptDataLockRequestChangesCommandHandlerTests { private TestsFixture _fixture; [SetUp] public void Arrange() { _fixture = new TestsFixture(); } [Test] public async Task ShouldNotResolveDataLock_WhenNoNewDataLockToProcess() { // Arrange _fixture.SeedData() .WithDataLock(TestsFixture.ApprenticeshipId + 1, 10, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Unknown, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId + 2, 20, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock03) .WithDataLock(TestsFixture.ApprenticeshipId + 3, 30, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 40, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, true, Status.Fail, DataLockErrorCode.Dlock03) .WithDataLock(TestsFixture.ApprenticeshipId, 50, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime.AddMonths(1), 2000, false, TriageStatus.Change, EventStatus.New, false, Status.Pass, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 60, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime.AddMonths(2), 3000, false, TriageStatus.Unknown, EventStatus.New, false, Status.Fail, DataLockErrorCode.Dlock03); // Act await _fixture.Handle(); // Assert _fixture.VerifyDataLockResolved(40, true, "Should not update already resolved datalocks"); _fixture.VerifyDataLockResolved(50, false, "Should not update passed datalocks"); _fixture.VerifyDataLockResolved(60, false, "Should not update datalocks with triage status 'unknown' even when unhandled"); } [Test] public async Task ShouldNotPublishStateChanged_WhenNoNewDataLockToProcess() { // Arrange _fixture.SeedData() .WithDataLock(TestsFixture.ApprenticeshipId, 40, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, true, Status.Fail, DataLockErrorCode.Dlock03) .WithDataLock(TestsFixture.ApprenticeshipId, 50, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime.AddMonths(1), 2000, false, TriageStatus.Change, EventStatus.New, false, Status.Pass, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 60, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime.AddMonths(2), 3000, false, TriageStatus.Unknown, EventStatus.New, false, Status.Fail, DataLockErrorCode.Dlock03); // Act await _fixture.Handle(); // Assert _fixture.VerifyEntityStateChangedEventPublished(Times.Never); } [Test] public async Task ShouldNotPublishDataLockTriage_WhenNoNewDataLockToProcess() { // Arrange _fixture.SeedData() .WithDataLock(TestsFixture.ApprenticeshipId + 1, 10, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Unknown, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId + 2, 20, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock03) .WithDataLock(TestsFixture.ApprenticeshipId + 3, 30, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 40, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, true, Status.Fail, DataLockErrorCode.Dlock03) .WithDataLock(TestsFixture.ApprenticeshipId, 50, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime.AddMonths(1), 2000, false, TriageStatus.Change, EventStatus.New, false, Status.Pass, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 60, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime.AddMonths(2), 3000, false, TriageStatus.Unknown, EventStatus.New, false, Status.Fail, DataLockErrorCode.Dlock03); // Act await _fixture.Handle(); // Assert _fixture.VerifyDataLockTriageApprovedEventPublished(Times.Never); } [Test] public async Task ShouldNotResolveDataLock_WhenHasHadDataLockSuccessAndNewDataLocksAreNotPriceOnly() { // Arrange _fixture.SeedData() .WithHasHadDataLockSuccess(true) .WithDataLock(TestsFixture.ApprenticeshipId + 1, 10, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Unknown, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId + 2, 20, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock03) .WithDataLock(TestsFixture.ApprenticeshipId + 3, 30, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock( TestsFixture.ApprenticeshipId, 40, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Fail, DataLockErrorCode.Dlock07 | DataLockErrorCode.Dlock03); // Act await _fixture.Handle(); // Assert _fixture.VerifyDataLockResolved(40, false, "Should not update price only datalocks when apprenticeship HasHadDataLockSuccess"); } [Test] public async Task ShouldResolveDataLock_WhenHasHadDataLockSuccessAndNewDataLocksAreNotPriceOnlyAndNotExpired() { // Arrange _fixture.SeedData() .WithHasHadDataLockSuccess(true) .WithDataLock(TestsFixture.ApprenticeshipId + 1, 10, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, true, TriageStatus.Unknown, EventStatus.Updated, false, Status.Pass, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId + 2, 20, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, true, TriageStatus.Unknown, EventStatus.Removed, false, Status.Fail, DataLockErrorCode.Dlock03) .WithDataLock(TestsFixture.ApprenticeshipId + 3, 30, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Fail, DataLockErrorCode.Dlock07) .WithDataLock( TestsFixture.ApprenticeshipId, 40, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Fail, DataLockErrorCode.Dlock07); // Act await _fixture.Handle(); // Assert _fixture.VerifyDataLockResolved(40, true, "Should accept Data Locks for apprenticeship When Data Lock is not expired"); } [Test] public async Task ShouldNotPublishStateChanged_WhenHasHadDataLockSuccessAndNewDataLocksAreNotPriceOnly() { // Arrange _fixture.SeedData() .WithHasHadDataLockSuccess(true) .WithDataLock(TestsFixture.ApprenticeshipId + 1, 10, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Unknown, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId + 2, 20, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock03) .WithDataLock(TestsFixture.ApprenticeshipId + 3, 30, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock( TestsFixture.ApprenticeshipId, 40, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Fail, DataLockErrorCode.Dlock07 | DataLockErrorCode.Dlock03); // Act await _fixture.Handle(); // Assert _fixture.VerifyEntityStateChangedEventPublished(Times.Never); } [Test] public async Task ShouldNotPublishDataLockTriage_WhenHasHadDataLockSuccessAndNewDataLocksAreNotPriceOnly() { // Arrange _fixture.SeedData() .WithHasHadDataLockSuccess(true) .WithDataLock(TestsFixture.ApprenticeshipId + 1, 10, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Unknown, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId + 2, 20, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock03) .WithDataLock(TestsFixture.ApprenticeshipId + 3, 30, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock( TestsFixture.ApprenticeshipId, 40, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Fail, DataLockErrorCode.Dlock07 | DataLockErrorCode.Dlock03); // Act await _fixture.Handle(); // Assert _fixture.VerifyDataLockTriageApprovedEventPublished(Times.Never); } [Test] public async Task ShouldResolveDataLock_WhenNotHasHadDataLockSuccessAndNewDataLocksArePriceOnly() { // Arrange _fixture.SeedData() .WithHasHadDataLockSuccess(false) .WithDataLock(TestsFixture.ApprenticeshipId + 1, 10, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Unknown, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId + 2, 20, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock03) .WithDataLock(TestsFixture.ApprenticeshipId + 3, 30, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 40, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Fail, DataLockErrorCode.Dlock07); // Act await _fixture.Handle(); // Assert _fixture.VerifyDataLockResolved(40, true, "Should update price only datalocks when apprenticeship not HasHadDataLockSuccess"); } [Test] public async Task ShouldPublishStateChanged_WhenNotHasHadDataLockSuccessAndNewDataLocksArePriceOnly() { // Arrange _fixture.SeedData() .WithHasHadDataLockSuccess(false) .WithDataLock(TestsFixture.ApprenticeshipId + 1, 10, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Unknown, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId + 2, 20, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock03) .WithDataLock(TestsFixture.ApprenticeshipId + 3, 30, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 40, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Fail, DataLockErrorCode.Dlock07); // Act await _fixture.Handle(); // Assert _fixture.VerifyEntityStateChangedEventPublished(UserAction.TriageDataLocks,()=> Times.Exactly(2)); } [Test] public async Task ShouldPublishDataLockTriage_WhenNotHasHadDataLockSuccessAndNewDataLocksArePriceOnly() { // Arrange _fixture.SeedData() .WithHasHadDataLockSuccess(false) .WithDataLock(TestsFixture.ApprenticeshipId + 1, 10, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Unknown, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId + 2, 20, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock03) .WithDataLock(TestsFixture.ApprenticeshipId + 3, 30, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 40, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Fail, DataLockErrorCode.Dlock07); // Act await _fixture.Handle(); // Assert _fixture.VerifyDataLockTriageApprovedEventPublished(TestsFixture.ApprenticeshipId, TestsFixture.ProxyCurrentDateTime, new PriceEpisode[] { new PriceEpisode { FromDate = TestsFixture.ProxyCurrentDateTime, ToDate = null, Cost = 1000 } }, TestsFixture.TrainingCourseCode100, TestsFixture.ProgrammeType100, Times.Once); } [TestCaseSource(typeof(ShouldUpdatePriceHistoryDataCases))] public async Task ShouldResolveDataLocks(ShouldUpdatePriceHistoryDataCases.Setup setup, ShouldUpdatePriceHistoryDataCases.InputDataLock[] inputDataLocks, ShouldUpdatePriceHistoryDataCases.ExpectedOutput expectedOutput) { // Arrange _fixture.SeedData() .WithHasHadDataLockSuccess(setup.HasHadDataLockSuccess) .WithDataLock(TestsFixture.ApprenticeshipId + 1, 10, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Unknown, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId + 2, 20, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock03) .WithDataLock(TestsFixture.ApprenticeshipId + 3, 30, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07); inputDataLocks.ToList().ForEach(p => _fixture.WithDataLock(p.ApprenticeshipId, p.EventDataLockId, p.IlrTrainingCourseCode, p.IlrEffectiveFromDate, p.IlrTotalCost, p.IsExpired, p.TriageStatus, p.EventStatus, p.IsResolved, p.Status, p.DataLockErrorCode)); // Act await _fixture.Handle(); // Assert expectedOutput.OutputResolvedEventDataLockIds.ToList().ForEach(p => _fixture.VerifyDataLockResolved(p.EventDataLockId, p.IsResolved, p.Because)); } [TestCaseSource(typeof(ShouldUpdatePriceHistoryDataCases))] public async Task ShouldPublishStateChangedEvent(ShouldUpdatePriceHistoryDataCases.Setup setup, ShouldUpdatePriceHistoryDataCases.InputDataLock[] inputDataLocks, ShouldUpdatePriceHistoryDataCases.ExpectedOutput expectedOutput) { // Arrange _fixture.SeedData() .WithHasHadDataLockSuccess(setup.HasHadDataLockSuccess) .WithDataLock(TestsFixture.ApprenticeshipId + 1, 10, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Unknown, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId + 2, 20, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock03) .WithDataLock(TestsFixture.ApprenticeshipId + 3, 30, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07); inputDataLocks.ToList().ForEach(p => _fixture.WithDataLock(p.ApprenticeshipId, p.EventDataLockId, p.IlrTrainingCourseCode, p.IlrEffectiveFromDate, p.IlrTotalCost, p.IsExpired, p.TriageStatus, p.EventStatus, p.IsResolved, p.Status, p.DataLockErrorCode)); // Act await _fixture.Handle(); // Assert _fixture.VerifyEntityStateChangedEventPublished(UserAction.TriageDataLocks, () => Times.Exactly(expectedOutput.OutputPriceHistories.Length + 1)); } [TestCaseSource(typeof(ShouldUpdatePriceHistoryDataCases))] public async Task ShouldPublishDataLockTriage(ShouldUpdatePriceHistoryDataCases.Setup setup, ShouldUpdatePriceHistoryDataCases.InputDataLock[] inputDataLocks, ShouldUpdatePriceHistoryDataCases.ExpectedOutput expectedOutput) { // Arrange _fixture.SeedData() .WithHasHadDataLockSuccess(setup.HasHadDataLockSuccess) .WithDataLock(TestsFixture.ApprenticeshipId + 1, 10, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Unknown, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId + 2, 20, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock03) .WithDataLock(TestsFixture.ApprenticeshipId + 3, 30, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07); inputDataLocks.ToList().ForEach(p => _fixture.WithDataLock(p.ApprenticeshipId, p.EventDataLockId, p.IlrTrainingCourseCode, p.IlrEffectiveFromDate, p.IlrTotalCost, p.IsExpired, p.TriageStatus, p.EventStatus, p.IsResolved, p.Status, p.DataLockErrorCode)); // Act await _fixture.Handle(); // Assert _fixture.VerifyDataLockTriageApprovedEventPublished(TestsFixture.ApprenticeshipId, TestsFixture.ProxyCurrentDateTime, expectedOutput.OutputPriceHistories.ToList().Select(p => new PriceEpisode { FromDate = p.FromDate, ToDate = p.ToDate, Cost = p.Cost }).ToArray(), expectedOutput.CourseCode, expectedOutput.ProgrammeType, Times.Once); } [Test] public async Task ShouldUpdateCourse_WhenNotHasHadDataLockSuccessAndNewDataLocksHasDifferentCourse() { // Arrange _fixture.SeedData() .WithHasHadDataLockSuccess(false) .WithDataLock(TestsFixture.ApprenticeshipId + 1, 10, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Unknown, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId + 2, 20, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock03) .WithDataLock(TestsFixture.ApprenticeshipId + 3, 30, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 40, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, true, Status.Fail, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 41, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime.AddDays(20), 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Fail, DataLockErrorCode.Dlock03); // Act await _fixture.Handle(); // Assert _fixture.ApprenticeshipFromDb.CourseCode.Should().Be(TestsFixture.TrainingCourseCode200, "Course code should update for course data lock when not has had datalock success"); _fixture.ApprenticeshipFromDb.CourseName.Should().Be(TestsFixture.TrainingCourseName200, "Course name should update for course data lock when not has had datalock success"); } [Test] public async Task ShouldResolveDataLocks_WhenNotHasHadDataLockSuccessAndNewDataLocksHasDifferentCourse() { // Arrange _fixture.SeedData() .WithHasHadDataLockSuccess(false) .WithDataLock(TestsFixture.ApprenticeshipId + 1, 10, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Unknown, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId + 2, 20, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock03) .WithDataLock(TestsFixture.ApprenticeshipId + 3, 30, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 40, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, true, Status.Fail, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 41, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime.AddDays(20), 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Fail, DataLockErrorCode.Dlock03); // Act await _fixture.Handle(); // Assert _fixture.VerifyDataLockResolved(41, true, "Course data lock should be resolved"); } [Test] public async Task ShouldPublishStateChanged_WhenNotHasHadDataLockSuccessAndNewDataLocksHasDifferentCourse() { // Arrange _fixture.SeedData() .WithHasHadDataLockSuccess(false) .WithDataLock(TestsFixture.ApprenticeshipId + 1, 10, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Unknown, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId + 2, 20, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock03) .WithDataLock(TestsFixture.ApprenticeshipId + 3, 30, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 40, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, true, Status.Fail, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 41, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime.AddDays(20), 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Fail, DataLockErrorCode.Dlock03); // Act await _fixture.Handle(); // Assert _fixture.VerifyEntityStateChangedEventPublished(UserAction.TriageDataLocks, ()=> Times.Exactly(3)); _fixture.VerifyEntityStateChangedEventPublished(UserAction.UpdateCourse, Times.Once); } [Test] public async Task ShouldPublishStateChanged_WhenNotHasHadDataLockSuccessAndNewDataLocksHasDifferentPrice() { // Arrange _fixture.SeedData(true) .WithHasHadDataLockSuccess(false) .WithDataLock(TestsFixture.ApprenticeshipId, 40, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1500, false, TriageStatus.Change, EventStatus.New, true, Status.Fail, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 41, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime.AddDays(20), 2500, false, TriageStatus.Change, EventStatus.New, false, Status.Fail, DataLockErrorCode.Dlock07); // Act await _fixture.Handle(); // Assert _fixture.VerifyEntityStateChangedEventPublished(UserAction.TriageDataLocks, () => Times.Exactly(3)); _fixture.VerifyEntityStateChangedEventPublished(UserAction.UpdateCourse, Times.Once); } [Test] public async Task ShouldPublishDataLockTriage_WhenNotHasHadDataLockSuccessAndNewDataLocksHasDifferentCourse() { // Arrange _fixture.SeedData() .WithHasHadDataLockSuccess(false) .WithDataLock(TestsFixture.ApprenticeshipId + 1, 10, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Unknown, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId + 2, 20, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock03) .WithDataLock(TestsFixture.ApprenticeshipId + 3, 30, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 40, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, true, Status.Fail, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 41, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime.AddDays(20), 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Fail, DataLockErrorCode.Dlock03); // Act await _fixture.Handle(); // Assert _fixture.VerifyDataLockTriageApprovedEventPublished(TestsFixture.ApprenticeshipId, TestsFixture.ProxyCurrentDateTime, new PriceEpisode[] { new PriceEpisode { FromDate = TestsFixture.ProxyCurrentDateTime, ToDate = TestsFixture.ProxyCurrentDateTime.AddDays(19), Cost = 1000 }, new PriceEpisode { FromDate = TestsFixture.ProxyCurrentDateTime.AddDays(20), ToDate = null, Cost = 1000 } }, TestsFixture.TrainingCourseCode200, TestsFixture.ProgrammeType200, Times.Once); } [Test] public async Task ShouldNotUpdateCourse_WhenHasHadDataLockSuccessAndNewDataLocksHasDifferentCourse() { // Arrange _fixture.SeedData() .WithHasHadDataLockSuccess(true) .WithDataLock(TestsFixture.ApprenticeshipId + 1, 10, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Unknown, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId + 2, 20, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock03) .WithDataLock(TestsFixture.ApprenticeshipId + 3, 30, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 40, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, true, Status.Fail, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 41, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime.AddDays(20), 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Fail, DataLockErrorCode.Dlock03); // Act await _fixture.Handle(); // Assert _fixture.ApprenticeshipFromDb.CourseCode.Should().Be(TestsFixture.TrainingCourseCode100, "Course code should not update for course data lock when has had datalock success"); _fixture.ApprenticeshipFromDb.CourseName.Should().Be(TestsFixture.TrainingCourseName100, "Course name should not update for course data lock when has had datalock success"); } [Test] public async Task ShouldNotResolveDataLocks_WhenHasHadDataLockSuccessAndNewDataLocksHasDifferentCourse() { // Arrange _fixture.SeedData() .WithHasHadDataLockSuccess(true) .WithDataLock(TestsFixture.ApprenticeshipId + 1, 10, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Unknown, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId + 2, 20, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock03) .WithDataLock(TestsFixture.ApprenticeshipId + 3, 30, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 40, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, true, Status.Fail, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 41, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime.AddDays(20), 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Fail, DataLockErrorCode.Dlock03); // Act await _fixture.Handle(); // Assert _fixture.VerifyDataLockResolved(41, false, "Course data lock should not be resolved when had had datalock success"); } [Test] public async Task ShouldNotPublishStateChanged_WhenNotHasHadDataLockSuccessAndNewDataLocksHasDifferentCourse() { // Arrange _fixture.SeedData() .WithHasHadDataLockSuccess(true) .WithDataLock(TestsFixture.ApprenticeshipId + 1, 10, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Unknown, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId + 2, 20, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock03) .WithDataLock(TestsFixture.ApprenticeshipId + 3, 30, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Unknown, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 40, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1000, false, TriageStatus.Change, EventStatus.New, true, Status.Fail, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 41, TestsFixture.TrainingCourseCode200, TestsFixture.ProxyCurrentDateTime.AddDays(20), 1000, false, TriageStatus.Change, EventStatus.New, false, Status.Fail, DataLockErrorCode.Dlock03); // Act await _fixture.Handle(); // Assert _fixture.VerifyEntityStateChangedEventPublished(UserAction.UpdatePriceHistory, Times.Never); _fixture.VerifyEntityStateChangedEventPublished(UserAction.UpdateCourse, Times.Never); } [Test] public async Task ShouldNotDuplicatePriceHistory_WhenMultipleDataLockStatusForSameCostAndFromDate() { // Arrange _fixture.SeedData(withPriceHistory: false) .WithHasHadDataLockSuccess(true) .WithDataLock(TestsFixture.ApprenticeshipId, 10, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime.AddDays(-2), 1000, false, TriageStatus.Change, EventStatus.New, true, Status.Fail, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 11, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1100, false, TriageStatus.Change, EventStatus.New, true, Status.Fail, DataLockErrorCode.Dlock07) .WithDataLock(TestsFixture.ApprenticeshipId, 12, TestsFixture.TrainingCourseCode100, TestsFixture.ProxyCurrentDateTime, 1100, false, TriageStatus.Change, EventStatus.New, false, Status.Fail, DataLockErrorCode.Dlock07); // Act await _fixture.Handle(); // Assert _fixture.VerifyNoDuplicatePriceHistory(TestsFixture.ApprenticeshipId, 2); } public class ShouldUpdatePriceHistoryDataCases : IEnumerable { public IEnumerator GetEnumerator() { // define some datalocks which are pre-existing in all cases var previouslyResolvedPriceOnlyDataLock40 = new InputDataLock { ApprenticeshipId = TestsFixture.ApprenticeshipId, EventDataLockId = 40, IlrTrainingCourseCode = TestsFixture.TrainingCourseCode100, IlrEffectiveFromDate = TestsFixture.ProxyCurrentDateTime.AddDays(10), IlrTotalCost = 1000, IsExpired = false, TriageStatus = TriageStatus.Change, EventStatus = EventStatus.New, IsResolved = true, Status = Status.Fail, DataLockErrorCode = DataLockErrorCode.Dlock07 }; var previouslyResolvedPriceOnlyDataLock41 = new InputDataLock { ApprenticeshipId = TestsFixture.ApprenticeshipId, EventDataLockId = 41, IlrTrainingCourseCode = TestsFixture.TrainingCourseCode100, IlrEffectiveFromDate = TestsFixture.ProxyCurrentDateTime.AddDays(20), IlrTotalCost = 1100, IsExpired = false, TriageStatus = TriageStatus.Change, EventStatus = EventStatus.New, IsResolved = true, Status = Status.Fail, DataLockErrorCode = DataLockErrorCode.Dlock07 }; var passDataLock50 = new InputDataLock { ApprenticeshipId = TestsFixture.ApprenticeshipId, EventDataLockId = 50, IlrTrainingCourseCode = TestsFixture.TrainingCourseCode100, IlrEffectiveFromDate = TestsFixture.ProxyCurrentDateTime.AddDays(30), IlrTotalCost = 1200, IsExpired = false, TriageStatus = TriageStatus.Unknown, EventStatus = EventStatus.New, IsResolved = false, Status = Status.Pass, DataLockErrorCode = DataLockErrorCode.Dlock07 }; var passDataLock51 = new InputDataLock { ApprenticeshipId = TestsFixture.ApprenticeshipId, EventDataLockId = 51, IlrTrainingCourseCode = TestsFixture.TrainingCourseCode100, IlrEffectiveFromDate = TestsFixture.ProxyCurrentDateTime.AddDays(40), IlrTotalCost = 1300, IsExpired = false, TriageStatus = TriageStatus.Unknown, EventStatus = EventStatus.New, IsResolved = true, Status = Status.Pass, DataLockErrorCode = DataLockErrorCode.Dlock07 }; var passDataLock52 = new InputDataLock { ApprenticeshipId = TestsFixture.ApprenticeshipId, EventDataLockId = 52, IlrTrainingCourseCode = TestsFixture.TrainingCourseCode100, IlrEffectiveFromDate = TestsFixture.ProxyCurrentDateTime.AddDays(50), IlrTotalCost = 1400, IsExpired = false, TriageStatus = TriageStatus.Change, EventStatus = EventStatus.New, IsResolved = false, Status = Status.Pass, DataLockErrorCode = DataLockErrorCode.Dlock07 }; var previouslyResolvedPriceOnlyDataLock40PriceHistory = new OutputPriceHistory { FromDate = TestsFixture.ProxyCurrentDateTime.AddDays(10), ToDate = TestsFixture.ProxyCurrentDateTime.AddDays(19), Cost = 1000 }; var previouslyResolvedPriceOnlyDataLock41PriceHistory = new OutputPriceHistory { FromDate = TestsFixture.ProxyCurrentDateTime.AddDays(20), ToDate = TestsFixture.ProxyCurrentDateTime.AddDays(29), Cost = 1100 }; var passDataLock50PriceHistory = new OutputPriceHistory { FromDate = TestsFixture.ProxyCurrentDateTime.AddDays(30), ToDate = TestsFixture.ProxyCurrentDateTime.AddDays(39), Cost = 1200 }; var passDataLock51PriceHistory = new OutputPriceHistory { FromDate = TestsFixture.ProxyCurrentDateTime.AddDays(40), ToDate = TestsFixture.ProxyCurrentDateTime.AddDays(49), Cost = 1300 }; var passDataLock52PriceHistory = new OutputPriceHistory { FromDate = TestsFixture.ProxyCurrentDateTime.AddDays(50), ToDate = TestsFixture.ProxyCurrentDateTime.AddDays(59), Cost = 1400 }; // has had datalock success will not include course datalocks in price history yield return new object[] { new Setup { ApprenticeshipId = TestsFixture.ApprenticeshipId, HasHadDataLockSuccess = true }, new InputDataLock[] { previouslyResolvedPriceOnlyDataLock40, previouslyResolvedPriceOnlyDataLock41, passDataLock50, passDataLock51, passDataLock52, // price datalock 60 will be included in the price history new InputDataLock { ApprenticeshipId = TestsFixture.ApprenticeshipId, EventDataLockId = 60, IlrTrainingCourseCode = TestsFixture.TrainingCourseCode100, IlrEffectiveFromDate = TestsFixture.ProxyCurrentDateTime.AddDays(60), IlrTotalCost = 1500, IsExpired = false, TriageStatus = TriageStatus.Change, EventStatus = EventStatus.New, IsResolved = false, Status = Status.Unknown, DataLockErrorCode = DataLockErrorCode.Dlock07 }, // course datalock 61 will not be included in the price history new InputDataLock { ApprenticeshipId = TestsFixture.ApprenticeshipId, EventDataLockId = 61, IlrTrainingCourseCode = TestsFixture.TrainingCourseCode200, IlrEffectiveFromDate = TestsFixture.ProxyCurrentDateTime.AddDays(70), IlrTotalCost = 1500, IsExpired = false, TriageStatus = TriageStatus.Change, EventStatus = EventStatus.New, IsResolved = false, Status = Status.Unknown, DataLockErrorCode = DataLockErrorCode.Dlock03 }, // price datalock 62 will be included in the price history new InputDataLock { ApprenticeshipId = TestsFixture.ApprenticeshipId, EventDataLockId = 62, IlrTrainingCourseCode = TestsFixture.TrainingCourseCode100, IlrEffectiveFromDate = TestsFixture.ProxyCurrentDateTime.AddDays(80), IlrTotalCost = 1700, IsExpired = false, TriageStatus = TriageStatus.Change, EventStatus = EventStatus.New, IsResolved = false, Status = Status.Unknown, DataLockErrorCode = DataLockErrorCode.Dlock07 }, }, new ExpectedOutput { OutputResolvedEventDataLockIds = new OutputResolvedEventDataLockId[] { new OutputResolvedEventDataLockId { EventDataLockId = 60, IsResolved = true, Because = "New price data lock should always be resolved"}, new OutputResolvedEventDataLockId { EventDataLockId = 61, IsResolved = false, Because = "New course data lock should not be resolved when HadHadDataLockSuccess is true"}, new OutputResolvedEventDataLockId { EventDataLockId = 62, IsResolved = true, Because = "New price data lock should always be resolved"} }, OutputPriceHistories = new OutputPriceHistory[] { previouslyResolvedPriceOnlyDataLock40PriceHistory, previouslyResolvedPriceOnlyDataLock41PriceHistory, passDataLock50PriceHistory, passDataLock51PriceHistory, passDataLock52PriceHistory, new OutputPriceHistory { FromDate = TestsFixture.ProxyCurrentDateTime.AddDays(60), ToDate = TestsFixture.ProxyCurrentDateTime.AddDays(79), Cost = 1500 }, new OutputPriceHistory { FromDate = TestsFixture.ProxyCurrentDateTime.AddDays(80), ToDate = null, Cost = 1700 } }, CourseCode = TestsFixture.TrainingCourseCode100, ProgrammeType = TestsFixture.ProgrammeType100 } }; // has had datalock success will not include course/price datalocks in price history yield return new object[] { new Setup { ApprenticeshipId = TestsFixture.ApprenticeshipId, HasHadDataLockSuccess = true }, new InputDataLock[] { previouslyResolvedPriceOnlyDataLock40, previouslyResolvedPriceOnlyDataLock41, passDataLock50, passDataLock51, passDataLock52, // price datalock 60 will be included in the price history new InputDataLock { ApprenticeshipId = TestsFixture.ApprenticeshipId, EventDataLockId = 60, IlrTrainingCourseCode = TestsFixture.TrainingCourseCode100, IlrEffectiveFromDate = TestsFixture.ProxyCurrentDateTime.AddDays(60), IlrTotalCost = 1500, IsExpired = false, TriageStatus = TriageStatus.Change, EventStatus = EventStatus.New, IsResolved = false, Status = Status.Unknown, DataLockErrorCode = DataLockErrorCode.Dlock07 }, // course/price datalock 61 will not be included in the price history new InputDataLock { ApprenticeshipId = TestsFixture.ApprenticeshipId, EventDataLockId = 61, IlrTrainingCourseCode = TestsFixture.TrainingCourseCode200, IlrEffectiveFromDate = TestsFixture.ProxyCurrentDateTime.AddDays(70), IlrTotalCost = 1600, IsExpired = false, TriageStatus = TriageStatus.Change, EventStatus = EventStatus.New, IsResolved = false, Status = Status.Unknown, DataLockErrorCode = DataLockErrorCode.Dlock03 | DataLockErrorCode.Dlock07 }, // price datalock 62 will be included in the price history new InputDataLock { ApprenticeshipId = TestsFixture.ApprenticeshipId, EventDataLockId = 62, IlrTrainingCourseCode = TestsFixture.TrainingCourseCode100, IlrEffectiveFromDate = TestsFixture.ProxyCurrentDateTime.AddDays(80), IlrTotalCost = 1700, IsExpired = false, TriageStatus = TriageStatus.Change, EventStatus = EventStatus.New, IsResolved = false, Status = Status.Unknown, DataLockErrorCode = DataLockErrorCode.Dlock07 }, }, new ExpectedOutput { OutputResolvedEventDataLockIds = new OutputResolvedEventDataLockId[] { new OutputResolvedEventDataLockId { EventDataLockId = 60, IsResolved = true, Because = "New price data lock should always be resolved"}, new OutputResolvedEventDataLockId { EventDataLockId = 61, IsResolved = false, Because = "New course/price data lock should not be resolved when HadHadDataLockSuccess is true"}, new OutputResolvedEventDataLockId { EventDataLockId = 62, IsResolved = true, Because = "New price data lock should always be resolved"} }, OutputPriceHistories = new OutputPriceHistory[] { previouslyResolvedPriceOnlyDataLock40PriceHistory, previouslyResolvedPriceOnlyDataLock41PriceHistory, passDataLock50PriceHistory, passDataLock51PriceHistory, passDataLock52PriceHistory, new OutputPriceHistory { FromDate = TestsFixture.ProxyCurrentDateTime.AddDays(60), ToDate = TestsFixture.ProxyCurrentDateTime.AddDays(79), Cost = 1500 }, new OutputPriceHistory { FromDate = TestsFixture.ProxyCurrentDateTime.AddDays(80), ToDate = null, Cost = 1700 } }, CourseCode = TestsFixture.TrainingCourseCode100, ProgrammeType = TestsFixture.ProgrammeType100 } }; // not has had datalock success will include course/price datalocks yield return new object[] { new Setup { ApprenticeshipId = TestsFixture.ApprenticeshipId, HasHadDataLockSuccess = false }, new InputDataLock[] { previouslyResolvedPriceOnlyDataLock40, previouslyResolvedPriceOnlyDataLock41, passDataLock50, passDataLock51, passDataLock52, // price datalock 60 will be included in the price history new InputDataLock { ApprenticeshipId = TestsFixture.ApprenticeshipId, EventDataLockId = 60, IlrTrainingCourseCode = TestsFixture.TrainingCourseCode100, IlrEffectiveFromDate = TestsFixture.ProxyCurrentDateTime.AddDays(60), IlrTotalCost = 1500, IsExpired = false, TriageStatus = TriageStatus.Change, EventStatus = EventStatus.New, IsResolved = false, Status = Status.Unknown, DataLockErrorCode = DataLockErrorCode.Dlock07 }, // course/price datalock 61 will be included in the price history new InputDataLock { ApprenticeshipId = TestsFixture.ApprenticeshipId, EventDataLockId = 61, IlrTrainingCourseCode = TestsFixture.TrainingCourseCode200, IlrEffectiveFromDate = TestsFixture.ProxyCurrentDateTime.AddDays(70), IlrTotalCost = 1600, IsExpired = false, TriageStatus = TriageStatus.Change, EventStatus = EventStatus.New, IsResolved = false, Status = Status.Unknown, DataLockErrorCode = DataLockErrorCode.Dlock03 | DataLockErrorCode.Dlock07 }, // price datalock 62 will be included in the price history new InputDataLock { ApprenticeshipId = TestsFixture.ApprenticeshipId, EventDataLockId = 62, IlrTrainingCourseCode = TestsFixture.TrainingCourseCode100, IlrEffectiveFromDate = TestsFixture.ProxyCurrentDateTime.AddDays(80), IlrTotalCost = 1700, IsExpired = false, TriageStatus = TriageStatus.Change, EventStatus = EventStatus.New, IsResolved = false, Status = Status.Unknown, DataLockErrorCode = DataLockErrorCode.Dlock07 }, }, new ExpectedOutput { OutputResolvedEventDataLockIds = new OutputResolvedEventDataLockId[] { new OutputResolvedEventDataLockId { EventDataLockId = 60, IsResolved = true, Because = "New price data lock should always be resolved"}, new OutputResolvedEventDataLockId { EventDataLockId = 61, IsResolved = true, Because = "New course/price data lock should be resolved when HadHadDataLockSuccess is false"}, new OutputResolvedEventDataLockId { EventDataLockId = 62, IsResolved = true, Because = "New price data lock should always be resolved"} }, OutputPriceHistories = new OutputPriceHistory[] { previouslyResolvedPriceOnlyDataLock40PriceHistory, previouslyResolvedPriceOnlyDataLock41PriceHistory, passDataLock50PriceHistory, passDataLock51PriceHistory, passDataLock52PriceHistory, new OutputPriceHistory { FromDate = TestsFixture.ProxyCurrentDateTime.AddDays(60), ToDate = TestsFixture.ProxyCurrentDateTime.AddDays(69), Cost = 1500 }, new OutputPriceHistory { FromDate = TestsFixture.ProxyCurrentDateTime.AddDays(70), ToDate = TestsFixture.ProxyCurrentDateTime.AddDays(79), Cost = 1600 }, new OutputPriceHistory { FromDate = TestsFixture.ProxyCurrentDateTime.AddDays(80), ToDate = null, Cost = 1700 } }, CourseCode = TestsFixture.TrainingCourseCode200, ProgrammeType = TestsFixture.ProgrammeType200 } }; } public class Setup { public long ApprenticeshipId { get; set; } public bool HasHadDataLockSuccess { get; set; } } public class InputDataLock { public long ApprenticeshipId { get; set; } public long EventDataLockId { get; set; } public string IlrTrainingCourseCode { get; set; } public DateTime IlrEffectiveFromDate { get; set; } public decimal IlrTotalCost { get; set; } public bool IsExpired { get; set; } public TriageStatus TriageStatus { get; set; } public EventStatus EventStatus { get; set; } public bool IsResolved { get; set; } public Status Status { get; set; } public DataLockErrorCode DataLockErrorCode { get; set; } } public class ExpectedOutput { public OutputResolvedEventDataLockId[] OutputResolvedEventDataLockIds { get; set; } public OutputPriceHistory[] OutputPriceHistories { get; set; } public string CourseCode { get; set; } public ProgrammeType ProgrammeType { get; set; } } public class OutputResolvedEventDataLockId { public long EventDataLockId { get; set; } public bool IsResolved { get; set; } public string Because { get; set; } } public class OutputPriceHistory { public DateTime FromDate { get; set; } public DateTime? ToDate { get; set; } public decimal Cost { get; set; } } } } public class AcceptDataLockRequestChangesCommandHandlerTestsFixture { public static long ApprenticeshipId = 12; public static string TrainingCourseCode100 = "100"; public static string TrainingCourseName100 = "100 Test Name"; public static ProgrammeType ProgrammeType100 = ProgrammeType.Standard; public static string TrainingCourseCode200 = "200"; public static string TrainingCourseName200 = "200 Test Name"; public static ProgrammeType ProgrammeType200 = ProgrammeType.Standard; public static DateTime ProxyCurrentDateTime = new DateTime(2020, 1, 1); public Fixture AutoFixture { get; set; } public AcceptDataLocksRequestChangesCommand Command { get; set; } public ProviderCommitmentsDbContext Db { get; set; } public IRequestHandler<AcceptDataLocksRequestChangesCommand> Handler { get; set; } public UserInfo UserInfo { get; } public Mock<IAuthenticationService> AuthenticationService; public Mock<ICurrentDateTime> CurrentDateTimeService; public Mock<ITrainingProgrammeLookup> TrainingProgrammeLookup; public UnitOfWorkContext UnitOfWorkContext { get; set; } public Apprenticeship ApprenticeshipFromDb => Db.Apprenticeships.First(x => x.Id == ApprenticeshipId); public PriceHistory PriceHistoryFromDb => Db.Apprenticeships.First(x => x.Id == ApprenticeshipId).PriceHistory.First(); public AcceptDataLockRequestChangesCommandHandlerTestsFixture() { AutoFixture = new Fixture(); AutoFixture.Behaviors.Add(new OmitOnRecursionBehavior()); AutoFixture.Customizations.Add(new ModelSpecimenBuilder()); UnitOfWorkContext = new UnitOfWorkContext(); Db = new ProviderCommitmentsDbContext(new DbContextOptionsBuilder<ProviderCommitmentsDbContext>() .UseInMemoryDatabase(Guid.NewGuid().ToString()) .Options); AuthenticationService = new Mock<IAuthenticationService>(); AuthenticationService.Setup(x => x.GetUserParty()).Returns(() => Party.Employer); CurrentDateTimeService = new Mock<ICurrentDateTime>(); CurrentDateTimeService.Setup(x => x.UtcNow).Returns(ProxyCurrentDateTime); TrainingProgrammeLookup = new Mock<ITrainingProgrammeLookup>(); TrainingProgrammeLookup.Setup(x => x.GetTrainingProgramme(TrainingCourseCode100)) .ReturnsAsync(new CommitmentsV2.Domain.Entities.TrainingProgramme(TrainingCourseCode100, TrainingCourseName100, ProgrammeType.Standard, DateTime.Now, DateTime.Now)); TrainingProgrammeLookup.Setup(x => x.GetTrainingProgramme(TrainingCourseCode200)) .ReturnsAsync(new CommitmentsV2.Domain.Entities.TrainingProgramme(TrainingCourseCode200, TrainingCourseName200, ProgrammeType.Standard, DateTime.Now, DateTime.Now)); UserInfo = AutoFixture.Create<UserInfo>(); Command = new AcceptDataLocksRequestChangesCommand(ApprenticeshipId, UserInfo); Handler = new AcceptDataLocksRequestChangesCommandHandler( new Lazy<ProviderCommitmentsDbContext>(() => Db), CurrentDateTimeService.Object, TrainingProgrammeLookup.Object, Mock.Of<ILogger<AcceptDataLocksRequestChangesCommandHandler>>()); } public async Task Handle() { await Handler.Handle(Command, default); // this call is part of the DAS.SFA.UnitOfWork.Context.UnitOfWorkContext middleware in the API await Db.SaveChangesAsync(); } public AcceptDataLockRequestChangesCommandHandlerTestsFixture SeedData(bool withPriceHistory = true) { var accountLegalEntityDetails = new AccountLegalEntity() .Set(c => c.Id, 444); Db.AccountLegalEntities.Add(accountLegalEntityDetails); var cohortDetails = new Cohort() .Set(c => c.Id, 111) .Set(c => c.EmployerAccountId, 222) .Set(c => c.ProviderId, 333) .Set(c => c.AccountLegalEntityId, accountLegalEntityDetails.Id); Db.Cohorts.Add(cohortDetails); var apprenticeshipDetails = AutoFixture.Build<CommitmentsV2.Models.Apprenticeship>() .With(s => s.Id, ApprenticeshipId) .With(s => s.CourseCode, TrainingCourseCode100) .With(s => s.CourseName, TrainingCourseName100) .With(s => s.ProgrammeType, ProgrammeType.Standard) .With(s => s.PaymentStatus, PaymentStatus.Completed) .With(s => s.EndDate, DateTime.UtcNow) .With(s => s.CompletionDate, DateTime.UtcNow.AddDays(10)) .With(s => s.StartDate, DateTime.UtcNow.AddDays(-10)) .Without(s => s.Cohort) .Without(s => s.PriceHistory) .Without(s => s.ApprenticeshipUpdate) .Without(s => s.DataLockStatus) .Without(s => s.EpaOrg) .Without(s => s.Continuation) .Without(s => s.PreviousApprenticeship) .Create(); // if set above in autofixture build throws exception for some obscure reason apprenticeshipDetails.CommitmentId = cohortDetails.Id; Db.Apprenticeships.Add(apprenticeshipDetails); Db.SaveChanges(); if (withPriceHistory) { var priceHistoryDetails = new List<PriceHistory>() { new PriceHistory { FromDate = DateTime.Now, ToDate = null, Cost = 10000, ApprenticeshipId = apprenticeshipDetails.Id } }; Db.PriceHistory.AddRange(priceHistoryDetails); } Db.SaveChanges(); return this; } public AcceptDataLockRequestChangesCommandHandlerTestsFixture WithHasHadDataLockSuccess(bool hasHadDataLockSuccess) { var apprenticeship = Db.Apprenticeships.Single(p => p.Id == ApprenticeshipId); apprenticeship.HasHadDataLockSuccess = hasHadDataLockSuccess; Db.SaveChanges(); return this; } public AcceptDataLockRequestChangesCommandHandlerTestsFixture WithDataLock(long apprenticeshipId, long eventDataLockId, string ilrTrainingCourseCode, DateTime ilrEffectiveFromDate, decimal ilrTotalCost, bool isExpired, TriageStatus triageStatus, EventStatus eventStatus, bool isResolved, Status status, DataLockErrorCode dataLockErrorCode) { var dataLockStatus = AutoFixture .Build<DataLockStatus>() .With(p => p.ApprenticeshipId, apprenticeshipId) .With(p => p.DataLockEventId, eventDataLockId) .With(p => p.IlrTrainingCourseCode, ilrTrainingCourseCode) .With(p => p.IlrEffectiveFromDate, ilrEffectiveFromDate) .With(p => p.IlrTotalCost, ilrTotalCost) .With(p => p.IsExpired, isExpired) .With(p => p.TriageStatus, triageStatus) .With(p => p.EventStatus, eventStatus) .With(p => p.IsResolved, isResolved) .With(p => p.Status, status) .With(p => p.ErrorCode, dataLockErrorCode) .Without(p => p.Apprenticeship) .Without(p => p.ApprenticeshipUpdate) .Create(); Db.DataLocks.Add(dataLockStatus); Db.SaveChanges(); return this; } public void VerifyNoDuplicatePriceHistory(long apprenticeshipId, int count) { Db.PriceHistory.Count().Should().Be(count); Db.PriceHistory .Where(ph => ph.ApprenticeshipId == apprenticeshipId) .GroupBy(ph => new {ph.Cost, ph.FromDate}) .Select(grp => grp.Count()) .Any(grp => grp > 1) .Should() .BeFalse(); } public void VerifyDataLockResolved(long dataLockEventId, bool isResolved, string because) { Db.DataLocks .Single(p => p.DataLockEventId == dataLockEventId) .IsResolved .Should() .Be(isResolved, because); } public void VerifyEntityStateChangedEventPublished(Func<Times> times) { times().Deconstruct(out int expectedFrom, out int expectedTo); UnitOfWorkContext .GetEvents() .OfType<EntityStateChangedEvent>() .Count() .Should() .Be(expectedFrom); } public void VerifyEntityStateChangedEventPublished(UserAction userAction, Func<Times> times) { times().Deconstruct(out int expectedFrom, out int expectedTo); UnitOfWorkContext .GetEvents() .OfType<EntityStateChangedEvent>() .Where(p => p.StateChangeType == userAction) .Count() .Should() .Be(expectedFrom); } public void VerifyDataLockTriageApprovedEventPublished(Func<Times> times) { times().Deconstruct(out int expectedFrom, out int expectedTo); UnitOfWorkContext .GetEvents() .OfType<DataLockTriageApprovedEvent>() .Count() .Should() .Be(expectedFrom); } public void VerifyDataLockTriageApprovedEventPublished(long apprenticeshipId, DateTime approvedOn, PriceEpisode[] priceEpisodes, string trainingCode, ProgrammeType trainingType, Func<Times> times) { times().Deconstruct(out int expectedFrom, out int expectedTo); var events = UnitOfWorkContext .GetEvents() .OfType<DataLockTriageApprovedEvent>(); events .Count() .Should() .Be(expectedFrom); events.ToList().ForEach(p => { p.Should().BeEquivalentTo(new DataLockTriageApprovedEvent() { ApprenticeshipId = apprenticeshipId, ApprovedOn = approvedOn, PriceEpisodes = priceEpisodes, TrainingCode = trainingCode, TrainingType = trainingType }); }); } } }
/* * Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying * LICENSE file. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.IO; using System.Threading; using AdoNetTest.BIN.Configuration; using AdoNetTest.Logger; using Pivotal.Data.GemFireXD; namespace AdoNetTest.BIN { /// <summary> /// Automates the test initialization, execution, and cleanup /// </summary> public class GFXDTestRunner { /// <summary> /// Test event & delegate /// </summary> public delegate void TestEventHandler(TestEventArgs e); public static event TestEventHandler TestEvent; /// <summary> /// Static member properties /// </summary> private static Logger.Logger logger; private object tLocker = new object(); private static object lLocker = new object(); public static int TestCount = 0; public static int ConnCount = 0; /// <summary> /// Instance members /// </summary> private ManualResetEvent resetEvent; private bool runContinuously; private bool interrupted; private string testname; public GFXDTestRunner() { this.resetEvent = new ManualResetEvent(false); this.runContinuously = false; this.interrupted = false; if (logger != null) logger.Close(); //logger = new Logger.Logger(GFXDConfigManager.GetClientSetting("logDir"), // typeof(GFXDTestRunner).FullName + ".log"); logger = new Logger.Logger(Environment.GetEnvironmentVariable("GFXDADOOUTDIR"), typeof(GFXDTestRunner).FullName + ".log"); } public GFXDTestRunner(bool runContinuously) : this() { this.runContinuously = runContinuously; } public GFXDTestRunner(string testname) : this() { this.testname = testname; } public void Interrupt() { interrupted = true; } public void SetConfigFile(String configXML) { GFXDConfigManager.SetConfigFile(configXML); } public static List<string> GetTestList() { List<string> testlist = new List<string>(); try { Assembly assembly = Assembly.GetExecutingAssembly(); foreach (Type type in assembly.GetTypes()) { if (type.IsSubclassOf(typeof(GFXDTest))) { testlist.Add(type.FullName); } } } catch (Exception e) { Log(DbHelper.GetExceptionDetails(e, new StringBuilder()).ToString()); OnTestEvent(new TestEventArgs(string.Empty, string.Empty, string.Empty, "Encountered exception in GFXDTestRunner.GetTestList(). Check log for detail")); } return testlist; } public void RunOne() { try { Initialize(); Assembly assembly = Assembly.GetExecutingAssembly(); GFXDTest test = null; foreach (Type type in assembly.GetTypes()) { if (type.IsSubclassOf(typeof(GFXDTest)) && type.FullName.Equals(testname)) { test = (GFXDTest)Activator.CreateInstance(type, resetEvent); } } OnTestEvent(new TestEventArgs(test.GetType().FullName + " Queued")); ThreadPool.QueueUserWorkItem(test.Run, tLocker); lock (tLocker) { TestCount += 1; } Thread.Sleep(1000); } catch (Exception e) { Log(DbHelper.GetExceptionDetails(e, new StringBuilder()).ToString()); OnTestEvent(new TestEventArgs(string.Empty, string.Empty, string.Empty, "Encountered exception in GFXDTestRunner.RunOne(). Check log for detail")); } finally { try { Cleanup(); } catch (Exception e) { Log(DbHelper.GetExceptionDetails(e, new StringBuilder()).ToString()); OnTestEvent(new TestEventArgs(string.Empty, string.Empty, string.Empty, "Encountered exception in GFXDTestRunner.Cleanup(). Check log for detail")); } } OnTestEvent(new TestEventArgs(string.Empty, string.Empty, string.Empty, "Done")); } /// <summary> /// Entry point to automated test run /// </summary> public void Run() { try { Initialize(); Assembly assembly = Assembly.GetExecutingAssembly(); do { foreach (Type type in assembly.GetTypes()) { if (interrupted) { runContinuously = false; break; } if (type.IsSubclassOf(typeof(GFXDTest))) { GFXDTest test = (GFXDTest)Activator.CreateInstance(type, resetEvent); OnTestEvent(new TestEventArgs(test.GetType().FullName + " Queued")); ThreadPool.QueueUserWorkItem(test.Run, tLocker); lock (tLocker) { TestCount += 1; } Thread.Sleep(1000); } } while (TestCount > 0) { resetEvent.WaitOne(); } Thread.Sleep(1000); } while (runContinuously); } catch (Exception e) { Log(DbHelper.GetExceptionDetails(e, new StringBuilder()).ToString()); OnTestEvent(new TestEventArgs(string.Empty, string.Empty, string.Empty, "Encounter exception in EsqlTestRunner.Run(). Check log for detail")); } finally { try { Cleanup(); } catch (Exception e) { Log(DbHelper.GetExceptionDetails(e, new StringBuilder()).ToString()); OnTestEvent(new TestEventArgs(string.Empty, string.Empty, string.Empty, "Encounter exception in EsqlTestRunner.Cleanup(). Check log for detail")); } } OnTestEvent(new TestEventArgs(string.Empty, string.Empty, string.Empty, "Done")); } public static void OnTestEvent(TestEventArgs e) { if(TestEvent != null) TestEvent(e); Log(String.Format("{0}", e.ToString())); } private void Initialize() { OnTestEvent(new TestEventArgs(string.Empty, string.Empty, string.Empty, "Initializing... please wait")); DbHelper.Initialize(); } private void Cleanup() { OnTestEvent(new TestEventArgs(string.Empty, string.Empty, string.Empty, "Cleaning up... please wait")); DbHelper.Cleanup(); } private static void Log(String msg) { lock(lLocker) { logger.Write(msg); } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: A1008Response.txt #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.ProtocolBuffers; using pbc = global::Google.ProtocolBuffers.Collections; using pbd = global::Google.ProtocolBuffers.Descriptors; using scg = global::System.Collections.Generic; namespace DolphinServer.ProtoEntity { namespace Proto { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class A1008Response { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_A1008Response__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::DolphinServer.ProtoEntity.A1008Response, global::DolphinServer.ProtoEntity.A1008Response.Builder> internal__static_A1008Response__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static A1008Response() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChFBMTAwOFJlc3BvbnNlLnR4dCJhCg1BMTAwOFJlc3BvbnNlEhEKCUVycm9y", "SW5mbxgBIAEoCRIRCglFcnJvckNvZGUYAiABKAUSDAoEQ2FyZBgDIAEoBRIL", "CgNVaWQYBCABKAkSDwoHTW9kQ2FyZBgFIAEoBUIcqgIZRG9scGhpblNlcnZl", "ci5Qcm90b0VudGl0eQ==")); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_A1008Response__Descriptor = Descriptor.MessageTypes[0]; internal__static_A1008Response__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::DolphinServer.ProtoEntity.A1008Response, global::DolphinServer.ProtoEntity.A1008Response.Builder>(internal__static_A1008Response__Descriptor, new string[] { "ErrorInfo", "ErrorCode", "Card", "Uid", "ModCard", }); pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance(); RegisterAllExtensions(registry); return registry; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { }, assigner); } #endregion } } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class A1008Response : pb::GeneratedMessage<A1008Response, A1008Response.Builder> { private A1008Response() { } private static readonly A1008Response defaultInstance = new A1008Response().MakeReadOnly(); private static readonly string[] _a1008ResponseFieldNames = new string[] { "Card", "ErrorCode", "ErrorInfo", "ModCard", "Uid" }; private static readonly uint[] _a1008ResponseFieldTags = new uint[] { 24, 16, 10, 40, 34 }; public static A1008Response DefaultInstance { get { return defaultInstance; } } public override A1008Response DefaultInstanceForType { get { return DefaultInstance; } } protected override A1008Response ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::DolphinServer.ProtoEntity.Proto.A1008Response.internal__static_A1008Response__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<A1008Response, A1008Response.Builder> InternalFieldAccessors { get { return global::DolphinServer.ProtoEntity.Proto.A1008Response.internal__static_A1008Response__FieldAccessorTable; } } public const int ErrorInfoFieldNumber = 1; private bool hasErrorInfo; private string errorInfo_ = ""; public bool HasErrorInfo { get { return hasErrorInfo; } } public string ErrorInfo { get { return errorInfo_; } } public const int ErrorCodeFieldNumber = 2; private bool hasErrorCode; private int errorCode_; public bool HasErrorCode { get { return hasErrorCode; } } public int ErrorCode { get { return errorCode_; } } public const int CardFieldNumber = 3; private bool hasCard; private int card_; public bool HasCard { get { return hasCard; } } public int Card { get { return card_; } } public const int UidFieldNumber = 4; private bool hasUid; private string uid_ = ""; public bool HasUid { get { return hasUid; } } public string Uid { get { return uid_; } } public const int ModCardFieldNumber = 5; private bool hasModCard; private int modCard_; public bool HasModCard { get { return hasModCard; } } public int ModCard { get { return modCard_; } } public override bool IsInitialized { get { return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _a1008ResponseFieldNames; if (hasErrorInfo) { output.WriteString(1, field_names[2], ErrorInfo); } if (hasErrorCode) { output.WriteInt32(2, field_names[1], ErrorCode); } if (hasCard) { output.WriteInt32(3, field_names[0], Card); } if (hasUid) { output.WriteString(4, field_names[4], Uid); } if (hasModCard) { output.WriteInt32(5, field_names[3], ModCard); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasErrorInfo) { size += pb::CodedOutputStream.ComputeStringSize(1, ErrorInfo); } if (hasErrorCode) { size += pb::CodedOutputStream.ComputeInt32Size(2, ErrorCode); } if (hasCard) { size += pb::CodedOutputStream.ComputeInt32Size(3, Card); } if (hasUid) { size += pb::CodedOutputStream.ComputeStringSize(4, Uid); } if (hasModCard) { size += pb::CodedOutputStream.ComputeInt32Size(5, ModCard); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static A1008Response ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static A1008Response ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static A1008Response ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static A1008Response ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static A1008Response ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static A1008Response ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static A1008Response ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static A1008Response ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static A1008Response ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static A1008Response ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private A1008Response MakeReadOnly() { return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(A1008Response prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<A1008Response, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(A1008Response cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private A1008Response result; private A1008Response PrepareBuilder() { if (resultIsReadOnly) { A1008Response original = result; result = new A1008Response(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override A1008Response MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::DolphinServer.ProtoEntity.A1008Response.Descriptor; } } public override A1008Response DefaultInstanceForType { get { return global::DolphinServer.ProtoEntity.A1008Response.DefaultInstance; } } public override A1008Response BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is A1008Response) { return MergeFrom((A1008Response) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(A1008Response other) { if (other == global::DolphinServer.ProtoEntity.A1008Response.DefaultInstance) return this; PrepareBuilder(); if (other.HasErrorInfo) { ErrorInfo = other.ErrorInfo; } if (other.HasErrorCode) { ErrorCode = other.ErrorCode; } if (other.HasCard) { Card = other.Card; } if (other.HasUid) { Uid = other.Uid; } if (other.HasModCard) { ModCard = other.ModCard; } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_a1008ResponseFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _a1008ResponseFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 10: { result.hasErrorInfo = input.ReadString(ref result.errorInfo_); break; } case 16: { result.hasErrorCode = input.ReadInt32(ref result.errorCode_); break; } case 24: { result.hasCard = input.ReadInt32(ref result.card_); break; } case 34: { result.hasUid = input.ReadString(ref result.uid_); break; } case 40: { result.hasModCard = input.ReadInt32(ref result.modCard_); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasErrorInfo { get { return result.hasErrorInfo; } } public string ErrorInfo { get { return result.ErrorInfo; } set { SetErrorInfo(value); } } public Builder SetErrorInfo(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasErrorInfo = true; result.errorInfo_ = value; return this; } public Builder ClearErrorInfo() { PrepareBuilder(); result.hasErrorInfo = false; result.errorInfo_ = ""; return this; } public bool HasErrorCode { get { return result.hasErrorCode; } } public int ErrorCode { get { return result.ErrorCode; } set { SetErrorCode(value); } } public Builder SetErrorCode(int value) { PrepareBuilder(); result.hasErrorCode = true; result.errorCode_ = value; return this; } public Builder ClearErrorCode() { PrepareBuilder(); result.hasErrorCode = false; result.errorCode_ = 0; return this; } public bool HasCard { get { return result.hasCard; } } public int Card { get { return result.Card; } set { SetCard(value); } } public Builder SetCard(int value) { PrepareBuilder(); result.hasCard = true; result.card_ = value; return this; } public Builder ClearCard() { PrepareBuilder(); result.hasCard = false; result.card_ = 0; return this; } public bool HasUid { get { return result.hasUid; } } public string Uid { get { return result.Uid; } set { SetUid(value); } } public Builder SetUid(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasUid = true; result.uid_ = value; return this; } public Builder ClearUid() { PrepareBuilder(); result.hasUid = false; result.uid_ = ""; return this; } public bool HasModCard { get { return result.hasModCard; } } public int ModCard { get { return result.ModCard; } set { SetModCard(value); } } public Builder SetModCard(int value) { PrepareBuilder(); result.hasModCard = true; result.modCard_ = value; return this; } public Builder ClearModCard() { PrepareBuilder(); result.hasModCard = false; result.modCard_ = 0; return this; } } static A1008Response() { object.ReferenceEquals(global::DolphinServer.ProtoEntity.Proto.A1008Response.Descriptor, null); } } #endregion } #endregion Designer generated code
/* * Copyright (c) .NET Foundation and Contributors * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * https://github.com/piranhacms/piranha.core * */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Dynamic; using System.Linq; using System.Threading.Tasks; using Piranha.Extend; using Piranha.Extend.Fields; using Piranha.Manager.Extensions; using Piranha.Models; using Piranha.Manager.Models; using Piranha.Manager.Models.Content; using Piranha.Services; namespace Piranha.Manager.Services { public class PostService { private readonly IApi _api; private readonly IContentFactory _factory; public PostService(IApi api, IContentFactory factory) { _api = api; _factory = factory; } public async Task<PostModalModel> GetArchiveMap(Guid? siteId, Guid? archiveId) { var model = new PostModalModel(); // Get default site if none is selected if (!siteId.HasValue) { var site = await _api.Sites.GetDefaultAsync(); if (site != null) { siteId = site.Id; } } model.SiteId = siteId.Value; // Get the sites available model.Sites = (await _api.Sites.GetAllAsync()) .Select(s => new PostModalModel.SiteItem { Id = s.Id, Title = s.Title }) .OrderBy(s => s.Title) .ToList(); // Get the current site title var currentSite = model.Sites.FirstOrDefault(s => s.Id == siteId.Value); if (currentSite != null) { model.SiteTitle = currentSite.Title; } // Get the blogs available model.Archives = (await _api.Pages.GetAllBlogsAsync<PageInfo>(siteId.Value)) .Select(p => new PostModalModel.ArchiveItem { Id = p.Id, Title = p.Title, Slug = p.Slug }) .OrderBy(p => p.Title) .ToList(); if (model.Archives.Any()) { if (!archiveId.HasValue) { // Select the first blog archiveId = model.Archives.First().Id; } var archive = model.Archives.FirstOrDefault(b => b.Id == archiveId.Value); if (archive != null) { model.ArchiveId = archive.Id; model.ArchiveTitle = archive.Title; model.ArchiveSlug = archive.Slug; } // Get the available posts model.Posts = (await _api.Posts.GetAllAsync<PostInfo>(archiveId.Value)) .Select(p => new PostModalModel.PostModalItem { Id = p.Id, Title = p.Title, Permalink = "/" + model.ArchiveSlug + "/" + p.Slug, Published = p.Published?.ToString("yyyy-MM-dd HH:mm") }).ToList(); // Sort so we show unpublished drafts first model.Posts = model.Posts.Where(p => string.IsNullOrEmpty(p.Published)) .Concat(model.Posts.Where(p => !string.IsNullOrEmpty(p.Published))) .ToList(); } return model; } public async Task<PostListModel> GetList(Guid archiveId, int index = 0) { var page = await _api.Pages.GetByIdAsync<PageInfo>(archiveId); if (page == null) { return new PostListModel(); } var pageType = App.PageTypes.GetById(page.TypeId); var pageSize = 0; using (var config = new Config(_api)) { pageSize = config.ManagerPageSize; } var model = new PostListModel { PostTypes = App.PostTypes.Select(t => new PostListModel.PostTypeItem { Id = t.Id, Title = t.Title, AddUrl = "manager/post/add/" }).ToList(), TotalPosts = await _api.Posts.GetCountAsync(archiveId) }; model.TotalPages = Convert.ToInt32(Math.Ceiling(model.TotalPosts / Convert.ToDouble(pageSize))); model.Index = index; // We have specified the post types that should be available // in this archive. Filter them accordingly if (pageType.ArchiveItemTypes.Count > 0) { model.PostTypes = model.PostTypes .Where(t => pageType.ArchiveItemTypes.Contains(t.Id)) .ToList(); } // Get drafts var drafts = await _api.Posts.GetAllDraftsAsync(archiveId); // Get posts model.Posts = (await _api.Posts.GetAllAsync<PostInfo>(archiveId, index, pageSize)) .Select(p => new PostListModel.PostItem { Id = p.Id.ToString(), Title = p.Title, TypeName = model.PostTypes.First(t => t.Id == p.TypeId).Title, Category = p.Category.Title, Published = p.Published?.ToString("yyyy-MM-dd HH:mm"), Status = p.GetState(drafts.Contains(p.Id)), isScheduled = p.Published.HasValue && p.Published.Value > DateTime.Now, EditUrl = "manager/post/edit/" }).ToList(); // Get categories model.Categories = (await _api.Posts.GetAllCategoriesAsync(archiveId)) .Select(c => new PostListModel.CategoryItem { Id = c.Id.ToString(), Title = c.Title }).ToList(); return model; } public async Task<PostEditModel> GetById(Guid id, bool useDraft = true) { var isDraft = true; var post = useDraft ? await _api.Posts.GetDraftByIdAsync(id) : null; if (post == null) { post = await _api.Posts.GetByIdAsync(id); isDraft = false; } if (post != null) { // Perform manager init await _factory.InitDynamicManagerAsync(post, App.PostTypes.GetById(post.TypeId)); var postModel = Transform(post, isDraft); postModel.Categories = (await _api.Posts.GetAllCategoriesAsync(post.BlogId)) .Select(c => c.Title).ToList(); postModel.Tags = (await _api.Posts.GetAllTagsAsync(post.BlogId)) .Select(t => t.Title).ToList(); postModel.PendingCommentCount = (await _api.Posts.GetAllPendingCommentsAsync(id)) .Count(); postModel.SelectedCategory = post.Category.Title; postModel.SelectedTags = post.Tags.Select(t => t.Title).ToList(); return postModel; } return null; } public async Task<PostEditModel> Create(Guid archiveId, string typeId) { var post = await _api.Posts.CreateAsync<DynamicPost>(typeId); if (post != null) { post.Id = Guid.NewGuid(); post.BlogId = archiveId; // Perform manager init await _factory.InitDynamicManagerAsync(post, App.PostTypes.GetById(post.TypeId)); var postModel = Transform(post, false); postModel.Categories = (await _api.Posts.GetAllCategoriesAsync(post.BlogId)) .Select(c => c.Title).ToList(); postModel.Tags = (await _api.Posts.GetAllTagsAsync(post.BlogId)) .Select(t => t.Title).ToList(); postModel.SelectedCategory = post.Category?.Title; postModel.SelectedTags = post.Tags.Select(t => t.Title).ToList(); return postModel; } return null; } public async Task Save(PostEditModel model, bool draft) { var postType = App.PostTypes.GetById(model.TypeId); if (postType != null) { if (model.Id == Guid.Empty) { model.Id = Guid.NewGuid(); } var post = await _api.Posts.GetByIdAsync(model.Id); if (post == null) { post = await _factory.CreateAsync<DynamicPost>(postType); post.Id = model.Id; } post.BlogId = model.BlogId; post.TypeId = model.TypeId; post.Title = model.Title; post.Slug = model.Slug; post.MetaTitle = model.MetaTitle; post.MetaKeywords = model.MetaKeywords; post.MetaDescription = model.MetaDescription; post.MetaIndex = model.MetaIndex; post.MetaFollow = model.MetaFollow; post.MetaPriority = model.MetaPriority; post.OgTitle = model.OgTitle; post.OgDescription = model.OgDescription; post.OgImage = model.OgImage; post.Excerpt = model.Excerpt; post.Published = !string.IsNullOrEmpty(model.Published) ? DateTime.Parse(model.Published) : (DateTime?)null; post.RedirectUrl = model.RedirectUrl; post.RedirectType = (RedirectType)Enum.Parse(typeof(RedirectType), model.RedirectType); post.EnableComments = model.EnableComments; post.CloseCommentsAfterDays = model.CloseCommentsAfterDays; post.Permissions = model.SelectedPermissions; post.PrimaryImage = model.PrimaryImage; if (postType.Routes.Count > 1) { post.Route = postType.Routes.FirstOrDefault(r => r.Route == model.SelectedRoute?.Route) ?? postType.Routes.First(); } // Save category post.Category = new Taxonomy { Title = model.SelectedCategory }; // Save tags post.Tags.Clear(); foreach (var tag in model.SelectedTags) { post.Tags.Add(new Taxonomy { Title = tag }); } // Save regions foreach (var region in postType.Regions) { var modelRegion = model.Regions .FirstOrDefault(r => r.Meta.Id == region.Id); if (region.Collection) { var listRegion = (IRegionList)((IDictionary<string, object>)post.Regions)[region.Id]; listRegion.Clear(); foreach (var item in modelRegion.Items) { if (region.Fields.Count == 1) { listRegion.Add(item.Fields[0].Model); } else { var postRegion = new ExpandoObject(); foreach (var field in region.Fields) { var modelField = item.Fields .FirstOrDefault(f => f.Meta.Id == field.Id); ((IDictionary<string, object>)postRegion)[field.Id] = modelField.Model; } listRegion.Add(postRegion); } } } else { var postRegion = ((IDictionary<string, object>)post.Regions)[region.Id]; if (region.Fields.Count == 1) { ((IDictionary<string, object>)post.Regions)[region.Id] = modelRegion.Items[0].Fields[0].Model; } else { foreach (var field in region.Fields) { var modelField = modelRegion.Items[0].Fields .FirstOrDefault(f => f.Meta.Id == field.Id); ((IDictionary<string, object>)postRegion)[field.Id] = modelField.Model; } } } } // Save blocks post.Blocks.Clear(); foreach (var block in model.Blocks) { if (block is BlockGroupModel blockGroup) { var groupType = App.Blocks.GetByType(blockGroup.Type); if (groupType != null) { var postBlock = (BlockGroup)Activator.CreateInstance(groupType.Type); postBlock.Id = blockGroup.Id; postBlock.Type = blockGroup.Type; foreach (var field in blockGroup.Fields) { var prop = postBlock.GetType().GetProperty(field.Meta.Id, App.PropertyBindings); prop.SetValue(postBlock, field.Model); } foreach (var item in blockGroup.Items) { if (item is BlockItemModel blockItem) { postBlock.Items.Add(blockItem.Model); } else if (item is BlockGenericModel blockGeneric) { var transformed = ContentUtils.TransformGenericBlock(blockGeneric); if (transformed != null) { postBlock.Items.Add(transformed); } } } post.Blocks.Add(postBlock); } } else if (block is BlockItemModel blockItem) { post.Blocks.Add(blockItem.Model); } else if (block is BlockGenericModel blockGeneric) { var transformed = ContentUtils.TransformGenericBlock(blockGeneric); if (transformed != null) { post.Blocks.Add(transformed); } } } // Save post if (draft) { await _api.Posts.SaveDraftAsync(post); } else { await _api.Posts.SaveAsync(post); } } else { throw new ValidationException("Invalid Post Type."); } } /// <summary> /// Deletes the post with the given id. /// </summary> /// <param name="id">The unique id</param> public Task Delete(Guid id) { return _api.Posts.DeleteAsync(id); } private PostEditModel Transform(DynamicPost post, bool isDraft) { var config = new Config(_api); var type = App.PostTypes.GetById(post.TypeId); var route = type.Routes.FirstOrDefault(r => r.Route == post.Route) ?? type.Routes.FirstOrDefault(); var model = new PostEditModel { Id = post.Id, BlogId = post.BlogId, TypeId = post.TypeId, PrimaryImage = post.PrimaryImage, Title = post.Title, Slug = post.Slug, MetaTitle = post.MetaTitle, MetaKeywords = post.MetaKeywords, MetaDescription = post.MetaDescription, MetaIndex = post.MetaIndex, MetaFollow = post.MetaFollow, MetaPriority = post.MetaPriority, OgTitle = post.OgTitle, OgDescription = post.OgDescription, OgImage = post.OgImage, Excerpt = post.Excerpt, Published = post.Published?.ToString("yyyy-MM-dd HH:mm"), RedirectUrl = post.RedirectUrl, RedirectType = post.RedirectType.ToString(), EnableComments = post.EnableComments, CloseCommentsAfterDays = post.CloseCommentsAfterDays, CommentCount = post.CommentCount, State = post.GetState(isDraft), UseBlocks = type.UseBlocks, UsePrimaryImage = type.UsePrimaryImage, UseExcerpt = type.UseExcerpt, UseHtmlExcerpt = config.HtmlExcerpt, IsScheduled = post.Published.HasValue && post.Published.Value > DateTime.Now, SelectedRoute = route == null ? null : new RouteModel { Title = route.Title, Route = route.Route }, Permissions = App.Permissions .GetPublicPermissions() .Select(p => new KeyValuePair<string, string>(p.Name, p.Title)) .ToList(), SelectedPermissions = post.Permissions }; foreach (var r in type.Routes) { model.Routes.Add(new RouteModel { Title = r.Title, Route = r.Route }); } foreach (var regionType in type.Regions) { var region = new RegionModel { Meta = new RegionMeta { Id = regionType.Id, Name = regionType.Title, Description = regionType.Description, Placeholder = regionType.ListTitlePlaceholder, IsCollection = regionType.Collection, Expanded = regionType.ListExpand, Icon = regionType.Icon, Display = regionType.Display.ToString().ToLower(), Width = regionType.Width.ToString().ToLower() } }; var regionListModel = ((IDictionary<string, object>)post.Regions)[regionType.Id]; if (!regionType.Collection) { var regionModel = (IRegionList)Activator.CreateInstance(typeof(RegionList<>).MakeGenericType(regionListModel.GetType())); regionModel.Add(regionListModel); regionListModel = regionModel; } foreach (var regionModel in (IEnumerable)regionListModel) { var regionItem = new RegionItemModel(); foreach (var fieldType in regionType.Fields) { var appFieldType = App.Fields.GetByType(fieldType.Type); var field = new FieldModel { Meta = new FieldMeta { Id = fieldType.Id, Name = fieldType.Title, Component = appFieldType.Component, Placeholder = fieldType.Placeholder, IsHalfWidth = fieldType.Options.HasFlag(FieldOption.HalfWidth), Description = fieldType.Description } }; if (typeof(SelectFieldBase).IsAssignableFrom(appFieldType.Type)) { foreach(var item in ((SelectFieldBase)Activator.CreateInstance(appFieldType.Type)).Items) { field.Meta.Options.Add(Convert.ToInt32(item.Value), item.Title); } } if (regionType.Fields.Count > 1) { field.Model = (IField)((IDictionary<string, object>)regionModel)[fieldType.Id]; if (regionType.ListTitleField == fieldType.Id) { regionItem.Title = field.Model.GetTitle(); field.Meta.NotifyChange = true; } } else { field.Model = (IField)regionModel; field.Meta.NotifyChange = true; regionItem.Title = field.Model.GetTitle(); } regionItem.Fields.Add(field); } if (string.IsNullOrWhiteSpace(regionItem.Title)) { regionItem.Title = "..."; } region.Items.Add(regionItem); } model.Regions.Add(region); } foreach (var block in post.Blocks) { var blockType = App.Blocks.GetByType(block.Type); if (block is BlockGroup blockGroup) { var group = new BlockGroupModel { Id = block.Id, Type = block.Type, Meta = new BlockMeta { Name = blockType.Name, Icon = blockType.Icon, Component = blockType.Component, Width = blockType.Width.ToString().ToLower(), IsGroup = true, isCollapsed = config.ManagerDefaultCollapsedBlocks, ShowHeader = !config.ManagerDefaultCollapsedBlockGroupHeaders } }; group.Fields = ContentUtils.GetBlockFields(block); bool firstChild = true; foreach (var child in blockGroup.Items) { blockType = App.Blocks.GetByType(child.Type); if (!blockType.IsGeneric) { group.Items.Add(new BlockItemModel { IsActive = firstChild, Model = child, Meta = new BlockMeta { Name = blockType.Name, Title = child.GetTitle(), Icon = blockType.Icon, Component = blockType.Component, Width = blockType.Width.ToString().ToLower() } }); } else { // Generic block item model group.Items.Add(new BlockGenericModel { Id = child.Id, IsActive = firstChild, Model = ContentUtils.GetBlockFields(child), Type = child.Type, Meta = new BlockMeta { Name = blockType.Name, Title = child.GetTitle(), Icon = blockType.Icon, Component = blockType.Component, Width = blockType.Width.ToString().ToLower() } }); } firstChild = false; } model.Blocks.Add(group); } else { if (!blockType.IsGeneric) { // Regular block item model model.Blocks.Add(new BlockItemModel { Model = block, Meta = new BlockMeta { Name = blockType.Name, Title = block.GetTitle(), Icon = blockType.Icon, Component = blockType.Component, Width = blockType.Width.ToString().ToLower(), isCollapsed = config.ManagerDefaultCollapsedBlocks } }); } else { // Generic block item model model.Blocks.Add(new BlockGenericModel { Id = block.Id, Model = ContentUtils.GetBlockFields(block), Type = block.Type, Meta = new BlockMeta { Name = blockType.Name, Title = block.GetTitle(), Icon = blockType.Icon, Component = blockType.Component, Width = blockType.Width.ToString().ToLower(), isCollapsed = config.ManagerDefaultCollapsedBlocks } }); } } } // Custom editors foreach (var editor in type.CustomEditors) { model.Editors.Add(new EditorModel { Component = editor.Component, Icon = editor.Icon, Name = editor.Title }); } return model; } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type ContactRequest. /// </summary> public partial class ContactRequest : BaseRequest, IContactRequest { /// <summary> /// Constructs a new ContactRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public ContactRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified Contact using POST. /// </summary> /// <param name="contactToCreate">The Contact to create.</param> /// <returns>The created Contact.</returns> public System.Threading.Tasks.Task<Contact> CreateAsync(Contact contactToCreate) { return this.CreateAsync(contactToCreate, CancellationToken.None); } /// <summary> /// Creates the specified Contact using POST. /// </summary> /// <param name="contactToCreate">The Contact to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Contact.</returns> public async System.Threading.Tasks.Task<Contact> CreateAsync(Contact contactToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<Contact>(contactToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified Contact. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified Contact. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<Contact>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified Contact. /// </summary> /// <returns>The Contact.</returns> public System.Threading.Tasks.Task<Contact> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified Contact. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The Contact.</returns> public async System.Threading.Tasks.Task<Contact> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<Contact>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified Contact using PATCH. /// </summary> /// <param name="contactToUpdate">The Contact to update.</param> /// <returns>The updated Contact.</returns> public System.Threading.Tasks.Task<Contact> UpdateAsync(Contact contactToUpdate) { return this.UpdateAsync(contactToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified Contact using PATCH. /// </summary> /// <param name="contactToUpdate">The Contact to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated Contact.</returns> public async System.Threading.Tasks.Task<Contact> UpdateAsync(Contact contactToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<Contact>(contactToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IContactRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IContactRequest Expand(Expression<Func<Contact, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IContactRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IContactRequest Select(Expression<Func<Contact, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="contactToInitialize">The <see cref="Contact"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(Contact contactToInitialize) { if (contactToInitialize != null && contactToInitialize.AdditionalData != null) { if (contactToInitialize.Extensions != null && contactToInitialize.Extensions.CurrentPage != null) { contactToInitialize.Extensions.AdditionalData = contactToInitialize.AdditionalData; object nextPageLink; contactToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { contactToInitialize.Extensions.InitializeNextPageRequest( this.Client, nextPageLinkString); } } } } } }
/************************************************************************************ 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. ************************************************************************************/ //#define OVR_USE_PROJ_MATRIX using System; using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// A head-tracked stereoscopic virtual reality camera rig. /// </summary> //[ExecuteInEditMode] SHJO MODIFIED public class OVRCameraRig : MonoBehaviour { /// <summary> /// The left eye camera. /// </summary> private Camera leftEyeCamera; /// <summary> /// The right eye camera. /// </summary> private Camera rightEyeCamera; /// <summary> /// Always coincides with the pose of the left eye. /// </summary> public Transform leftEyeAnchor { get; private set; } /// <summary> /// Always coincides with average of the left and right eye poses. /// </summary> public Transform centerEyeAnchor { get; private set; } /// <summary> /// Always coincides with the pose of the right eye. /// </summary> public Transform rightEyeAnchor { get; private set; } private bool needsCameraConfigure; public bool StopUpdateAnchors = false; #region Unity Messages private void Awake() { EnsureGameObjectIntegrity(); if (!Application.isPlaying) return; needsCameraConfigure = true; } private void Start() { EnsureGameObjectIntegrity(); if (!Application.isPlaying) return; UpdateCameras(); UpdateAnchors(); } #if !UNITY_ANDROID || UNITY_EDITOR private void LateUpdate() #else private void Update() #endif { EnsureGameObjectIntegrity(); if (!Application.isPlaying) return; UpdateCameras(); UpdateAnchors(); } #endregion private void UpdateAnchors() { OVRPose leftEye = OVRManager.display.GetEyePose(OVREye.Left); OVRPose rightEye = OVRManager.display.GetEyePose(OVREye.Right); //Manager.Instance.CameraRotation = leftEye.orientation.eulerAngles; Manager.Instance.CameraRotation = leftEye.orientation.eulerAngles; Manager.Instance.CameraOrientation = leftEye.orientation; //Debug.Log (leftEye.orientation.eulerAngles); //Debug.Log (Manager.Instance.CameraOrientation); if (StopUpdateAnchors != true) { leftEyeAnchor.localRotation = leftEye.orientation; centerEyeAnchor.localRotation = leftEye.orientation; // using left eye for now rightEyeAnchor.localRotation = rightEye.orientation; leftEyeAnchor.localPosition = leftEye.position; centerEyeAnchor.localPosition = 0.5f * (leftEye.position + rightEye.position); rightEyeAnchor.localPosition = rightEye.position; } } private void UpdateCameras() { if (needsCameraConfigure) { leftEyeCamera = ConfigureCamera(OVREye.Left); rightEyeCamera = ConfigureCamera(OVREye.Right); #if !UNITY_ANDROID || UNITY_EDITOR #if OVR_USE_PROJ_MATRIX OVRManager.display.ForceSymmetricProj(false); #else OVRManager.display.ForceSymmetricProj(true); #endif needsCameraConfigure = false; #endif } } private void EnsureGameObjectIntegrity() { if (leftEyeAnchor == null) leftEyeAnchor = ConfigureEyeAnchor(OVREye.Left); if (centerEyeAnchor == null) centerEyeAnchor = ConfigureEyeAnchor(OVREye.Center); if (rightEyeAnchor == null) rightEyeAnchor = ConfigureEyeAnchor(OVREye.Right); if (leftEyeCamera == null) { leftEyeCamera = leftEyeAnchor.GetComponent<Camera>(); if (leftEyeCamera == null) { leftEyeCamera = leftEyeAnchor.gameObject.AddComponent<Camera>(); } } if (rightEyeCamera == null) { rightEyeCamera = rightEyeAnchor.GetComponent<Camera>(); if (rightEyeCamera == null) { rightEyeCamera = rightEyeAnchor.gameObject.AddComponent<Camera>(); } } } private Transform ConfigureEyeAnchor(OVREye eye) { string name = eye.ToString() + "EyeAnchor"; Transform anchor = transform.Find(name); if (anchor == null) { string oldName = "Camera" + eye.ToString(); anchor = transform.Find(oldName); } if (anchor == null) anchor = new GameObject(name).transform; anchor.parent = transform; anchor.localScale = Vector3.one; anchor.localPosition = Vector3.zero; anchor.localRotation = Quaternion.identity; return anchor; } private Camera ConfigureCamera(OVREye eye) { Transform anchor = (eye == OVREye.Left) ? leftEyeAnchor : rightEyeAnchor; Camera cam = anchor.GetComponent<Camera>(); OVRDisplay.EyeRenderDesc eyeDesc = OVRManager.display.GetEyeRenderDesc(eye); cam.fieldOfView = eyeDesc.fov.y; cam.aspect = eyeDesc.resolution.x / eyeDesc.resolution.y; cam.rect = new Rect(0f, 0f, OVRManager.instance.virtualTextureScale, OVRManager.instance.virtualTextureScale); cam.targetTexture = OVRManager.display.GetEyeTexture(eye); // AA is documented to have no effect in deferred, but it causes black screens. if (cam.actualRenderingPath == RenderingPath.DeferredLighting) QualitySettings.antiAliasing = 0; #if !UNITY_ANDROID || UNITY_EDITOR #if OVR_USE_PROJ_MATRIX cam.projectionMatrix = OVRManager.display.GetProjection((int)eye, cam.nearClipPlane, cam.farClipPlane); #endif #endif return cam; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //------------------------------------------------------------------------------ using System.Text; namespace System.Data.Common { internal class MultipartIdentifier { private const int MaxParts = 4; internal const int ServerIndex = 0; internal const int CatalogIndex = 1; internal const int SchemaIndex = 2; internal const int TableIndex = 3; /* Left quote strings need to correspond 1 to 1 with the right quote strings example: "ab" "cd", passed in for the left and the right quote would set a or b as a starting quote character. If a is the starting quote char then c would be the ending quote char otherwise if b is the starting quote char then d would be the ending quote character. */ internal static string[] ParseMultipartIdentifier(string name, string leftQuote, string rightQuote, string property, bool ThrowOnEmptyMultipartName) { return ParseMultipartIdentifier(name, leftQuote, rightQuote, '.', MaxParts, true, property, ThrowOnEmptyMultipartName); } private enum MPIState { MPI_Value, MPI_ParseNonQuote, MPI_LookForSeparator, MPI_LookForNextCharOrSeparator, MPI_ParseQuote, MPI_RightQuote, } /* Core function for parsing the multipart identifier string. * parameters: name - string to parse * leftquote: set of characters which are valid quoting characters to initiate a quote * rightquote: set of characters which are valid to stop a quote, array index's correspond to the leftquote array. * separator: separator to use * limit: number of names to parse out * removequote:to remove the quotes on the returned string */ private static void IncrementStringCount(string name, string[] ary, ref int position, string property) { ++position; int limit = ary.Length; if (position >= limit) { throw ADP.InvalidMultipartNameToManyParts(property, name, limit); } ary[position] = string.Empty; } private static bool IsWhitespace(char ch) { return Char.IsWhiteSpace(ch); } internal static string[] ParseMultipartIdentifier(string name, string leftQuote, string rightQuote, char separator, int limit, bool removequotes, string property, bool ThrowOnEmptyMultipartName) { if (limit <= 0) { throw ADP.InvalidMultipartNameToManyParts(property, name, limit); } if (-1 != leftQuote.IndexOf(separator) || -1 != rightQuote.IndexOf(separator) || leftQuote.Length != rightQuote.Length) { throw ADP.InvalidMultipartNameIncorrectUsageOfQuotes(property, name); } string[] parsedNames = new string[limit]; // return string array int stringCount = 0; // index of current string in the buffer MPIState state = MPIState.MPI_Value; // Initialize the starting state StringBuilder sb = new StringBuilder(name.Length); // String buffer to hold the string being currently built, init the string builder so it will never be resized StringBuilder whitespaceSB = null; // String buffer to hold whitespace used when parsing nonquoted strings 'a b . c d' = 'a b' and 'c d' char rightQuoteChar = ' '; // Right quote character to use given the left quote character found. for (int index = 0; index < name.Length; ++index) { char testchar = name[index]; switch (state) { case MPIState.MPI_Value: { int quoteIndex; if (IsWhitespace(testchar)) { // Is White Space then skip the whitespace continue; } else if (testchar == separator) { // If we found a separator, no string was found, initialize the string we are parsing to Empty and the next one to Empty. // This is NOT a redundant setting of string.Empty it solves the case where we are parsing ".foo" and we should be returning null, null, empty, foo parsedNames[stringCount] = string.Empty; IncrementStringCount(name, parsedNames, ref stringCount, property); } else if (-1 != (quoteIndex = leftQuote.IndexOf(testchar))) { // If we are a left quote rightQuoteChar = rightQuote[quoteIndex]; // record the corresponding right quote for the left quote sb.Length = 0; if (!removequotes) { sb.Append(testchar); } state = MPIState.MPI_ParseQuote; } else if (-1 != rightQuote.IndexOf(testchar)) { // If we shouldn't see a right quote throw ADP.InvalidMultipartNameIncorrectUsageOfQuotes(property, name); } else { sb.Length = 0; sb.Append(testchar); state = MPIState.MPI_ParseNonQuote; } break; } case MPIState.MPI_ParseNonQuote: { if (testchar == separator) { parsedNames[stringCount] = sb.ToString(); // set the currently parsed string IncrementStringCount(name, parsedNames, ref stringCount, property); state = MPIState.MPI_Value; } else // Quotes are not valid inside a non-quoted name if (-1 != rightQuote.IndexOf(testchar)) { throw ADP.InvalidMultipartNameIncorrectUsageOfQuotes(property, name); } else if (-1 != leftQuote.IndexOf(testchar)) { throw ADP.InvalidMultipartNameIncorrectUsageOfQuotes(property, name); } else if (IsWhitespace(testchar)) { // If it is Whitespace parsedNames[stringCount] = sb.ToString(); // Set the currently parsed string if (null == whitespaceSB) { whitespaceSB = new StringBuilder(); } whitespaceSB.Length = 0; whitespaceSB.Append(testchar); // start to record the whitespace, if we are parsing a name like "foo bar" we should return "foo bar" state = MPIState.MPI_LookForNextCharOrSeparator; } else { sb.Append(testchar); } break; } case MPIState.MPI_LookForNextCharOrSeparator: { if (!IsWhitespace(testchar)) { // If it is not whitespace if (testchar == separator) { IncrementStringCount(name, parsedNames, ref stringCount, property); state = MPIState.MPI_Value; } else { // If its not a separator and not whitespace sb.Append(whitespaceSB); sb.Append(testchar); parsedNames[stringCount] = sb.ToString(); // Need to set the name here in case the string ends here. state = MPIState.MPI_ParseNonQuote; } } else { whitespaceSB.Append(testchar); } break; } case MPIState.MPI_ParseQuote: { if (testchar == rightQuoteChar) { // if se are on a right quote see if we are escaping the right quote or ending the quoted string if (!removequotes) { sb.Append(testchar); } state = MPIState.MPI_RightQuote; } else { sb.Append(testchar); // Append what we are currently parsing } break; } case MPIState.MPI_RightQuote: { if (testchar == rightQuoteChar) { // If the next char is a another right quote then we were escaping the right quote sb.Append(testchar); state = MPIState.MPI_ParseQuote; } else if (testchar == separator) { // If its a separator then record what we've parsed parsedNames[stringCount] = sb.ToString(); IncrementStringCount(name, parsedNames, ref stringCount, property); state = MPIState.MPI_Value; } else if (!IsWhitespace(testchar)) { // If it is not whitespace we got problems throw ADP.InvalidMultipartNameIncorrectUsageOfQuotes(property, name); } else { // It is a whitespace character so the following char should be whitespace, separator, or end of string anything else is bad parsedNames[stringCount] = sb.ToString(); state = MPIState.MPI_LookForSeparator; } break; } case MPIState.MPI_LookForSeparator: { if (!IsWhitespace(testchar)) { // If it is not whitespace if (testchar == separator) { // If it is a separator IncrementStringCount(name, parsedNames, ref stringCount, property); state = MPIState.MPI_Value; } else { // Otherwise not a separator throw ADP.InvalidMultipartNameIncorrectUsageOfQuotes(property, name); } } break; } } } // Resolve final states after parsing the string switch (state) { case MPIState.MPI_Value: // These states require no extra action case MPIState.MPI_LookForSeparator: case MPIState.MPI_LookForNextCharOrSeparator: break; case MPIState.MPI_ParseNonQuote: // Dump what ever was parsed case MPIState.MPI_RightQuote: parsedNames[stringCount] = sb.ToString(); break; case MPIState.MPI_ParseQuote: // Invalid Ending States default: throw ADP.InvalidMultipartNameIncorrectUsageOfQuotes(property, name); } if (parsedNames[0] == null) { if (ThrowOnEmptyMultipartName) { throw ADP.InvalidMultipartName(property, name); // Name is entirely made up of whitespace } } else { // Shuffle the parsed name, from left justification to right justification, i.e. [a][b][null][null] goes to [null][null][a][b] int offset = limit - stringCount - 1; if (offset > 0) { for (int x = limit - 1; x >= offset; --x) { parsedNames[x] = parsedNames[x - offset]; parsedNames[x - offset] = null; } } } return parsedNames; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Examples.Datagrid { using System; using Apache.Ignite.Core; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cache.Query; /// <summary> /// This example works with cache entirely in binary mode: no classes or configurations are needed. /// <para /> /// 1) Set this class as startup object (Apache.Ignite.Examples project -> right-click -> Properties -> /// Application -> Startup object); /// 2) Start example (F5 or Ctrl+F5). /// <para /> /// This example can be run with standalone Apache Ignite.NET node: /// 1) Run %IGNITE_HOME%/platforms/dotnet/bin/Apache.Ignite.exe: /// Apache.Ignite.exe -configFileName=platforms\dotnet\examples\apache.ignite.examples\app.config /// 2) Start example. /// </summary> public class BinaryModeExample { /// <summary>Cache name.</summary> private const string CacheName = "dotnet_binary_cache"; /// <summary>Person type name.</summary> private const string PersonType = "Person"; /// <summary>Company type name.</summary> private const string CompanyType = "Company"; /// <summary>Name field name.</summary> private const string NameField = "Name"; /// <summary>Company ID field name.</summary> private const string CompanyIdField = "CompanyId"; /// <summary>ID field name.</summary> private const string IdField = "Id"; [STAThread] public static void Main() { using (var ignite = Ignition.StartFromApplicationConfiguration()) { Console.WriteLine(); Console.WriteLine(">>> Binary mode example started."); // Create new cache and configure queries for Person and Company binary types. // Note that there are no such classes defined. var cache0 = ignite.GetOrCreateCache<object, object>(new CacheConfiguration { Name = CacheName, QueryEntities = new[] { new QueryEntity { KeyType = typeof(int), ValueTypeName = PersonType, Fields = new[] { new QueryField(NameField, typeof(string)), new QueryField(CompanyIdField, typeof(int)) }, Indexes = new[] { new QueryIndex(false, QueryIndexType.FullText, NameField), new QueryIndex(false, QueryIndexType.Sorted, CompanyIdField) } }, new QueryEntity { KeyType = typeof(int), ValueTypeName = CompanyType, Fields = new[] { new QueryField(IdField, typeof(int)), new QueryField(NameField, typeof(string)) } } } }); // Switch to binary mode to work with data in serialized form. var cache = cache0.WithKeepBinary<int, IBinaryObject>(); // Clean up caches on all nodes before run. cache.Clear(); // Populate cache with sample data entries. PopulateCache(cache); // Run read & modify example. ReadModifyExample(cache); // Run SQL query example. SqlQueryExample(cache); // Run SQL query with join example. SqlJoinQueryExample(cache); // Run SQL fields query example. SqlFieldsQueryExample(cache); // Run full text query example. FullTextQueryExample(cache); Console.WriteLine(); } Console.WriteLine(); Console.WriteLine(">>> Example finished, press any key to exit ..."); Console.ReadKey(); } /// <summary> /// Reads binary object fields and modifies them. /// </summary> /// <param name="cache">Cache.</param> private static void ReadModifyExample(ICache<int, IBinaryObject> cache) { const int id = 1; IBinaryObject person = cache[id]; string name = person.GetField<string>(NameField); Console.WriteLine(); Console.WriteLine(">>> Name of the person with id {0}: {1}", id, name); // Modify the binary object. cache[id] = person.ToBuilder().SetField("Name", name + " Jr.").Build(); Console.WriteLine(">>> Modified person with id {0}: {1}", id, cache[1]); } /// <summary> /// Queries persons that have a specific name using SQL. /// </summary> /// <param name="cache">Cache.</param> private static void SqlQueryExample(ICache<int, IBinaryObject> cache) { var qry = cache.Query(new SqlQuery(PersonType, "name like 'James%'")); Console.WriteLine(); Console.WriteLine(">>> Persons named James:"); foreach (var entry in qry) Console.WriteLine(">>> " + entry.Value); } /// <summary> /// Queries persons that work for company with provided name. /// </summary> /// <param name="cache">Cache.</param> private static void SqlJoinQueryExample(ICache<int, IBinaryObject> cache) { const string orgName = "Apache"; var qry = cache.Query(new SqlQuery(PersonType, "from Person, Company " + "where Person.CompanyId = Company.Id and Company.Name = ?", orgName) { EnableDistributedJoins = true }); Console.WriteLine(); Console.WriteLine(">>> Persons working for " + orgName + ":"); foreach (var entry in qry) Console.WriteLine(">>> " + entry.Value); } /// <summary> /// Queries names for all persons. /// </summary> /// <param name="cache">Cache.</param> private static void SqlFieldsQueryExample(ICache<int, IBinaryObject> cache) { var qry = cache.Query(new SqlFieldsQuery("select name from Person order by name")); Console.WriteLine(); Console.WriteLine(">>> All person names:"); foreach (var row in qry) Console.WriteLine(">>> " + row[0]); } /// <summary> /// Queries persons that have a specific name using full-text query API. /// </summary> /// <param name="cache">Cache.</param> private static void FullTextQueryExample(ICache<int, IBinaryObject> cache) { var qry = cache.Query(new TextQuery(PersonType, "Peters")); Console.WriteLine(); Console.WriteLine(">>> Persons named Peters:"); foreach (var entry in qry) Console.WriteLine(">>> " + entry.Value); } /// <summary> /// Populate cache with data for this example. /// </summary> /// <param name="cache">Cache.</param> private static void PopulateCache(ICache<int, IBinaryObject> cache) { IBinary binary = cache.Ignite.GetBinary(); // Populate persons. cache[1] = binary.GetBuilder(PersonType) .SetField(NameField, "James Wilson") .SetField(CompanyIdField, -1) .Build(); cache[2] = binary.GetBuilder(PersonType) .SetField(NameField, "Daniel Adams") .SetField(CompanyIdField, -1) .Build(); cache[3] = binary.GetBuilder(PersonType) .SetField(NameField, "Cristian Moss") .SetField(CompanyIdField, -1) .Build(); cache[4] = binary.GetBuilder(PersonType) .SetField(NameField, "Allison Mathis") .SetField(CompanyIdField, -2) .Build(); cache[5] = binary.GetBuilder(PersonType) .SetField(NameField, "Breana Robbin") .SetField(CompanyIdField, -2) .Build(); cache[6] = binary.GetBuilder(PersonType) .SetField(NameField, "Philip Horsley") .SetField(CompanyIdField, -2) .Build(); cache[7] = binary.GetBuilder(PersonType) .SetField(NameField, "James Peters") .SetField(CompanyIdField, -2) .Build(); // Populate companies. cache[-1] = binary.GetBuilder(CompanyType) .SetField(NameField, "Apache") .SetField(IdField, -1) .Build(); cache[-2] = binary.GetBuilder(CompanyType) .SetField(NameField, "Microsoft") .SetField(IdField, -2) .Build(); } } }
// // ContextBackendHandler.cs // // Author: // Lluis Sanchez <[email protected]> // Alex Corrado <[email protected]> // // 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 Xwt.Backends; using MonoMac.AppKit; using Xwt.Drawing; using MonoMac.Foundation; using MonoMac.CoreGraphics; using System.Drawing; using System.Collections.Generic; namespace Xwt.Mac { class CGContextBackend { public CGContext Context; public SizeF Size; public CGAffineTransform? InverseViewTransform; public Stack<ContextStatus> StatusStack = new Stack<ContextStatus> (); public ContextStatus CurrentStatus = new ContextStatus (); public double ScaleFactor = 1; } class ContextStatus { public object Pattern; } public class MacContextBackendHandler: ContextBackendHandler { const double degrees = System.Math.PI / 180d; public override double GetScaleFactor (object backend) { var ct = (CGContextBackend) backend; return ct.ScaleFactor; } public override void Save (object backend) { var ct = (CGContextBackend) backend; ct.Context.SaveState (); ct.StatusStack.Push (ct.CurrentStatus); var newStatus = new ContextStatus (); newStatus.Pattern = ct.CurrentStatus.Pattern; ct.CurrentStatus = newStatus; } public override void Restore (object backend) { var ct = (CGContextBackend) backend; ct.Context.RestoreState (); ct.CurrentStatus = ct.StatusStack.Pop (); } public override void SetGlobalAlpha (object backend, double alpha) { ((CGContextBackend)backend).Context.SetAlpha ((float)alpha); } public override void Arc (object backend, double xc, double yc, double radius, double angle1, double angle2) { CGContext ctx = ((CGContextBackend)backend).Context; ctx.AddArc ((float)xc, (float)yc, (float)radius, (float)(angle1 * degrees), (float)(angle2 * degrees), false); } public override void ArcNegative (object backend, double xc, double yc, double radius, double angle1, double angle2) { CGContext ctx = ((CGContextBackend)backend).Context; ctx.AddArc ((float)xc, (float)yc, (float)radius, (float)(angle1 * degrees), (float)(angle2 * degrees), true); } public override void Clip (object backend) { ((CGContextBackend)backend).Context.Clip (); } public override void ClipPreserve (object backend) { CGContext ctx = ((CGContextBackend)backend).Context; using (CGPath oldPath = ctx.CopyPath ()) { ctx.Clip (); ctx.AddPath (oldPath); } } public override void ClosePath (object backend) { ((CGContextBackend)backend).Context.ClosePath (); } public override void CurveTo (object backend, double x1, double y1, double x2, double y2, double x3, double y3) { ((CGContextBackend)backend).Context.AddCurveToPoint ((float)x1, (float)y1, (float)x2, (float)y2, (float)x3, (float)y3); } public override void Fill (object backend) { CGContextBackend gc = (CGContextBackend)backend; CGContext ctx = gc.Context; SetupContextForDrawing (ctx); if (gc.CurrentStatus.Pattern is GradientInfo) { MacGradientBackendHandler.Draw (ctx, ((GradientInfo)gc.CurrentStatus.Pattern)); } else if (gc.CurrentStatus.Pattern is ImagePatternInfo) { SetupPattern (gc); ctx.DrawPath (CGPathDrawingMode.Fill); } else { ctx.DrawPath (CGPathDrawingMode.Fill); } } public override void FillPreserve (object backend) { CGContext ctx = ((CGContextBackend)backend).Context; using (CGPath oldPath = ctx.CopyPath ()) { Fill (backend); ctx.AddPath (oldPath); } } public override void LineTo (object backend, double x, double y) { ((CGContextBackend)backend).Context.AddLineToPoint ((float)x, (float)y); } public override void MoveTo (object backend, double x, double y) { ((CGContextBackend)backend).Context.MoveTo ((float)x, (float)y); } public override void NewPath (object backend) { ((CGContextBackend)backend).Context.BeginPath (); } public override void Rectangle (object backend, double x, double y, double width, double height) { ((CGContextBackend)backend).Context.AddRect (new RectangleF ((float)x, (float)y, (float)width, (float)height)); } public override void RelCurveTo (object backend, double dx1, double dy1, double dx2, double dy2, double dx3, double dy3) { CGContext ctx = ((CGContextBackend)backend).Context; PointF p = ctx.GetPathCurrentPoint (); ctx.AddCurveToPoint ((float)(p.X + dx1), (float)(p.Y + dy1), (float)(p.X + dx2), (float)(p.Y + dy2), (float)(p.X + dx3), (float)(p.Y + dy3)); } public override void RelLineTo (object backend, double dx, double dy) { CGContext ctx = ((CGContextBackend)backend).Context; PointF p = ctx.GetPathCurrentPoint (); ctx.AddLineToPoint ((float)(p.X + dx), (float)(p.Y + dy)); } public override void RelMoveTo (object backend, double dx, double dy) { CGContext ctx = ((CGContextBackend)backend).Context; PointF p = ctx.GetPathCurrentPoint (); ctx.MoveTo ((float)(p.X + dx), (float)(p.Y + dy)); } public override void Stroke (object backend) { CGContext ctx = ((CGContextBackend)backend).Context; SetupContextForDrawing (ctx); ctx.DrawPath (CGPathDrawingMode.Stroke); } public override void StrokePreserve (object backend) { CGContext ctx = ((CGContextBackend)backend).Context; SetupContextForDrawing (ctx); using (CGPath oldPath = ctx.CopyPath ()) { ctx.DrawPath (CGPathDrawingMode.Stroke); ctx.AddPath (oldPath); } } public override void SetColor (object backend, Xwt.Drawing.Color color) { CGContextBackend gc = (CGContextBackend)backend; gc.CurrentStatus.Pattern = null; CGContext ctx = gc.Context; ctx.SetFillColorSpace (Util.DeviceRGBColorSpace); ctx.SetStrokeColorSpace (Util.DeviceRGBColorSpace); ctx.SetFillColor ((float)color.Red, (float)color.Green, (float)color.Blue, (float)color.Alpha); ctx.SetStrokeColor ((float)color.Red, (float)color.Green, (float)color.Blue, (float)color.Alpha); } public override void SetLineWidth (object backend, double width) { ((CGContextBackend)backend).Context.SetLineWidth ((float)width); } public override void SetLineDash (object backend, double offset, params double[] pattern) { float[] array = new float[pattern.Length]; for (int n=0; n<pattern.Length; n++) array [n] = (float) pattern[n]; if (array.Length == 0) array = new float [] { 1 }; ((CGContextBackend)backend).Context.SetLineDash ((float)offset, array); } public override void SetPattern (object backend, object p) { CGContextBackend gc = (CGContextBackend)backend; gc.CurrentStatus.Pattern = p; } void SetupPattern (CGContextBackend gc) { gc.Context.SetPatternPhase (new SizeF (0, 0)); if (gc.CurrentStatus.Pattern is GradientInfo) return; if (gc.CurrentStatus.Pattern is ImagePatternInfo) { var pi = (ImagePatternInfo) gc.CurrentStatus.Pattern; RectangleF bounds = new RectangleF (PointF.Empty, new SizeF (pi.Image.Size.Width, pi.Image.Size.Height)); var t = CGAffineTransform.Multiply (CGAffineTransform.MakeScale (1f, -1f), gc.Context.GetCTM ()); CGPattern pattern; if (pi.Image is CustomImage) { pattern = new CGPattern (bounds, t, bounds.Width, bounds.Height, CGPatternTiling.ConstantSpacing, true, c => { c.TranslateCTM (0, bounds.Height); c.ScaleCTM (1f, -1f); ((CustomImage)pi.Image).DrawInContext (c); }); } else { RectangleF empty = RectangleF.Empty; CGImage cgimg = ((NSImage)pi.Image).AsCGImage (ref empty, null, null); pattern = new CGPattern (bounds, t, bounds.Width, bounds.Height, CGPatternTiling.ConstantSpacing, true, c => c.DrawImage (bounds, cgimg)); } CGContext ctx = gc.Context; float[] alpha = new[] { (float)pi.Alpha }; ctx.SetFillColorSpace (Util.PatternColorSpace); ctx.SetStrokeColorSpace (Util.PatternColorSpace); ctx.SetFillPattern (pattern, alpha); ctx.SetStrokePattern (pattern, alpha); } } public override void DrawTextLayout (object backend, TextLayout layout, double x, double y) { CGContext ctx = ((CGContextBackend)backend).Context; SetupContextForDrawing (ctx); var li = ApplicationContext.Toolkit.GetSafeBackend (layout); MacTextLayoutBackendHandler.Draw (ctx, li, x, y); } public override void DrawImage (object backend, ImageDescription img, double x, double y) { var srcRect = new Rectangle (Point.Zero, img.Size); var destRect = new Rectangle (x, y, img.Size.Width, img.Size.Height); DrawImage (backend, img, srcRect, destRect); } public override void DrawImage (object backend, ImageDescription img, Rectangle srcRect, Rectangle destRect) { CGContext ctx = ((CGContextBackend)backend).Context; NSImage image = img.ToNSImage (); ctx.SaveState (); ctx.SetAlpha ((float)img.Alpha); double rx = destRect.Width / srcRect.Width; double ry = destRect.Height / srcRect.Height; ctx.AddRect (new RectangleF ((float)destRect.X, (float)destRect.Y, (float)destRect.Width, (float)destRect.Height)); ctx.Clip (); ctx.TranslateCTM ((float)(destRect.X - (srcRect.X * rx)), (float)(destRect.Y - (srcRect.Y * ry))); ctx.ScaleCTM ((float)rx, (float)ry); if (image is CustomImage) { ((CustomImage)image).DrawInContext ((CGContextBackend)backend); } else { RectangleF rr = new RectangleF (0, 0, (float)image.Size.Width, image.Size.Height); ctx.ScaleCTM (1f, -1f); ctx.DrawImage (new RectangleF (0, -image.Size.Height, image.Size.Width, image.Size.Height), image.AsCGImage (ref rr, NSGraphicsContext.CurrentContext, null)); } ctx.RestoreState (); } public override void Rotate (object backend, double angle) { ((CGContextBackend)backend).Context.RotateCTM ((float)(angle * degrees)); } public override void Scale (object backend, double scaleX, double scaleY) { ((CGContextBackend)backend).Context.ScaleCTM ((float)scaleX, (float)scaleY); } public override void Translate (object backend, double tx, double ty) { ((CGContextBackend)backend).Context.TranslateCTM ((float)tx, (float)ty); } public override void ModifyCTM (object backend, Matrix m) { CGAffineTransform t = new CGAffineTransform ((float)m.M11, (float)m.M12, (float)m.M21, (float)m.M22, (float)m.OffsetX, (float)m.OffsetY); ((CGContextBackend)backend).Context.ConcatCTM (t); } public override Matrix GetCTM (object backend) { CGAffineTransform t = GetContextTransform ((CGContextBackend)backend); Matrix ctm = new Matrix (t.xx, t.yx, t.xy, t.yy, t.x0, t.y0); return ctm; } public override object CreatePath () { return new CGPath (); } public override object CopyPath (object backend) { return ((CGContextBackend)backend).Context.CopyPath (); } public override void AppendPath (object backend, object otherBackend) { CGContext dest = ((CGContextBackend)backend).Context; CGContextBackend src = otherBackend as CGContextBackend; if (src != null) { using (var path = src.Context.CopyPath ()) dest.AddPath (path); } else { dest.AddPath ((CGPath)otherBackend); } } public override bool IsPointInFill (object backend, double x, double y) { return ((CGContextBackend)backend).Context.PathContainsPoint (new PointF ((float)x, (float)y), CGPathDrawingMode.Fill); } public override bool IsPointInStroke (object backend, double x, double y) { return ((CGContextBackend)backend).Context.PathContainsPoint (new PointF ((float)x, (float)y), CGPathDrawingMode.Stroke); } public override void Dispose (object backend) { ((CGContextBackend)backend).Context.Dispose (); } static CGAffineTransform GetContextTransform (CGContextBackend gc) { CGAffineTransform t = gc.Context.GetCTM (); // The CTM returned above actually includes the full view transform. // We only want the transform that is applied to the context, so concat // the inverse of the view transform to nullify that part. if (gc.InverseViewTransform.HasValue) t.Multiply (gc.InverseViewTransform.Value); return t; } static void SetupContextForDrawing (CGContext ctx) { if (ctx.IsPathEmpty ()) return; // setup pattern drawing to better match the behavior of Cairo var drawPoint = ctx.GetCTM ().TransformPoint (ctx.GetPathBoundingBox ().Location); var patternPhase = new SizeF (drawPoint.X, drawPoint.Y); if (patternPhase != SizeF.Empty) ctx.SetPatternPhase (patternPhase); } } }
/* * Exchange Web Services Managed API * * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ namespace Microsoft.Exchange.WebServices.Autodiscover { using System; using System.IO; using System.IO.Compression; using System.Net; using System.Xml; using Microsoft.Exchange.WebServices.Data; /// <summary> /// Represents the base class for all requested made to the Autodiscover service. /// </summary> internal abstract class AutodiscoverRequest { private AutodiscoverService service; private Uri url; /// <summary> /// Initializes a new instance of the <see cref="AutodiscoverRequest"/> class. /// </summary> /// <param name="service">Autodiscover service associated with this request.</param> /// <param name="url">URL of Autodiscover service.</param> internal AutodiscoverRequest(AutodiscoverService service, Uri url) { this.service = service; this.url = url; } /// <summary> /// Determines whether response is a redirection. /// </summary> /// <param name="httpWebResponse">The HTTP web response.</param> /// <returns>True if redirection response.</returns> internal static bool IsRedirectionResponse(IEwsHttpWebResponse httpWebResponse) { return (httpWebResponse.StatusCode == HttpStatusCode.Redirect) || (httpWebResponse.StatusCode == HttpStatusCode.Moved) || (httpWebResponse.StatusCode == HttpStatusCode.RedirectKeepVerb) || (httpWebResponse.StatusCode == HttpStatusCode.RedirectMethod); } /// <summary> /// Validates the request. /// </summary> internal virtual void Validate() { this.Service.Validate(); } /// <summary> /// Executes this instance. /// </summary> /// <returns></returns> internal AutodiscoverResponse InternalExecute() { this.Validate(); try { IEwsHttpWebRequest request = this.Service.PrepareHttpWebRequestForUrl(this.Url); this.Service.TraceHttpRequestHeaders(TraceFlags.AutodiscoverRequestHttpHeaders, request); bool needSignature = this.Service.Credentials != null && this.Service.Credentials.NeedSignature; bool needTrace = this.Service.IsTraceEnabledFor(TraceFlags.AutodiscoverRequest); using (Stream requestStream = request.GetRequestStream()) { using (MemoryStream memoryStream = new MemoryStream()) { using (EwsServiceXmlWriter writer = new EwsServiceXmlWriter(this.Service, memoryStream)) { writer.RequireWSSecurityUtilityNamespace = needSignature; this.WriteSoapRequest( this.Url, writer); } if (needSignature) { this.service.Credentials.Sign(memoryStream); } if (needTrace) { memoryStream.Position = 0; this.Service.TraceXml(TraceFlags.AutodiscoverRequest, memoryStream); } EwsUtilities.CopyStream(memoryStream, requestStream); } } using (IEwsHttpWebResponse webResponse = request.GetResponse()) { if (AutodiscoverRequest.IsRedirectionResponse(webResponse)) { AutodiscoverResponse response = this.CreateRedirectionResponse(webResponse); if (response != null) { return response; } else { throw new ServiceRemoteException(Strings.InvalidRedirectionResponseReturned); } } using (Stream responseStream = AutodiscoverRequest.GetResponseStream(webResponse)) { using (MemoryStream memoryStream = new MemoryStream()) { // Copy response stream to in-memory stream and reset to start EwsUtilities.CopyStream(responseStream, memoryStream); memoryStream.Position = 0; this.Service.TraceResponse(webResponse, memoryStream); EwsXmlReader ewsXmlReader = new EwsXmlReader(memoryStream); // WCF may not generate an XML declaration. ewsXmlReader.Read(); if (ewsXmlReader.NodeType == XmlNodeType.XmlDeclaration) { ewsXmlReader.ReadStartElement(XmlNamespace.Soap, XmlElementNames.SOAPEnvelopeElementName); } else if ((ewsXmlReader.NodeType != XmlNodeType.Element) || (ewsXmlReader.LocalName != XmlElementNames.SOAPEnvelopeElementName) || (ewsXmlReader.NamespaceUri != EwsUtilities.GetNamespaceUri(XmlNamespace.Soap))) { throw new ServiceXmlDeserializationException(Strings.InvalidAutodiscoverServiceResponse); } this.ReadSoapHeaders(ewsXmlReader); AutodiscoverResponse response = this.ReadSoapBody(ewsXmlReader); ewsXmlReader.ReadEndElement(XmlNamespace.Soap, XmlElementNames.SOAPEnvelopeElementName); if (response.ErrorCode == AutodiscoverErrorCode.NoError) { return response; } else { throw new AutodiscoverResponseException(response.ErrorCode, response.ErrorMessage); } } } } } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null) { IEwsHttpWebResponse httpWebResponse = this.Service.HttpWebRequestFactory.CreateExceptionResponse(ex); if (AutodiscoverRequest.IsRedirectionResponse(httpWebResponse)) { this.Service.ProcessHttpResponseHeaders( TraceFlags.AutodiscoverResponseHttpHeaders, httpWebResponse); AutodiscoverResponse response = this.CreateRedirectionResponse(httpWebResponse); if (response != null) { return response; } } else { this.ProcessWebException(ex); } } // Wrap exception if the above code block didn't throw throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, ex.Message), ex); } catch (XmlException ex) { this.Service.TraceMessage( TraceFlags.AutodiscoverConfiguration, string.Format("XML parsing error: {0}", ex.Message)); // Wrap exception throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, ex.Message), ex); } catch (IOException ex) { this.Service.TraceMessage( TraceFlags.AutodiscoverConfiguration, string.Format("I/O error: {0}", ex.Message)); // Wrap exception throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, ex.Message), ex); } } /// <summary> /// Processes the web exception. /// </summary> /// <param name="webException">The web exception.</param> private void ProcessWebException(WebException webException) { if (webException.Response != null) { IEwsHttpWebResponse httpWebResponse = this.Service.HttpWebRequestFactory.CreateExceptionResponse(webException); SoapFaultDetails soapFaultDetails; if (httpWebResponse.StatusCode == HttpStatusCode.InternalServerError) { // If tracing is enabled, we read the entire response into a MemoryStream so that we // can pass it along to the ITraceListener. Then we parse the response from the // MemoryStream. if (this.Service.IsTraceEnabledFor(TraceFlags.AutodiscoverRequest)) { using (MemoryStream memoryStream = new MemoryStream()) { using (Stream serviceResponseStream = AutodiscoverRequest.GetResponseStream(httpWebResponse)) { // Copy response to in-memory stream and reset position to start. EwsUtilities.CopyStream(serviceResponseStream, memoryStream); memoryStream.Position = 0; } this.Service.TraceResponse(httpWebResponse, memoryStream); EwsXmlReader reader = new EwsXmlReader(memoryStream); soapFaultDetails = this.ReadSoapFault(reader); } } else { using (Stream stream = AutodiscoverRequest.GetResponseStream(httpWebResponse)) { EwsXmlReader reader = new EwsXmlReader(stream); soapFaultDetails = this.ReadSoapFault(reader); } } if (soapFaultDetails != null) { throw new ServiceResponseException(new ServiceResponse(soapFaultDetails)); } } else { this.Service.ProcessHttpErrorResponse(httpWebResponse, webException); } } } /// <summary> /// Create a redirection response. /// </summary> /// <param name="httpWebResponse">The HTTP web response.</param> private AutodiscoverResponse CreateRedirectionResponse(IEwsHttpWebResponse httpWebResponse) { string location = httpWebResponse.Headers[HttpResponseHeader.Location]; if (!string.IsNullOrEmpty(location)) { try { Uri redirectionUri = new Uri(this.Url, location); if ((redirectionUri.Scheme == Uri.UriSchemeHttp) || (redirectionUri.Scheme == Uri.UriSchemeHttps)) { AutodiscoverResponse response = this.CreateServiceResponse(); response.ErrorCode = AutodiscoverErrorCode.RedirectUrl; response.RedirectionUrl = redirectionUri; return response; } this.Service.TraceMessage( TraceFlags.AutodiscoverConfiguration, string.Format("Invalid redirection URL '{0}' returned by Autodiscover service.", redirectionUri)); } catch (UriFormatException) { this.Service.TraceMessage( TraceFlags.AutodiscoverConfiguration, string.Format("Invalid redirection location '{0}' returned by Autodiscover service.", location)); } } else { this.Service.TraceMessage( TraceFlags.AutodiscoverConfiguration, "Redirection response returned by Autodiscover service without redirection location."); } return null; } /// <summary> /// Reads the SOAP fault. /// </summary> /// <param name="reader">The reader.</param> /// <returns>SOAP fault details.</returns> private SoapFaultDetails ReadSoapFault(EwsXmlReader reader) { SoapFaultDetails soapFaultDetails = null; try { // WCF may not generate an XML declaration. reader.Read(); if (reader.NodeType == XmlNodeType.XmlDeclaration) { reader.Read(); } if (!reader.IsStartElement() || (reader.LocalName != XmlElementNames.SOAPEnvelopeElementName)) { return soapFaultDetails; } // Get the namespace URI from the envelope element and use it for the rest of the parsing. // If it's not 1.1 or 1.2, we can't continue. XmlNamespace soapNamespace = EwsUtilities.GetNamespaceFromUri(reader.NamespaceUri); if (soapNamespace == XmlNamespace.NotSpecified) { return soapFaultDetails; } reader.Read(); // Skip SOAP header. if (reader.IsStartElement(soapNamespace, XmlElementNames.SOAPHeaderElementName)) { do { reader.Read(); } while (!reader.IsEndElement(soapNamespace, XmlElementNames.SOAPHeaderElementName)); // Queue up the next read reader.Read(); } // Parse the fault element contained within the SOAP body. if (reader.IsStartElement(soapNamespace, XmlElementNames.SOAPBodyElementName)) { do { reader.Read(); // Parse Fault element if (reader.IsStartElement(soapNamespace, XmlElementNames.SOAPFaultElementName)) { soapFaultDetails = SoapFaultDetails.Parse(reader, soapNamespace); } } while (!reader.IsEndElement(soapNamespace, XmlElementNames.SOAPBodyElementName)); } reader.ReadEndElement(soapNamespace, XmlElementNames.SOAPEnvelopeElementName); } catch (XmlException) { // If response doesn't contain a valid SOAP fault, just ignore exception and // return null for SOAP fault details. } return soapFaultDetails; } /// <summary> /// Writes the autodiscover SOAP request. /// </summary> /// <param name="requestUrl">Request URL.</param> /// <param name="writer">The writer.</param> internal void WriteSoapRequest( Uri requestUrl, EwsServiceXmlWriter writer) { writer.WriteStartElement(XmlNamespace.Soap, XmlElementNames.SOAPEnvelopeElementName); writer.WriteAttributeValue("xmlns", EwsUtilities.AutodiscoverSoapNamespacePrefix, EwsUtilities.AutodiscoverSoapNamespace); writer.WriteAttributeValue("xmlns", EwsUtilities.WSAddressingNamespacePrefix, EwsUtilities.WSAddressingNamespace); writer.WriteAttributeValue("xmlns", EwsUtilities.EwsXmlSchemaInstanceNamespacePrefix, EwsUtilities.EwsXmlSchemaInstanceNamespace); if (writer.RequireWSSecurityUtilityNamespace) { writer.WriteAttributeValue("xmlns", EwsUtilities.WSSecurityUtilityNamespacePrefix, EwsUtilities.WSSecurityUtilityNamespace); } writer.WriteStartElement(XmlNamespace.Soap, XmlElementNames.SOAPHeaderElementName); if (this.Service.Credentials != null) { this.Service.Credentials.EmitExtraSoapHeaderNamespaceAliases(writer.InternalWriter); } writer.WriteElementValue( XmlNamespace.Autodiscover, XmlElementNames.RequestedServerVersion, this.Service.RequestedServerVersion.ToString()); writer.WriteElementValue( XmlNamespace.WSAddressing, XmlElementNames.Action, this.GetWsAddressingActionName()); writer.WriteElementValue( XmlNamespace.WSAddressing, XmlElementNames.To, requestUrl.AbsoluteUri); this.WriteExtraCustomSoapHeadersToXml(writer); if (this.Service.Credentials != null) { this.Service.Credentials.SerializeWSSecurityHeaders(writer.InternalWriter); } this.Service.DoOnSerializeCustomSoapHeaders(writer.InternalWriter); writer.WriteEndElement(); // soap:Header writer.WriteStartElement(XmlNamespace.Soap, XmlElementNames.SOAPBodyElementName); this.WriteBodyToXml(writer); writer.WriteEndElement(); // soap:Body writer.WriteEndElement(); // soap:Envelope writer.Flush(); } /// <summary> /// Write extra headers. /// </summary> /// <param name="writer">The writer</param> internal virtual void WriteExtraCustomSoapHeadersToXml(EwsServiceXmlWriter writer) { // do nothing here. // currently used only by GetUserSettingRequest to emit the BinarySecret header. } /// <summary> /// Writes XML body. /// </summary> /// <param name="writer">The writer.</param> internal void WriteBodyToXml(EwsServiceXmlWriter writer) { writer.WriteStartElement(XmlNamespace.Autodiscover, this.GetRequestXmlElementName()); this.WriteAttributesToXml(writer); this.WriteElementsToXml(writer); writer.WriteEndElement(); // m:this.GetXmlElementName() } /// <summary> /// Gets the response stream (may be wrapped with GZip/Deflate stream to decompress content) /// </summary> /// <param name="response">HttpWebResponse.</param> /// <returns>ResponseStream</returns> protected static Stream GetResponseStream(IEwsHttpWebResponse response) { string contentEncoding = response.ContentEncoding; Stream responseStream = response.GetResponseStream(); if (contentEncoding.ToLowerInvariant().Contains("gzip")) { return new GZipStream(responseStream, CompressionMode.Decompress); } else if (contentEncoding.ToLowerInvariant().Contains("deflate")) { return new DeflateStream(responseStream, CompressionMode.Decompress); } else { return responseStream; } } /// <summary> /// Read SOAP headers. /// </summary> /// <param name="reader">EwsXmlReader</param> internal void ReadSoapHeaders(EwsXmlReader reader) { reader.ReadStartElement(XmlNamespace.Soap, XmlElementNames.SOAPHeaderElementName); do { reader.Read(); this.ReadSoapHeader(reader); } while (!reader.IsEndElement(XmlNamespace.Soap, XmlElementNames.SOAPHeaderElementName)); } /// <summary> /// Reads a single SOAP header. /// </summary> /// <param name="reader">EwsXmlReader</param> internal virtual void ReadSoapHeader(EwsXmlReader reader) { // Is this the ServerVersionInfo? if (reader.IsStartElement(XmlNamespace.Autodiscover, XmlElementNames.ServerVersionInfo)) { this.service.ServerInfo = this.ReadServerVersionInfo(reader); } } /// <summary> /// Read ServerVersionInfo SOAP header. /// </summary> /// <param name="reader">EwsXmlReader</param> private ExchangeServerInfo ReadServerVersionInfo(EwsXmlReader reader) { ExchangeServerInfo serverInfo = new ExchangeServerInfo(); do { reader.Read(); if (reader.IsStartElement()) { switch (reader.LocalName) { case XmlElementNames.MajorVersion: serverInfo.MajorVersion = reader.ReadElementValue<int>(); break; case XmlElementNames.MinorVersion: serverInfo.MinorVersion = reader.ReadElementValue<int>(); break; case XmlElementNames.MajorBuildNumber: serverInfo.MajorBuildNumber = reader.ReadElementValue<int>(); break; case XmlElementNames.MinorBuildNumber: serverInfo.MinorBuildNumber = reader.ReadElementValue<int>(); break; case XmlElementNames.Version: serverInfo.VersionString = reader.ReadElementValue(); break; default: break; } } } while (!reader.IsEndElement(XmlNamespace.Autodiscover, XmlElementNames.ServerVersionInfo)); return serverInfo; } /// <summary> /// Read SOAP body. /// </summary> /// <param name="reader">EwsXmlReader</param> internal AutodiscoverResponse ReadSoapBody(EwsXmlReader reader) { reader.ReadStartElement(XmlNamespace.Soap, XmlElementNames.SOAPBodyElementName); AutodiscoverResponse responses = this.LoadFromXml(reader); reader.ReadEndElement(XmlNamespace.Soap, XmlElementNames.SOAPBodyElementName); return responses; } /// <summary> /// Loads responses from XML. /// </summary> /// <param name="reader">The reader.</param> /// <returns></returns> internal AutodiscoverResponse LoadFromXml(EwsXmlReader reader) { string elementName = this.GetResponseXmlElementName(); reader.ReadStartElement(XmlNamespace.Autodiscover, elementName); AutodiscoverResponse response = this.CreateServiceResponse(); response.LoadFromXml(reader, elementName); return response; } /// <summary> /// Gets the name of the request XML element. /// </summary> /// <returns></returns> internal abstract string GetRequestXmlElementName(); /// <summary> /// Gets the name of the response XML element. /// </summary> /// <returns></returns> internal abstract string GetResponseXmlElementName(); /// <summary> /// Gets the WS-Addressing action name. /// </summary> /// <returns></returns> internal abstract string GetWsAddressingActionName(); /// <summary> /// Creates the service response. /// </summary> /// <returns>AutodiscoverResponse</returns> internal abstract AutodiscoverResponse CreateServiceResponse(); /// <summary> /// Writes attributes to request XML. /// </summary> /// <param name="writer">The writer.</param> internal abstract void WriteAttributesToXml(EwsServiceXmlWriter writer); /// <summary> /// Writes elements to request XML. /// </summary> /// <param name="writer">The writer.</param> internal abstract void WriteElementsToXml(EwsServiceXmlWriter writer); /// <summary> /// Gets the service. /// </summary> internal AutodiscoverService Service { get { return this.service; } } /// <summary> /// Gets the URL. /// </summary> internal Uri Url { get { return this.url; } } } }
// file: Supervised\NeuralNetwork\Network.cs // // summary: Implements the network class using System; using numl.Model; using System.Linq; using numl.Math.Functions; using numl.Math.LinearAlgebra; using System.Collections.Generic; using System.Xml.Serialization; using System.Xml.Schema; using System.Xml; namespace numl.Supervised.NeuralNetwork { /// <summary>A network.</summary> [XmlRoot("Network")] public class Network : IXmlSerializable { /// <summary>Gets or sets the in.</summary> /// <value>The in.</value> public Node[] In { get; set; } /// <summary>Gets or sets the out.</summary> /// <value>The out.</value> public Node[] Out { get; set; } /// <summary>Defaults.</summary> /// <param name="d">The Descriptor to process.</param> /// <param name="x">The Vector to process.</param> /// <param name="y">The Vector to process.</param> /// <param name="activation">The activation.</param> /// <returns>A Network.</returns> public static Network Default(Descriptor d, Matrix x, Vector y, IFunction activation) { Network nn = new Network(); // set output to number of choices of available // 1 if only two choices int distinct = y.Distinct().Count(); int output = distinct > 2 ? distinct : 1; // identity funciton for bias nodes IFunction ident = new Ident(); // set number of hidden units to (Input + Hidden) * 2/3 as basic best guess. int hidden = (int)System.Math.Ceiling((decimal)(x.Cols + output) * 2m / 3m); // creating input nodes nn.In = new Node[x.Cols + 1]; nn.In[0] = new Node { Label = "B0", Activation = ident }; for (int i = 1; i < x.Cols + 1; i++) nn.In[i] = new Node { Label = d.ColumnAt(i - 1), Activation = ident }; // creating hidden nodes Node[] h = new Node[hidden + 1]; h[0] = new Node { Label = "B1", Activation = ident }; for (int i = 1; i < hidden + 1; i++) h[i] = new Node { Label = String.Format("H{0}", i), Activation = activation }; // creating output nodes nn.Out = new Node[output]; for (int i = 0; i < output; i++) nn.Out[i] = new Node { Label = GetLabel(i, d), Activation = activation }; // link input to hidden. Note: there are // no inputs to the hidden bias node for (int i = 1; i < h.Length; i++) for (int j = 0; j < nn.In.Length; j++) Edge.Create(nn.In[j], h[i]); // link from hidden to output (full) for (int i = 0; i < nn.Out.Length; i++) for (int j = 0; j < h.Length; j++) Edge.Create(h[j], nn.Out[i]); return nn; } /// <summary>Gets a label.</summary> /// <param name="n">The Node to process.</param> /// <param name="d">The Descriptor to process.</param> /// <returns>The label.</returns> private static string GetLabel(int n, Descriptor d) { if (d.Label.Type.IsEnum) return Enum.GetName(d.Label.Type, n); else if (d.Label is StringProperty && ((StringProperty)d.Label).AsEnum) return ((StringProperty)d.Label).Dictionary[n]; else return d.Label.Name; } /// <summary>Forwards the given x coordinate.</summary> /// <exception cref="InvalidOperationException">Thrown when the requested operation is invalid.</exception> /// <param name="x">The Vector to process.</param> public void Forward(Vector x) { if (In.Length != x.Length + 1) throw new InvalidOperationException("Input nodes not aligned to input vector"); // set input for (int i = 0; i < In.Length; i++) In[i].Input = In[i].Output = i == 0 ? 1 : x[i - 1]; // evaluate for (int i = 0; i < Out.Length; i++) Out[i].Evaluate(); } /// <summary>Backs.</summary> /// <param name="t">The double to process.</param> /// <param name="learningRate">The learning rate.</param> public void Back(double t, double learningRate) { // propagate error gradients for (int i = 0; i < In.Length; i++) In[i].Error(t); // reset weights for (int i = 0; i < Out.Length; i++) Out[i].Update(learningRate); } /// <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> public XmlSchema GetSchema() { return null; } /// <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) { XmlSerializer nSerializer = new XmlSerializer(typeof(Node)); XmlSerializer eSerializer = new XmlSerializer(typeof(Edge)); reader.MoveToContent(); Dictionary<string, Node> nodes = new Dictionary<string, Node>(); int length = 0; reader.ReadStartElement(); length = int.Parse(reader.GetAttribute("Length")); reader.ReadStartElement("Nodes"); for (int i = 0; i < length; i++) { var node = (Node)nSerializer.Deserialize(reader); nodes.Add(node.Id, node); reader.Read(); } reader.ReadEndElement(); length = int.Parse(reader.GetAttribute("Length")); reader.ReadStartElement("Edges"); for (int i = 0; i < length; i++) { var edge = (Edge)eSerializer.Deserialize(reader); reader.Read(); edge.Source = nodes[edge.SourceId]; edge.Target = nodes[edge.TargetId]; edge.Source.Out.Add(edge); edge.Target.In.Add(edge); } reader.ReadEndElement(); length = int.Parse(reader.GetAttribute("Length")); reader.ReadStartElement("In"); In = new Node[length]; for (int i = 0; i < length; i++) { reader.MoveToContent(); In[i] = nodes[reader.GetAttribute("Id")]; reader.Read(); } reader.ReadEndElement(); length = int.Parse(reader.GetAttribute("Length")); reader.ReadStartElement("Out"); Out = new Node[length]; for (int i = 0; i < length; i++) { reader.MoveToContent(); Out[i] = nodes[reader.GetAttribute("Id")]; reader.Read(); } reader.ReadEndElement(); } /// <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) { XmlSerializer nSerializer = new XmlSerializer(typeof(Node)); XmlSerializer eSerializer = new XmlSerializer(typeof(Edge)); var nodes = GetNodes().ToArray(); writer.WriteStartElement("Nodes"); writer.WriteAttributeString("Length", nodes.Length.ToString()); foreach (var node in nodes) nSerializer.Serialize(writer, node); writer.WriteEndElement(); var edges = GetEdges().ToArray(); writer.WriteStartElement("Edges"); writer.WriteAttributeString("Length", edges.Length.ToString()); foreach (var edge in edges) eSerializer.Serialize(writer, edge); writer.WriteEndElement(); writer.WriteStartElement("In"); writer.WriteAttributeString("Length", In.Length.ToString()); for (int i = 0; i < In.Length; i++) { writer.WriteStartElement("Node"); writer.WriteAttributeString("Id", In[i].Id); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteStartElement("Out"); writer.WriteAttributeString("Length", Out.Length.ToString()); for (int i = 0; i < Out.Length; i++) { writer.WriteStartElement("Node"); writer.WriteAttributeString("Id", Out[i].Id); writer.WriteEndElement(); } writer.WriteEndElement(); } /// <summary>The nodes.</summary> private HashSet<string> _nodes; /// <summary>Gets the nodes in this collection.</summary> /// <returns> /// An enumerator that allows foreach to be used to process the nodes in this collection. /// </returns> public IEnumerable<Node> GetNodes() { if (_nodes == null) _nodes = new HashSet<string>(); else _nodes.Clear(); foreach (var node in Out) { _nodes.Add(node.Id); yield return node; foreach (var n in GetNodes(node)) { if (!_nodes.Contains(n.Id)) { _nodes.Add(n.Id); yield return n; } } } } /// <summary>Gets the nodes in this collection.</summary> /// <param name="n">The Node to process.</param> /// <returns> /// An enumerator that allows foreach to be used to process the nodes in this collection. /// </returns> private IEnumerable<Node> GetNodes(Node n) { foreach (var edge in n.In) { yield return edge.Source; foreach (var node in GetNodes(edge.Source)) yield return node; } } /// <summary>The edges.</summary> private HashSet<Tuple<string, string>> _edges; /// <summary>Gets the edges in this collection.</summary> /// <returns> /// An enumerator that allows foreach to be used to process the edges in this collection. /// </returns> public IEnumerable<Edge> GetEdges() { if (_edges == null) _edges = new HashSet<Tuple<string, string>>(); else _edges.Clear(); foreach (var node in Out) { foreach (var edge in GetEdges(node)) { var key = new Tuple<string, string>(edge.Source.Id, edge.Target.Id); if (!_edges.Contains(key)) { _edges.Add(key); yield return edge; } } } } /// <summary>Gets the edges in this collection.</summary> /// <param name="n">The Node to process.</param> /// <returns> /// An enumerator that allows foreach to be used to process the edges in this collection. /// </returns> private IEnumerable<Edge> GetEdges(Node n) { foreach (var edge in n.In) { yield return edge; foreach (var e in GetEdges(edge.Source)) yield return e; } } } }
using System; using System.Collections.Generic; using System.ComponentModel.Design; using System.IO; using EnvDTE; using Microsoft.VisualStudio.Shell.Design; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Spark.FileSystem; namespace SparkSense.Parsing { public class ProjectExplorer : IProjectExplorer { private readonly ISparkServiceProvider _services; private ITypeDiscoveryService _discovery; private IVsHierarchy _hier; private IEnumerable<Type> _projectReferencedTypes; private CachingViewFolder _projectViewFolder; public ProjectExplorer(ISparkServiceProvider services) { if (services == null) throw new ArgumentNullException("services", "services is null."); _services = services; InitTypes(); } private void InitTypes() { InitTypeDiscoveryService(); GetProjectReferencedTypes(); } private CachingViewFolder ProjectViewFolder { get { string activeDocumentPath; if (!TryGetActiveDocumentPath(out activeDocumentPath)) return null; if (_projectViewFolder == null || _projectViewFolder.BasePath != GetViewRoot(activeDocumentPath)) { _hier = null; _discovery = null; _projectReferencedTypes = null; _projectViewFolder = new CachingViewFolder(GetViewRoot(activeDocumentPath) ?? string.Empty); InitTypes(); BuildViewMapFromProjectEnvironment(); } return _projectViewFolder; } } #region IProjectExplorer Members public bool ViewFolderExists() { string activeDocumentPath; if (!TryGetActiveDocumentPath(out activeDocumentPath)) return false; int viewsLocationStart = activeDocumentPath.LastIndexOf("Views"); return viewsLocationStart != -1; } public IViewFolder GetViewFolder() { string activeDocumentPath; if (!TryGetActiveDocumentPath(out activeDocumentPath)) return null; return ProjectViewFolder; } public IViewExplorer GetViewExplorer(ITextBuffer textBuffer) { IViewExplorer viewExplorer; if (textBuffer.Properties.TryGetProperty(typeof (ViewExplorer), out viewExplorer)) return viewExplorer; viewExplorer = new ViewExplorer(this, GetCurrentViewPath(textBuffer)); textBuffer.Properties.AddProperty(typeof (ViewExplorer), viewExplorer); return viewExplorer; } public string GetCurrentViewPath(ITextBuffer textBuffer) { var adapter = _services.AdaptersFactoryService.GetBufferAdapter(textBuffer) as IPersistFileFormat; if (adapter == null) return string.Empty; string filename; uint format; adapter.GetCurFile(out filename, out format); return GetViewPath(filename); } public void SetViewContent(string viewPath, string content) { ProjectViewFolder.SetViewSource(viewPath, content); } public IEnumerable<Type> GetProjectReferencedTypes() { if (_projectReferencedTypes != null) return _projectReferencedTypes; try { _projectReferencedTypes = _discovery.GetTypes(typeof (object), true) as IEnumerable<Type>; } catch (NullReferenceException) { //Type Discovery service isn't ready yet. } catch (Exception) { throw; } return _projectReferencedTypes; } #endregion public string GetCurrentViewPath() { string activeDocumentPath; if (!TryGetActiveDocumentPath(out activeDocumentPath)) return null; return GetViewPath(activeDocumentPath); } public bool HasView(string viewPath) { return ProjectViewFolder.HasView(viewPath); } private bool TryGetActiveDocumentPath(out string activeDocumentPath) { activeDocumentPath = _services.VsEnvironment.ActiveDocument != null ? _services.VsEnvironment.ActiveDocument.FullName : string.Empty; return !String.IsNullOrEmpty(activeDocumentPath); } private void BuildViewMapFromProjectEnvironment() { if (_services.VsEnvironment.ActiveDocument == null) return; Project currentProject = _services.VsEnvironment.ActiveDocument.ProjectItem.ContainingProject; foreach (ProjectItem projectItem in currentProject.ProjectItems) ScanProjectItemForViews(projectItem); } private void ScanProjectItemForViews(ProjectItem projectItem) { if (projectItem.Name.EndsWith(".spark")) { string projectItemMap = GetProjectItemMap(projectItem); if (!string.IsNullOrEmpty(projectItemMap)) ProjectViewFolder.Add(projectItemMap); } if (projectItem.ProjectItems != null) foreach (ProjectItem child in projectItem.ProjectItems) ScanProjectItemForViews(child); } private string GetProjectItemMap(ProjectItem projectItem) { if (projectItem.Properties == null) return null; string fullPath = projectItem.Properties.Item("FullPath").Value.ToString(); var foundView = GetViewPath(fullPath); return foundView; } private string GetViewPath(string fullPath) { string viewRoot = GetViewRoot(fullPath); if(string.IsNullOrEmpty(viewRoot)) return fullPath; return fullPath.Replace(viewRoot, string.Empty).TrimStart('\\'); } private string GetViewRoot(string activeDocumentPath) { int viewsLocationStart = activeDocumentPath.LastIndexOf("Views"); return viewsLocationStart != -1 ? activeDocumentPath.Substring(0, viewsLocationStart + 5) : GetProjectRoot(); } private string GetProjectRoot() { var projectFileName = _services.VsEnvironment.ActiveDocument.ProjectItem.ContainingProject.FullName; return Path.GetDirectoryName(projectFileName); } private IVsHierarchy GetHierarchy() { if (_hier == null) { var sln = _services.GetService<IVsSolution>(); if (_services.VsEnvironment.ActiveDocument != null) { string projectName = _services.VsEnvironment.ActiveDocument.ProjectItem.ContainingProject.UniqueName; sln.GetProjectOfUniqueName(projectName, out _hier); } } return _hier; } private void InitTypeDiscoveryService() { if (_discovery != null) return; DynamicTypeService typeService = _services.TypeService; if (typeService != null) _discovery = typeService.GetTypeDiscoveryService(GetHierarchy()); } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using FluentAssertions; using Microsoft.Build.Construction; using Microsoft.DotNet.Cli.Sln.Internal; using Microsoft.DotNet.Tools.Test.Utilities; using System; using System.IO; using System.Linq; using Xunit; using Xunit.Abstractions; namespace Microsoft.DotNet.Cli.Sln.Add.Tests { public class GivenDotnetSlnAdd : TestBase { private string HelpText = @".NET Add project(s) to a solution file Command Usage: dotnet sln <SLN_FILE> add [options] <args> Arguments: <SLN_FILE> Solution file to operate on. If not specified, the command will search the current directory for one. <args> Add one or more specified projects to the solution. Options: -h, --help Show help information "; private ITestOutputHelper _output; public GivenDotnetSlnAdd(ITestOutputHelper output) { _output = output; } private const string ExpectedSlnFileAfterAddingLibProj = @" Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26006.2 MinimumVisualStudioVersion = 10.0.40219.1 Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""App"", ""App\App.csproj"", ""{7072A694-548F-4CAE-A58F-12D257D5F486}"" EndProject Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""Lib"", ""Lib\Lib.csproj"", ""__LIB_PROJECT_GUID__"" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.Build.0 = Debug|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.ActiveCfg = Debug|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.Build.0 = Debug|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.ActiveCfg = Debug|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.Build.0 = Debug|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.ActiveCfg = Release|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.Build.0 = Release|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.ActiveCfg = Release|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.Build.0 = Release|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.ActiveCfg = Release|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.Build.0 = Release|x86 __LIB_PROJECT_GUID__.Debug|Any CPU.ActiveCfg = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|Any CPU.Build.0 = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|x64.ActiveCfg = Debug|x64 __LIB_PROJECT_GUID__.Debug|x64.Build.0 = Debug|x64 __LIB_PROJECT_GUID__.Debug|x86.ActiveCfg = Debug|x86 __LIB_PROJECT_GUID__.Debug|x86.Build.0 = Debug|x86 __LIB_PROJECT_GUID__.Release|Any CPU.ActiveCfg = Release|Any CPU __LIB_PROJECT_GUID__.Release|Any CPU.Build.0 = Release|Any CPU __LIB_PROJECT_GUID__.Release|x64.ActiveCfg = Release|x64 __LIB_PROJECT_GUID__.Release|x64.Build.0 = Release|x64 __LIB_PROJECT_GUID__.Release|x86.ActiveCfg = Release|x86 __LIB_PROJECT_GUID__.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal "; private const string ExpectedSlnFileAfterAddingLibProjToEmptySln = @" Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26006.2 MinimumVisualStudioVersion = 10.0.40219.1 Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""Lib"", ""Lib\Lib.csproj"", ""__LIB_PROJECT_GUID__"" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution __LIB_PROJECT_GUID__.Debug|Any CPU.ActiveCfg = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|Any CPU.Build.0 = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|x64.ActiveCfg = Debug|x64 __LIB_PROJECT_GUID__.Debug|x64.Build.0 = Debug|x64 __LIB_PROJECT_GUID__.Debug|x86.ActiveCfg = Debug|x86 __LIB_PROJECT_GUID__.Debug|x86.Build.0 = Debug|x86 __LIB_PROJECT_GUID__.Release|Any CPU.ActiveCfg = Release|Any CPU __LIB_PROJECT_GUID__.Release|Any CPU.Build.0 = Release|Any CPU __LIB_PROJECT_GUID__.Release|x64.ActiveCfg = Release|x64 __LIB_PROJECT_GUID__.Release|x64.Build.0 = Release|x64 __LIB_PROJECT_GUID__.Release|x86.ActiveCfg = Release|x86 __LIB_PROJECT_GUID__.Release|x86.Build.0 = Release|x86 EndGlobalSection EndGlobal "; private const string ExpectedSlnFileAfterAddingNestedProj = @" Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26006.2 MinimumVisualStudioVersion = 10.0.40219.1 Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""App"", ""App.csproj"", ""{7072A694-548F-4CAE-A58F-12D257D5F486}"" EndProject Project(""{2150E333-8FDC-42A3-9474-1A3956D46DE8}"") = ""src"", ""src"", ""__SRC_FOLDER_GUID__"" EndProject Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""Lib"", ""src\Lib\Lib.csproj"", ""__LIB_PROJECT_GUID__"" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.Build.0 = Debug|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.ActiveCfg = Debug|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.Build.0 = Debug|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.ActiveCfg = Debug|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.Build.0 = Debug|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.ActiveCfg = Release|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.Build.0 = Release|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.ActiveCfg = Release|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.Build.0 = Release|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.ActiveCfg = Release|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.Build.0 = Release|x86 __LIB_PROJECT_GUID__.Debug|Any CPU.ActiveCfg = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|Any CPU.Build.0 = Debug|Any CPU __LIB_PROJECT_GUID__.Debug|x64.ActiveCfg = Debug|x64 __LIB_PROJECT_GUID__.Debug|x64.Build.0 = Debug|x64 __LIB_PROJECT_GUID__.Debug|x86.ActiveCfg = Debug|x86 __LIB_PROJECT_GUID__.Debug|x86.Build.0 = Debug|x86 __LIB_PROJECT_GUID__.Release|Any CPU.ActiveCfg = Release|Any CPU __LIB_PROJECT_GUID__.Release|Any CPU.Build.0 = Release|Any CPU __LIB_PROJECT_GUID__.Release|x64.ActiveCfg = Release|x64 __LIB_PROJECT_GUID__.Release|x64.Build.0 = Release|x64 __LIB_PROJECT_GUID__.Release|x86.ActiveCfg = Release|x86 __LIB_PROJECT_GUID__.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution __LIB_PROJECT_GUID__ = __SRC_FOLDER_GUID__ EndGlobalSection EndGlobal "; [Theory] [InlineData("--help")] [InlineData("-h")] [InlineData("-?")] [InlineData("/?")] public void WhenHelpOptionIsPassedItPrintsUsage(string helpArg) { var cmd = new DotnetCommand() .ExecuteWithCapturedOutput($"sln add {helpArg}"); cmd.Should().Pass(); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Theory] [InlineData("")] [InlineData("unknownCommandName")] public void WhenNoCommandIsPassedItPrintsError(string commandName) { var cmd = new DotnetCommand() .ExecuteWithCapturedOutput($"sln {commandName}"); cmd.Should().Fail(); cmd.StdErr.Should().Be("Required command was not provided."); } [Fact] public void WhenTooManyArgumentsArePassedItPrintsError() { var cmd = new DotnetCommand() .ExecuteWithCapturedOutput("sln one.sln two.sln three.sln add"); cmd.Should().Fail(); cmd.StdErr.Should().BeVisuallyEquivalentTo("Unrecognized command or argument 'two.sln'\r\nUnrecognized command or argument 'three.sln'\r\nYou must specify at least one project to add."); } [Theory] [InlineData("idontexist.sln")] [InlineData("ihave?invalidcharacters")] [InlineData("ihaveinv@lidcharacters")] [InlineData("ihaveinvalid/characters")] [InlineData("ihaveinvalidchar\\acters")] public void WhenNonExistingSolutionIsPassedItPrintsErrorAndUsage(string solutionName) { var cmd = new DotnetCommand() .ExecuteWithCapturedOutput($"sln {solutionName} add p.csproj"); cmd.Should().Fail(); cmd.StdErr.Should().Be($"Could not find solution or directory `{solutionName}`."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenInvalidSolutionIsPassedItPrintsErrorAndUsage() { var projectDirectory = TestAssets .Get("InvalidSolution") .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = Path.Combine("Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln InvalidSolution.sln add {projectToAdd}"); cmd.Should().Fail(); cmd.StdErr.Should().Be("Invalid solution `InvalidSolution.sln`. Invalid format in line 1: File header is missing"); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenInvalidSolutionIsFoundItPrintsErrorAndUsage() { var projectDirectory = TestAssets .Get("InvalidSolution") .CreateInstance() .WithSourceFiles() .Root .FullName; var solutionPath = Path.Combine(projectDirectory, "InvalidSolution.sln"); var projectToAdd = Path.Combine("Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln add {projectToAdd}"); cmd.Should().Fail(); cmd.StdErr.Should().Be($"Invalid solution `{solutionPath}`. Invalid format in line 1: File header is missing"); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenNoProjectIsPassedItPrintsErrorAndUsage() { var projectDirectory = TestAssets .Get("TestAppWithSlnAndCsprojFiles") .CreateInstance() .WithSourceFiles() .Root .FullName; var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput(@"sln App.sln add"); cmd.Should().Fail(); cmd.StdErr.Should().Be("You must specify at least one project to add."); _output.WriteLine("[STD OUT]"); _output.WriteLine(cmd.StdOut); _output.WriteLine("[HelpText]"); _output.WriteLine(HelpText); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenNoSolutionExistsInTheDirectoryItPrintsErrorAndUsage() { var projectDirectory = TestAssets .Get("TestAppWithSlnAndCsprojFiles") .CreateInstance() .WithSourceFiles() .Root .FullName; var solutionPath = Path.Combine(projectDirectory, "App"); var cmd = new DotnetCommand() .WithWorkingDirectory(solutionPath) .ExecuteWithCapturedOutput(@"sln add App.csproj"); cmd.Should().Fail(); cmd.StdErr.Should().Be($"Specified solution file {solutionPath + Path.DirectorySeparatorChar} does not exist, or there is no solution file in the directory."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenMoreThanOneSolutionExistsInTheDirectoryItPrintsErrorAndUsage() { var projectDirectory = TestAssets .Get("TestAppWithMultipleSlnFiles") .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = Path.Combine("Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln add {projectToAdd}"); cmd.Should().Fail(); cmd.StdErr.Should().Be($"Found more than one solution file in {projectDirectory + Path.DirectorySeparatorChar}. Please specify which one to use."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenNestedProjectIsAddedSolutionFoldersAreCreated() { var projectDirectory = TestAssets .Get("TestAppWithSlnAndCsprojInSubDir") .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = Path.Combine("src", "Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); var slnPath = Path.Combine(projectDirectory, "App.sln"); var expectedSlnContents = GetExpectedSlnContents(slnPath, ExpectedSlnFileAfterAddingNestedProj); File.ReadAllText(slnPath) .Should().BeVisuallyEquivalentTo(expectedSlnContents); } [Fact] public void WhenProjectDirectoryIsAddedSolutionFoldersAreNotCreated() { var projectDirectory = TestAssets .Get("TestAppWithSlnAndCsprojFiles") .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = Path.Combine("Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); var slnFile = SlnFile.Read(Path.Combine(projectDirectory, "App.sln")); var solutionFolderProjects = slnFile.Projects.Where( p => p.TypeGuid == ProjectTypeGuids.SolutionFolderGuid); solutionFolderProjects.Count().Should().Be(0); slnFile.Sections.GetSection("NestedProjects").Should().BeNull(); } [Theory] [InlineData(".")] [InlineData("")] public void WhenSolutionFolderExistsItDoesNotGetAdded(string firstComponent) { var projectDirectory = TestAssets .Get("TestAppWithSlnAndSolutionFolders") .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = Path.Combine($"{firstComponent}", "src", "src", "Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); var slnFile = SlnFile.Read(Path.Combine(projectDirectory, "App.sln")); slnFile.Projects.Count().Should().Be(4); var solutionFolderProjects = slnFile.Projects.Where( p => p.TypeGuid == ProjectTypeGuids.SolutionFolderGuid); solutionFolderProjects.Count().Should().Be(2); var solutionFolders = slnFile.Sections.GetSection("NestedProjects").Properties; solutionFolders.Count.Should().Be(3); solutionFolders["{DDF3765C-59FB-4AA6-BE83-779ED13AA64A}"] .Should().Be("{72BFCA87-B033-4721-8712-4D12166B4A39}"); var newlyAddedSrcFolder = solutionFolderProjects.Where( p => p.Id != "{72BFCA87-B033-4721-8712-4D12166B4A39}").Single(); solutionFolders[newlyAddedSrcFolder.Id] .Should().Be("{72BFCA87-B033-4721-8712-4D12166B4A39}"); var libProject = slnFile.Projects.Where(p => p.Name == "Lib").Single(); solutionFolders[libProject.Id] .Should().Be(newlyAddedSrcFolder.Id); } [Theory] [InlineData("TestAppWithSlnAndCsprojFiles", ExpectedSlnFileAfterAddingLibProj, "")] [InlineData("TestAppWithSlnAndCsprojProjectGuidFiles", ExpectedSlnFileAfterAddingLibProj, "{84A45D44-B677-492D-A6DA-B3A71135AB8E}")] [InlineData("TestAppWithEmptySln", ExpectedSlnFileAfterAddingLibProjToEmptySln, "")] public void WhenValidProjectIsPassedBuildConfigsAreAdded( string testAsset, string expectedSlnContentsTemplate, string expectedProjectGuid) { var projectDirectory = TestAssets .Get(testAsset) .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = "Lib/Lib.csproj"; var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); var slnPath = Path.Combine(projectDirectory, "App.sln"); var expectedSlnContents = GetExpectedSlnContents( slnPath, expectedSlnContentsTemplate, expectedProjectGuid); File.ReadAllText(slnPath) .Should().BeVisuallyEquivalentTo(expectedSlnContents); } [Theory] [InlineData("TestAppWithSlnAndCsprojFiles")] [InlineData("TestAppWithSlnAndCsprojProjectGuidFiles")] [InlineData("TestAppWithEmptySln")] public void WhenValidProjectIsPassedItGetsAdded(string testAsset) { var projectDirectory = TestAssets .Get(testAsset) .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = "Lib/Lib.csproj"; var projectPath = Path.Combine("Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); cmd.StdOut.Should().Be($"Project `{projectPath}` added to the solution."); cmd.StdErr.Should().BeEmpty(); } [Theory] [InlineData("TestAppWithSlnAndCsprojFiles")] [InlineData("TestAppWithSlnAndCsprojProjectGuidFiles")] [InlineData("TestAppWithEmptySln")] public void WhenValidProjectIsPassedTheSlnBuilds(string testAsset) { var projectDirectory = TestAssets .Get(testAsset) .CreateInstance() .WithSourceFiles() .Root .FullName; var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput(@"sln App.sln add App/App.csproj Lib/Lib.csproj"); cmd.Should().Pass(); var slnPath = Path.Combine(projectDirectory, "App.sln"); new DotnetCommand() .WithWorkingDirectory(projectDirectory) .Execute($"restore App.sln") .Should().Pass(); new DotnetCommand() .WithWorkingDirectory(projectDirectory) .Execute("build App.sln --configuration Release") .Should().Pass(); var reasonString = "should be built in release mode, otherwise it means build configurations are missing from the sln file"; var appReleaseDirectory = Directory.EnumerateDirectories( Path.Combine(projectDirectory, "App", "bin"), "Release", SearchOption.AllDirectories); appReleaseDirectory.Count().Should().Be(1, $"App {reasonString}"); Directory.EnumerateFiles(appReleaseDirectory.Single(), "App.dll", SearchOption.AllDirectories) .Count().Should().Be(1, $"App {reasonString}"); var libReleaseDirectory = Directory.EnumerateDirectories( Path.Combine(projectDirectory, "Lib", "bin"), "Release", SearchOption.AllDirectories); libReleaseDirectory.Count().Should().Be(1, $"Lib {reasonString}"); Directory.EnumerateFiles(libReleaseDirectory.Single(), "Lib.dll", SearchOption.AllDirectories) .Count().Should().Be(1, $"Lib {reasonString}"); } [Theory] [InlineData("TestAppWithSlnAndExistingCsprojReferences")] [InlineData("TestAppWithSlnAndExistingCsprojReferencesWithEscapedDirSep")] public void WhenSolutionAlreadyContainsProjectItDoesntDuplicate(string testAsset) { var projectDirectory = TestAssets .Get(testAsset) .CreateInstance() .WithSourceFiles() .Root .FullName; var solutionPath = Path.Combine(projectDirectory, "App.sln"); var projectToAdd = Path.Combine("Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); cmd.StdOut.Should().Be($"Solution {solutionPath} already contains project {projectToAdd}."); cmd.StdErr.Should().BeEmpty(); } [Fact] public void WhenPassedMultipleProjectsAndOneOfthemDoesNotExistItCancelsWholeOperation() { var projectDirectory = TestAssets .Get("TestAppWithSlnAndCsprojFiles") .CreateInstance() .WithSourceFiles() .Root .FullName; var slnFullPath = Path.Combine(projectDirectory, "App.sln"); var contentBefore = File.ReadAllText(slnFullPath); var projectToAdd = Path.Combine("Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd} idonotexist.csproj"); cmd.Should().Fail(); cmd.StdErr.Should().Be("Project `idonotexist.csproj` does not exist."); File.ReadAllText(slnFullPath) .Should().BeVisuallyEquivalentTo(contentBefore); } //ISSUE: https://github.com/dotnet/sdk/issues/522 //[Fact] public void WhenPassedAnUnknownProjectTypeItFails() { var projectDirectory = TestAssets .Get("SlnFileWithNoProjectReferencesAndUnknownProject") .CreateInstance() .WithSourceFiles() .Root .FullName; var slnFullPath = Path.Combine(projectDirectory, "App.sln"); var contentBefore = File.ReadAllText(slnFullPath); var projectToAdd = Path.Combine("UnknownProject", "UnknownProject.unknownproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Fail(); cmd.StdErr.Should().BeVisuallyEquivalentTo("Unsupported project type. Please check with your sdk provider."); File.ReadAllText(slnFullPath) .Should().BeVisuallyEquivalentTo(contentBefore); } [Theory] //ISSUE: https://github.com/dotnet/sdk/issues/522 //[InlineData("SlnFileWithNoProjectReferencesAndCSharpProject", "CSharpProject", "CSharpProject.csproj", ProjectTypeGuids.CSharpProjectTypeGuid)] //[InlineData("SlnFileWithNoProjectReferencesAndFSharpProject", "FSharpProject", "FSharpProject.fsproj", "{F2A71F9B-5D33-465A-A702-920D77279786}")] //[InlineData("SlnFileWithNoProjectReferencesAndVBProject", "VBProject", "VBProject.vbproj", "{F184B08F-C81C-45F6-A57F-5ABD9991F28F}")] [InlineData("SlnFileWithNoProjectReferencesAndUnknownProjectWithSingleProjectTypeGuid", "UnknownProject", "UnknownProject.unknownproj", "{130159A9-F047-44B3-88CF-0CF7F02ED50F}")] [InlineData("SlnFileWithNoProjectReferencesAndUnknownProjectWithMultipleProjectTypeGuids", "UnknownProject", "UnknownProject.unknownproj", "{130159A9-F047-44B3-88CF-0CF7F02ED50F}")] public void WhenPassedAProjectItAddsCorrectProjectTypeGuid( string testAsset, string projectDir, string projectName, string expectedTypeGuid) { var projectDirectory = TestAssets .Get(testAsset) .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = Path.Combine(projectDir, projectName); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); cmd.StdOut.Should().Be($"Project `{projectToAdd}` added to the solution."); cmd.StdErr.Should().BeEmpty(); var slnFile = SlnFile.Read(Path.Combine(projectDirectory, "App.sln")); var nonSolutionFolderProjects = slnFile.Projects.Where( p => p.TypeGuid != ProjectTypeGuids.SolutionFolderGuid); nonSolutionFolderProjects.Count().Should().Be(1); nonSolutionFolderProjects.Single().TypeGuid.Should().Be(expectedTypeGuid); } [Fact] private void WhenSlnContainsSolutionFolderWithDifferentCasingItDoesNotCreateDuplicate() { var projectDirectory = TestAssets .Get("TestAppWithSlnAndCaseSensitiveSolutionFolders") .CreateInstance() .WithSourceFiles() .Root .FullName; var projectToAdd = Path.Combine("src", "Lib", "Lib.csproj"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .Execute($"sln App.sln add {projectToAdd}"); cmd.Should().Pass(); var slnFile = SlnFile.Read(Path.Combine(projectDirectory, "App.sln")); var solutionFolderProjects = slnFile.Projects.Where( p => p.TypeGuid == ProjectTypeGuids.SolutionFolderGuid); solutionFolderProjects.Count().Should().Be(1); } private string GetExpectedSlnContents( string slnPath, string slnTemplate, string expectedLibProjectGuid = null) { var slnFile = SlnFile.Read(slnPath); if (string.IsNullOrEmpty(expectedLibProjectGuid)) { var matchingProjects = slnFile.Projects .Where((p) => p.FilePath.EndsWith("Lib.csproj")) .ToList(); matchingProjects.Count.Should().Be(1); var slnProject = matchingProjects[0]; expectedLibProjectGuid = slnProject.Id; } var slnContents = slnTemplate.Replace("__LIB_PROJECT_GUID__", expectedLibProjectGuid); var matchingSrcFolder = slnFile.Projects .Where((p) => p.FilePath == "src") .ToList(); if (matchingSrcFolder.Count == 1) { slnContents = slnContents.Replace("__SRC_FOLDER_GUID__", matchingSrcFolder[0].Id); } return slnContents; } } }
// 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.Text; using System.Globalization; /// <summary> /// UInt64.Parse(System.string) /// </summary> public class UInt64Parse1 { public static int Main() { UInt64Parse1 ui64parse1 = new UInt64Parse1(); TestLibrary.TestFramework.BeginTestCase("UInt64Parse1"); if (ui64parse1.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; retVal = NegTest5() && retVal; return retVal; } #region PostiveTest public bool PosTest1() { bool retVal = true; UInt64 uintA; TestLibrary.TestFramework.BeginScenario("PosTest1: the string corresponding UInt64 is UInt64 MinValue "); try { string strA = UInt64.MinValue.ToString(); uintA = UInt64.Parse(strA); if (uintA != 0) { TestLibrary.TestFramework.LogError("001", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; UInt64 uintA; TestLibrary.TestFramework.BeginScenario("PosTest2: the string corresponding UInt64 is UInt64 MaxValue "); try { string strA = UInt64.MaxValue.ToString(); uintA = UInt64.Parse(strA); if (uintA != UInt64.MaxValue) { TestLibrary.TestFramework.LogError("003", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; UInt64 uintA; TestLibrary.TestFramework.BeginScenario("PosTest3: the string corresponding UInt64 is normal UInt64 "); try { UInt64 uintTest = (UInt64)this.GetInt64(0, UInt64.MaxValue); string strA = uintTest.ToString(); uintA = UInt64.Parse(strA); if (uintA != uintTest) { TestLibrary.TestFramework.LogError("005", "the ActualResult is not the ExpectResult,The UInt64 is:" + uintTest); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; UInt64 uintA; TestLibrary.TestFramework.BeginScenario("PosTest4: the string format is [ws][sign]digits[ws] 1"); try { UInt64 uintTest = (UInt64)this.GetInt64(0, UInt64.MaxValue); string strA = "+" + uintTest.ToString(); uintA = UInt64.Parse(strA); if (uintA != uintTest) { TestLibrary.TestFramework.LogError("007", "the ActualResult is not the ExpectResult,UInt64 is:" + uintTest); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; UInt64 uintA; TestLibrary.TestFramework.BeginScenario("PosTest5: the string format is [ws][sign]digits[ws] 2"); try { UInt64 uintTest = (UInt64)this.GetInt64(0, UInt64.MaxValue); string strA = "\u0020" + uintTest.ToString(); uintA = UInt64.Parse(strA); if (uintA != uintTest) { TestLibrary.TestFramework.LogError("009", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; UInt64 uintA; TestLibrary.TestFramework.BeginScenario("PosTest6: the string format is [ws][sign]digits[ws] 3"); try { UInt64 uintTest = (UInt64)this.GetInt64(0, UInt64.MaxValue); string strA = uintTest.ToString() + "\u0020"; uintA = UInt64.Parse(strA); if (uintA != uintTest) { TestLibrary.TestFramework.LogError("011", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; UInt64 uintA; TestLibrary.TestFramework.BeginScenario("PosTest7: the string format is [ws][sign]digits[ws] 4"); try { UInt64 uintTest = (UInt64)this.GetInt64(0, UInt64.MaxValue); string strA = "\u0009" + "+" + uintTest.ToString() + "\u0020"; uintA = UInt64.Parse(strA); if (uintA != uintTest) { TestLibrary.TestFramework.LogError("013", "the ActualResult is not the ExpectResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region NegativeTest public bool NegTest1() { bool retVal = true; UInt64 uintA; TestLibrary.TestFramework.BeginScenario("NegTest1: the parameter string is null"); try { string strA = null; uintA = UInt64.Parse(strA); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N001", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; UInt64 uintA; TestLibrary.TestFramework.BeginScenario("NegTest2: the parameter string is not of the correct format 1"); try { string strA = "abcd"; uintA = UInt64.Parse(strA); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; UInt64 uintA; TestLibrary.TestFramework.BeginScenario("NegTest3: the parameter string is not of the correct format 2"); try { string strA = "b12345d"; uintA = UInt64.Parse(strA); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N003", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; UInt64 uintA; TestLibrary.TestFramework.BeginScenario("NegTest4: the parameter string corresponding number is less than UInt64 minValue"); try { Int64 Testint = (-1) * Convert.ToInt64(this.GetInt64(1, Int64.MaxValue)); string strA = Testint.ToString(); uintA = UInt64.Parse(strA); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest5() { bool retVal = true; UInt64 uintA; TestLibrary.TestFramework.BeginScenario("NegTest5: the parameter string corresponding number is larger than UInt64 maxValue"); try { string strA = "18446744073709551616"; uintA = UInt64.Parse(strA); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N005", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region ForTestObject private UInt64 GetInt64(UInt64 minValue, UInt64 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + (UInt64)TestLibrary.Generator.GetInt64(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } #endregion }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace ClosedXML.Excel { using System.Linq; internal class XLCells : IXLCells, IXLStylized, IEnumerable<XLCell> { public Boolean StyleChanged { get; set; } #region Fields private readonly bool _includeFormats; private readonly List<XLRangeAddress> _rangeAddresses = new List<XLRangeAddress>(); private readonly bool _usedCellsOnly; private IXLStyle _style; private readonly Func<IXLCell, Boolean> _predicate; #endregion #region Constructor public XLCells(bool usedCellsOnly, bool includeFormats, Func<IXLCell, Boolean> predicate = null) { _style = new XLStyle(this, XLWorkbook.DefaultStyle); _usedCellsOnly = usedCellsOnly; _includeFormats = includeFormats; _predicate = predicate; } #endregion #region IEnumerable<XLCell> Members public IEnumerator<XLCell> GetEnumerator() { var cellsInRanges = new Dictionary<XLWorksheet, HashSet<XLSheetPoint>>(); Boolean oneRange = _rangeAddresses.Count == 1; foreach (XLRangeAddress range in _rangeAddresses) { HashSet<XLSheetPoint> hash; if (cellsInRanges.ContainsKey(range.Worksheet)) hash = cellsInRanges[range.Worksheet]; else { hash = new HashSet<XLSheetPoint>(); cellsInRanges.Add(range.Worksheet, hash); } if (_usedCellsOnly) { if (oneRange) { var cellRange = range .Worksheet .Internals .CellsCollection .GetCells( range.FirstAddress.RowNumber, range.FirstAddress.ColumnNumber, range.LastAddress.RowNumber, range.LastAddress.ColumnNumber) .Where(c => !c.IsEmpty(_includeFormats) && (_predicate == null || _predicate(c)) ); foreach(var cell in cellRange) { yield return cell; } } else { var tmpRange = range; var addressList = range.Worksheet.Internals.CellsCollection .GetSheetPoints( tmpRange.FirstAddress.RowNumber, tmpRange.FirstAddress.ColumnNumber, tmpRange.LastAddress.RowNumber, tmpRange.LastAddress.ColumnNumber); foreach (XLSheetPoint a in addressList.Where(a => !hash.Contains(a))) { hash.Add(a); } } } else { var mm = new MinMax { MinRow = range.FirstAddress.RowNumber, MaxRow = range.LastAddress.RowNumber, MinColumn = range.FirstAddress.ColumnNumber, MaxColumn = range.LastAddress.ColumnNumber }; if (mm.MaxRow > 0 && mm.MaxColumn > 0) { for (Int32 ro = mm.MinRow; ro <= mm.MaxRow; ro++) { for (Int32 co = mm.MinColumn; co <= mm.MaxColumn; co++) { if (oneRange) { var c = range.Worksheet.Cell(ro, co); if (_predicate == null || _predicate(c)) yield return c; } else { var address = new XLSheetPoint(ro, co); if (!hash.Contains(address)) hash.Add(address); } } } } } } if (!oneRange) { if (_usedCellsOnly) { var cellRange = cellsInRanges .SelectMany( cir => cir.Value.Select(a => cir.Key.Internals.CellsCollection.GetCell(a)).Where( cell => cell != null && !cell.IsEmpty(_includeFormats) && (_predicate == null || _predicate(cell)) ) ); foreach (var cell in cellRange) { yield return cell; } } else { foreach (var cir in cellsInRanges) { foreach (XLSheetPoint a in cir.Value) { var c = cir.Key.Cell(a.Row, a.Column); if (_predicate == null || _predicate(c)) yield return c; } } } } } #endregion #region IXLCells Members IEnumerator<IXLCell> IEnumerable<IXLCell>.GetEnumerator() { foreach (XLCell cell in this) yield return cell; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IXLStyle Style { get { return _style; } set { _style = new XLStyle(this, value); this.ForEach<XLCell>(c => c.Style = _style); } } public Object Value { set { this.ForEach<XLCell>(c => c.Value = value); } } public IXLCells SetDataType(XLCellValues dataType) { this.ForEach<XLCell>(c => c.DataType = dataType); return this; } public XLCellValues DataType { set { this.ForEach<XLCell>(c => c.DataType = value); } } public IXLCells Clear(XLClearOptions clearOptions = XLClearOptions.ContentsAndFormats) { this.ForEach<XLCell>(c => c.Clear(clearOptions)); return this; } public void DeleteComments() { this.ForEach<XLCell>(c => c.DeleteComment()); } public String FormulaA1 { set { this.ForEach<XLCell>(c => c.FormulaA1 = value); } } public String FormulaR1C1 { set { this.ForEach<XLCell>(c => c.FormulaR1C1 = value); } } #endregion #region IXLStylized Members public IEnumerable<IXLStyle> Styles { get { UpdatingStyle = true; yield return _style; foreach (XLCell c in this) yield return c.Style; UpdatingStyle = false; } } public Boolean UpdatingStyle { get; set; } public IXLStyle InnerStyle { get { return _style; } set { _style = new XLStyle(this, value); } } public IXLRanges RangesUsed { get { var retVal = new XLRanges(); this.ForEach<XLCell>(c => retVal.Add(c.AsRange())); return retVal; } } #endregion public void Add(XLRangeAddress rangeAddress) { _rangeAddresses.Add(rangeAddress); } public void Add(XLCell cell) { _rangeAddresses.Add(new XLRangeAddress(cell.Address, cell.Address)); } //-- #region Nested type: MinMax private struct MinMax { public Int32 MaxColumn; public Int32 MaxRow; public Int32 MinColumn; public Int32 MinRow; } #endregion public void Select() { foreach (var cell in this) cell.Select(); } } }